Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
07031f58a0 | ||
|
|
3151897a9a | ||
|
|
103ead0fe5 | ||
|
|
f0902f5f20 | ||
|
|
1876e8a8f2 | ||
|
|
627e17e0f2 | ||
|
|
af1e11c018 | ||
|
|
908286c1df | ||
|
|
5aef332026 | ||
|
|
c917df13cc | ||
|
|
d293bb47a4 | ||
|
|
97eaed1066 | ||
|
|
53201ba4e1 | ||
|
|
71f9879f68 | ||
|
|
3261b6ebdb | ||
|
|
61123ad550 | ||
|
|
02b197c119 | ||
|
|
aa58dd7f6f | ||
|
|
b043cb614e | ||
|
|
fec25bff8a | ||
|
|
c56460716f | ||
|
|
8531530ccd | ||
|
|
b605d7c2bb | ||
|
|
7ec369f77e | ||
|
|
f333c7f1fb | ||
|
|
c8d9e409c6 | ||
|
|
c74fdda7da | ||
|
|
c507879896 | ||
|
|
f6227f277a | ||
|
|
0b4519652b | ||
|
|
36a3c3b28d | ||
|
|
86d6c1d340 | ||
|
|
ed3f38f1ab | ||
|
|
fe6183dd44 | ||
|
|
febeecdec7 | ||
|
|
0b3b022edf | ||
|
|
0e2fb6a9b8 | ||
|
|
2c32758e34 | ||
|
|
1ee26d786a | ||
|
|
03195bbbe5 | ||
|
|
26a6b7318c | ||
|
|
cd0aa2bf41 | ||
|
|
d3f7d3efbc | ||
|
|
2f94768184 | ||
|
|
d37ebb7fcd | ||
|
|
ffec604ed9 | ||
|
|
7891959853 | ||
|
|
0c6a3ee660 | ||
|
|
0499ccb2cc | ||
|
|
f91a80f9dd | ||
|
|
95eb8ee676 | ||
|
|
70fbbe22df | ||
|
|
ed2dffb091 | ||
|
|
27c465491f | ||
|
|
91d768afd2 | ||
|
|
3b40598ced | ||
|
|
160a8977e6 | ||
|
|
8c6ee6ca89 | ||
|
|
6cb05ebc37 | ||
|
|
c8450b9908 | ||
|
|
6f1f2623a3 | ||
|
|
52342a9b8e | ||
|
|
a3b64d8c8d |
No files matched your search
+20
-7
@@ -1,10 +1,23 @@
|
||||
# EKB MCP 配置示例
|
||||
# hose-use 环境变量示例(全部可选,不设置即使用默认值)
|
||||
|
||||
# 企业配置目录(默认 ./enterprises)
|
||||
# EKB_CONFIG_DIR=./enterprises
|
||||
# 企业配置目录覆盖(默认 ~/.config/hose-use/enterprises,目录权限 0700)
|
||||
# HOSE_ENTERPRISES_DIR=~/.config/hose-use/enterprises
|
||||
|
||||
# Token 缓存目录(默认 ~/.cache/ekb-mcp)
|
||||
# EKB_TOKEN_CACHE_DIR=~/.cache/ekb-mcp
|
||||
# 全局配置文件覆盖(默认 ~/.config/hose-use/config.json)
|
||||
# HOSE_CONFIG_FILE=~/.config/hose-use/config.json
|
||||
|
||||
# 默认 API 基础 URL
|
||||
# EKB_BASE_URL=https://app.ekuaibao.com
|
||||
# 账号与 Token 缓存文件覆盖(默认位于 ~/.config/hose-use/,文件权限 0600)
|
||||
# HOSE_ACCOUNTS_FILE=~/.config/hose-use/accounts.json
|
||||
# HOSE_TOKENS_FILE=~/.config/hose-use/tokens.json
|
||||
|
||||
# 本地状态目录(审批引擎 / Token 缓存 / 守护进程状态,默认 ~/.config/hose-use)
|
||||
# HOSE_STATE_DIR=~/.config/hose-use
|
||||
|
||||
# 本地 HTTP Daemon(默认 127.0.0.1,建议保持回环地址)
|
||||
# HOST=127.0.0.1
|
||||
# PORT=8888
|
||||
# HOSE_HTTP_TOKEN=<访问令牌>
|
||||
# HOSE_HTTP_CORS_ORIGIN=http://localhost:7788
|
||||
|
||||
# MCP Server 总开关(默认关闭)
|
||||
# HOSE_USE_MCP_ENABLED=true
|
||||
@@ -0,0 +1,36 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: 1.3.14
|
||||
- run: bun install --frozen-lockfile
|
||||
- run: bun run check:version
|
||||
- run: bun run check
|
||||
- run: bun test
|
||||
- run: bun run build:binary
|
||||
- run: bun run scripts/verify-binary.ts dist/bin/hose-use
|
||||
- run: bun run build:plugin
|
||||
- run: git diff --exit-code -- dist/mcp/server.js
|
||||
- run: bun run scripts/verify-binary.ts dist/mcp/server.js --plugin
|
||||
+126
-27
@@ -5,41 +5,91 @@ on:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
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 }}
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
name: 🚀 Build & Publish Multi-Platform Binaries
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
MIRROR_ONLY: ${{ inputs.mirror_only || false }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ inputs.tag || github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
# A tag alone does not prove review. Also verify the commit actually being
|
||||
# compiled, so manual dispatch cannot validate one tag and ship another ref.
|
||||
- name: Verify release commit and version
|
||||
run: |
|
||||
git fetch --no-tags origin main:refs/remotes/origin/main
|
||||
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
|
||||
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() {
|
||||
@@ -64,69 +114,118 @@ jobs:
|
||||
(cd "${stage}" && zip -q "${GITHUB_WORKSPACE}/dist/bin/hose-use-windows-x64.zip" hose-use-windows-x64.exe hose-aipro.cmd)
|
||||
rm -rf "${stage}"
|
||||
|
||||
(cd dist/bin && sha256sum hose-use-* > checksums.txt)
|
||||
|
||||
- name: Publish GitHub Release
|
||||
if: ${{ !inputs.mirror_only }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${GITHUB_REF_NAME}" | sed '/^$/d')
|
||||
TAG_MSG=$(git tag -l --format='%(contents)' "${RELEASE_TAG}" | sed '/^$/d')
|
||||
if [ -n "$TAG_MSG" ]; then
|
||||
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --notes "$TAG_MSG" --generate-notes
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --notes "$TAG_MSG" --generate-notes
|
||||
else
|
||||
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
|
||||
gh release view "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${RELEASE_TAG}" --repo "${GITHUB_REPOSITORY}" --title "${RELEASE_TAG}" --generate-notes
|
||||
fi
|
||||
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
gh release upload "${RELEASE_TAG}" dist/bin/hose-use-* dist/bin/checksums.txt --repo "${GITHUB_REPOSITORY}" --clobber
|
||||
|
||||
- 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="${GITHUB_REF_NAME}"
|
||||
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
|
||||
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 0
|
||||
echo "::error::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
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..."
|
||||
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${file}")
|
||||
STATUS=$(echo "$RESP" | tail -n 1)
|
||||
echo " [done] ${filename} -> ${STATUS}"
|
||||
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
|
||||
echo "::error::Failed to upload ${filename} after 3 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Bound outbound traffic: large raw binaries must not compete with all archives.
|
||||
pids=()
|
||||
for file in dist/bin/hose-use-*; do
|
||||
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
|
||||
|
||||
for pid in "${pids[@]}"; do
|
||||
wait "$pid" || true
|
||||
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
|
||||
fi
|
||||
echo "✓ Successfully published release assets to Gitea!"
|
||||
@@ -46,3 +46,6 @@ data/
|
||||
|
||||
# Local roadmaps & scratch notes
|
||||
*.local.md
|
||||
|
||||
# Exports
|
||||
exports/
|
||||
@@ -2,7 +2,7 @@
|
||||
"mcpServers": {
|
||||
"hose-use": {
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"command": "bun",
|
||||
"args": [
|
||||
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.12",
|
||||
"version": "0.8.17",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -22,7 +22,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h
|
||||
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
|
||||
│
|
||||
▼
|
||||
domains/ (14 个业务子域:编排 tools/services + 传输 api)
|
||||
domains/ (业务子域:编排 tools/services + 传输 api;清单见域层说明)
|
||||
│
|
||||
▼
|
||||
core/ (严格基础设施白名单)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.12)
|
||||
# hose-use (v0.8.17)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
安装与自更新会校验 Release 的 SHA-256 清单;版本固定、镜像设置及发布流程见 [构建与分发说明](./src/packaging/README.packaging.md)。
|
||||
|
||||
### 方式二:本地 Bun 源码开发
|
||||
|
||||
```bash
|
||||
@@ -92,7 +94,7 @@ hose-use service logs # 查看守护进程日志
|
||||
hose-use service stop # 优雅停止常驻守护进程
|
||||
|
||||
# 8. Agent Skill 与连通性诊断
|
||||
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use skill install --yes # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
||||
|
||||
# 9. MCP Server (单工具网关模式)
|
||||
@@ -105,14 +107,14 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
- 避免数十个业务工具占用大量 Prompt Tokens;
|
||||
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
|
||||
- 内部同进程调用 CLI 分发层,零子进程开销;
|
||||
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
|
||||
- `HOSE_MCP_MODE` 始终采用 `single`;通过 `HOSE_USE_MCP_ENABLED=false` 可关闭工具暴露,写操作沿用 CLI 的预览与确认约定。
|
||||
|
||||
### 模块化 Agent Skill 与 IDE 插件规范
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
|
||||
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
|
||||
|
||||
## 架构
|
||||
|
||||
|
||||
@@ -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
+1744
-1240
File diff suppressed because it is too large.
Load diff
@@ -1,84 +0,0 @@
|
||||
# 2026-04-06 开发日报
|
||||
|
||||
> 截止提交:`792314a`(日报本身所在提交)
|
||||
> 下一个实例可用 `git log 792314a` 查看全部历史,或 `git checkout 792314a` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
从零搭建 ekb-cli,实现快报智能审核 Agent 的命令行管理,替代图形界面操作。
|
||||
|
||||
---
|
||||
|
||||
## 完成事项
|
||||
|
||||
### 一、项目骨架
|
||||
|
||||
- 初始化 Python 包结构(uv + pyproject.toml)
|
||||
- 实现认证机制:自定义 Header(accesstoken / corpid / staffid),支持多企业存储与切换
|
||||
- 解决 SOCKS5 代理兼容问题(补充 `httpx[socks]` 依赖)
|
||||
|
||||
### 二、ekb auth 命令组
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb auth add` | 添加企业认证 |
|
||||
| `ekb auth list` | 列出所有企业 |
|
||||
| `ekb auth use` | 切换当前企业 |
|
||||
| `ekb auth remove` | 删除企业 |
|
||||
| `ekb auth whoami` | 查看当前企业 |
|
||||
|
||||
### 三、ekb agent 命令组
|
||||
|
||||
**Agent 管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent list` | 列出所有 Agent |
|
||||
| `ekb agent get <id>` | 查看 Agent 详情(含四类条款、关联规则列表) |
|
||||
| `ekb agent get <id> --full` | 不截断规则字段,提示完整文本总字符数 |
|
||||
| `ekb agent update <id>` | patch 式修改(只改传入字段,其余保持原值) |
|
||||
| `ekb agent logs` | 查看审核日志(待实现) |
|
||||
|
||||
**规则管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent rules` | 列出企业全部审核规则 |
|
||||
| `ekb agent rules --level 严重` | 按风险等级筛选 |
|
||||
| `ekb agent rules --full` | 不截断描述字段 |
|
||||
| `ekb agent rule-get <编码或ID>` | 查看规则详情,含关联 Agent 列表 |
|
||||
|
||||
> 编码输入自适应:`1` / `01` / `0001` / `#0001` 均可识别,自动补零对齐。
|
||||
|
||||
### 四、ekb commands
|
||||
|
||||
`ekb commands` / `ekb commands agent` — 分层展示命令树,引导向下钻取。
|
||||
|
||||
### 五、API 封装(api/agent.py)
|
||||
|
||||
对接接口:
|
||||
|
||||
```
|
||||
GET /api/engine/hab/agent/list
|
||||
GET /api/engine/hab/agent/detail
|
||||
POST /api/engine/hab/agent/save
|
||||
GET /api/engine/hab/agent/rule/list
|
||||
POST /api/engine/hab/agent/rule/save
|
||||
POST /api/engine/hab/agent/rule/update
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 设计决策
|
||||
|
||||
- **截断提示展示字符总数**:CLI 是生产环境唯一入口(无 MCP),AI 读输出时需要知道是否值得拉全量数据,所以截断时提示完整文本总字符数而非截断标准。
|
||||
- **patch 式 update**:先 GET 当前值,再合并传入字段,避免覆盖未传字段。
|
||||
- **文档分层**:`CLAUDE.md`(项目级全图)→ `README.agent.md`(agent 语义/常量)→ `README.rule.md`(rule 语义/常量)。枚举常量不写在顶层文件。
|
||||
|
||||
---
|
||||
|
||||
## 待办
|
||||
|
||||
- [ ] `ekb agent logs` — 需抓包确认 API 结构
|
||||
- [ ] 规则关联管理 — 给 Agent 增删关联规则(`ruleIds` 字段)
|
||||
- [ ] `ekb rule update` — 修改规则内容(API 已封装,命令未实现)
|
||||
@@ -1,72 +0,0 @@
|
||||
# 2026-04-08 开发日报
|
||||
|
||||
> 截止提交:`c041966`(日报本身所在提交)
|
||||
> 下一个实例可用 `git log c041966` 查看全部历史,或 `git checkout c041966` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
在昨日基础上扩展写操作命令,完善 API 层架构。
|
||||
|
||||
---
|
||||
|
||||
## 完成事项
|
||||
|
||||
### 一、新增写操作命令
|
||||
|
||||
**规则管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent rule-create` | 新建审核规则(`--purpose` / `--desc` / `--level`) |
|
||||
|
||||
**Agent 管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent create` | 新建 Agent(支持全部字段,含关联规则 ID) |
|
||||
| `ekb agent copy <id>` | 复制 Agent,名称自动追加「(副本)」,检测重名 |
|
||||
| `ekb agent delete <id>` | 删除 Agent,方向键交互确认,不可恢复 |
|
||||
|
||||
### 二、API 层重构
|
||||
|
||||
- **拆分文件**:`api/agent.py`(Agent 接口)+ `api/rule.py`(Rule 接口)+ `api/schemas.py`(Pydantic 模型)
|
||||
- **统一 re-export**:所有 commands 只从 `ekb_cli.api` 导入,内部拆分对上层透明
|
||||
- **引入 Pydantic 校验**:所有接口响应经 `model_validate` 强制校验,字段变更时抛 `ValidationError` 精确定位,而非静默返回空值
|
||||
- 新增接口:`GET /engine/hab/agent/checkName`、`GET /engine/hab/agent/active`
|
||||
|
||||
### 三、交互体验优化
|
||||
|
||||
- `ekb agent delete` 默认使用 `questionary` 方向键选择器,默认停在「取消」
|
||||
- 非 tty 环境(管道/AI调用)自动降级为 `y/N` 文字输入;`--ai` 参数可强制指定;`--yes` 跳过确认
|
||||
- 修复 `checkName` 接口语义反转 bug(`data=false` 表示名称可用)
|
||||
|
||||
### 四、文档补全
|
||||
|
||||
- 新增 `api/README.api.md`:三层架构说明、各接口签名、Pydantic 应对策略
|
||||
- 补全 `README.agent.md`:`state` 枚举含义(0=启用 / 1=禁用 / 2=已删除)及对应接口
|
||||
- 补全 `README.rule.md`:`rule-create` 命令速查
|
||||
|
||||
---
|
||||
|
||||
## 新增接口
|
||||
|
||||
```
|
||||
GET /api/engine/hab/agent/checkName?name=xxx # 检查名称唯一性(data=false 表示可用)
|
||||
GET /api/engine/hab/agent/active?id=xxx&state= # 变更 Agent 状态(0启用/1禁用/2删除)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 设计决策
|
||||
|
||||
- **"删除"是状态变更**:快报无真正的 DELETE 接口,`state=2` 即为删除,通过 `/active` 接口实现。
|
||||
- **Pydantic `extra="allow"`**:允许快报新增字段,但已知字段强制类型,兼顾前向兼容与变更感知。
|
||||
- **`questionary` 仅在 tty 下启用**:`sys.stdin.isatty()` 自动检测,无需用户关心环境差异。
|
||||
|
||||
---
|
||||
|
||||
## 待办
|
||||
|
||||
- [ ] `ekb agent logs` — 需抓包确认 API 结构
|
||||
- [ ] `ekb agent rule update` — 修改规则内容(API 已封装,命令未实现)
|
||||
- [ ] `ekb agent rule delete` — 删除规则(接口待确认)
|
||||
@@ -1,107 +0,0 @@
|
||||
# 2026-05-18 开发日报
|
||||
|
||||
> 截止提交:`298e114`(当前 feature/workflow-control 分支)
|
||||
> 下一个实例可用 `git log 298e114` 查看全部历史,或 `git checkout 298e114` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
讨论并确定 ekb-mcp 项目的数据库方案。
|
||||
|
||||
---
|
||||
|
||||
## 讨论内容
|
||||
|
||||
### 一、数据库选型分析
|
||||
|
||||
**时间:2026-05-18 18:30**
|
||||
|
||||
针对项目是否需要数据库进行了深入讨论:
|
||||
|
||||
| 方案 | 优点 | 缺点 | 适用场景 |
|
||||
|------|------|------|----------|
|
||||
| PostgreSQL | 功能强大,支持复杂查询和并发 | 需要额外部署,运维复杂 | 多用户并发,复杂查询 |
|
||||
| SQLite | 轻量级,嵌入式,无需额外服务 | 并发支持有限 | 单机部署,小规模应用 |
|
||||
| 内存缓存 + JSON 文件 | 简单,无依赖,性能最高 | 重启后缓存丢失 | 单实例,数据量小 |
|
||||
|
||||
### 二、项目特点分析
|
||||
|
||||
**当前状态:**
|
||||
- 配置存储在 `enterprises/*.json` 文件中
|
||||
- 企业配置数量少(几个到几十个)
|
||||
- 结构简单,只需按 ID 读取
|
||||
- MCP 服务器单实例运行
|
||||
|
||||
**性能问题:**
|
||||
- `loadCorpConfigs()` 每次调用都读取文件系统
|
||||
- `getCorpTokens()` 每次调用都读取文件系统
|
||||
- 没有任何缓存机制
|
||||
- 大量重复查询会导致频繁的文件 I/O
|
||||
|
||||
### 三、中间件方案讨论
|
||||
|
||||
**时间:2026-05-18 19:00**
|
||||
|
||||
曾考虑实现存储中间件(Repository 模式),支持多种存储后端:
|
||||
|
||||
```
|
||||
src/core/storage/
|
||||
├── types.ts # 接口定义
|
||||
├── memory.ts # 内存存储实现
|
||||
├── sqlite.ts # SQLite 实现
|
||||
├── postgres.ts # PostgreSQL 实现
|
||||
└── factory.ts # 工厂函数
|
||||
```
|
||||
|
||||
**反思:**
|
||||
- 过度设计:对于当前项目来说太复杂
|
||||
- 维护成本:需要维护多个存储后端的代码
|
||||
- 依赖管理:需要处理可选依赖
|
||||
- 学习成本:新开发者需要理解抽象层
|
||||
|
||||
### 四、最终决策
|
||||
|
||||
**时间:2026-05-18 19:30**
|
||||
|
||||
**选择方案:内存缓存 + JSON 文件**
|
||||
|
||||
**理由:**
|
||||
1. **数据量小** - 企业配置通常不多,文件足够
|
||||
2. **结构简单** - 不需要复杂查询,只需按 ID 读取
|
||||
3. **运维简单** - 无额外依赖,易于备份和版本控制
|
||||
4. **单实例运行** - MCP 服务器通常单实例,无需高并发支持
|
||||
5. **性能足够** - 内存缓存可以解决重复查询的性能问题
|
||||
|
||||
**实现方案:**
|
||||
```typescript
|
||||
// 简单的内存缓存
|
||||
const cache = new Map<string, CorpConfig>();
|
||||
|
||||
function getConfig(id: string): CorpConfig | undefined {
|
||||
if (cache.has(id)) return cache.get(id);
|
||||
const config = loadFromFile(id);
|
||||
if (config) cache.set(id, config);
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
**清理工作:**
|
||||
- 移除了 `src/core/storage/` 目录(过度设计的中间件方案)
|
||||
- 移除了 `scripts/migrate-configs.ts`(不再需要的迁移脚本)
|
||||
|
||||
---
|
||||
|
||||
## 后续计划
|
||||
|
||||
1. 实现内存缓存机制,解决重复查询的性能问题
|
||||
2. 保持现有 JSON 文件方案,简化架构
|
||||
3. 如果未来数据量增长,再考虑 SQLite 作为轻量级方案
|
||||
|
||||
---
|
||||
|
||||
## 技术笔记
|
||||
|
||||
- 项目使用 TypeScript + Bun 运行时
|
||||
- 配置文件位于 `enterprises/*.json`
|
||||
- Token 缓存位于 `~/.cache/ekb-mcp/tokens.json`
|
||||
- 当前分支:`feature/workflow-control`
|
||||
- 最新提交:`298e114` - feat(platform): 新增工作流控制及辅助工具
|
||||
@@ -105,7 +105,7 @@ CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、
|
||||
|
||||
```bash
|
||||
bun run export:workflow-schema
|
||||
# 输出:schemas/workflow-schema.json
|
||||
# 输出:specs/workflow-schema.json
|
||||
```
|
||||
|
||||
## 工作流数据结构要点
|
||||
|
||||
@@ -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 和发布工作流记录为准。
|
||||
@@ -0,0 +1,5 @@
|
||||
# enterprises/ 目录说明
|
||||
|
||||
本目录仅保留 `example.json`(企业配置字段示例,随 git 分发),用于说明企业配置文件的格式。
|
||||
|
||||
**运行时数据不在这里。** CLI 实际读取的企业配置目录为 `~/.config/hose-use/enterprises/`(可用环境变量 `HOSE_ENTERPRISES_DIR` 覆盖),文件权限强制 `0600`、目录权限 `0700`,且已被 `.gitignore` 排除。解析逻辑见 `src/core/config/loader.ts`。
|
||||
+11
-1
@@ -1,12 +1,20 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.12",
|
||||
"version": "0.8.17",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/server.ts",
|
||||
"./sdk": "./src/sdk.ts"
|
||||
},
|
||||
"bin": {
|
||||
"hose-use": "src/cli.ts",
|
||||
"hose-aipro": "src/cli.ts"
|
||||
},
|
||||
"packageManager": "bun@1.3.14",
|
||||
"engines": {
|
||||
"bun": ">=1.3.14"
|
||||
},
|
||||
"scripts": {
|
||||
"cli": "bun run src/cli.ts",
|
||||
"aipro": "bun run src/aipro-cli.ts",
|
||||
@@ -32,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"
|
||||
},
|
||||
|
||||
@@ -19,6 +19,8 @@ function run(args) {
|
||||
|
||||
const mcpOutput = resolve(root, "dist/mcp/server.js");
|
||||
mkdirSync(dirname(mcpOutput), { recursive: true });
|
||||
run(["build", "src/server.ts", "--minify", "--target=node", "--outfile", mcpOutput]);
|
||||
// The shared CLI uses bun:sqlite; the plugin manifest must use this runtime too.
|
||||
// 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}`);
|
||||
+113
-85
@@ -1,93 +1,121 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync, existsSync, cpSync, readdirSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const ROOT = join(import.meta.dirname, "..");
|
||||
const pkgPath = join(ROOT, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
||||
const currentVersion: string = pkg.version;
|
||||
export function bumpVersion(ROOT: string, input: string, rebuild = () => {
|
||||
execFileSync(process.execPath, ["run", "openapi:all"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "build:plugin"], { cwd: ROOT, stdio: "inherit" });
|
||||
execFileSync(process.execPath, ["run", "check:version"], { cwd: ROOT, stdio: "inherit" });
|
||||
}): string {
|
||||
const pkgPath = join(ROOT, "package.json");
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
||||
const currentVersion: string = pkg.version;
|
||||
|
||||
const input = process.argv[2]?.trim();
|
||||
if (!input) {
|
||||
console.error("Usage: bun run bump <version | patch | minor | major>");
|
||||
console.error(`Current version: ${currentVersion}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let nextVersion = input.replace(/^v/, "");
|
||||
if (input === "patch" || input === "minor" || input === "major") {
|
||||
const [major, minor, patch] = currentVersion.split(".").map(Number);
|
||||
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
|
||||
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
|
||||
if (input === "major") nextVersion = `${major + 1}.0.0`;
|
||||
}
|
||||
|
||||
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(nextVersion)) {
|
||||
console.error(`Invalid SemVer format: '${nextVersion}'`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
|
||||
|
||||
// 1. package.json
|
||||
pkg.version = nextVersion;
|
||||
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
|
||||
console.log("✓ Updated package.json");
|
||||
|
||||
// 2. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v[\d.]+: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
for (const item of readdirSync(srcDir)) {
|
||||
cpSync(join(srcDir, item), join(globalSkillDir, item), { recursive: true, force: true });
|
||||
if (!input) {
|
||||
console.error("Usage: bun run bump <version | patch | minor | major>");
|
||||
console.error(`Current version: ${currentVersion}`);
|
||||
throw new Error("A release version is required");
|
||||
}
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
|
||||
let nextVersion = input.replace(/^v/, "");
|
||||
if (input === "patch" || input === "minor" || input === "major") {
|
||||
const [major, minor, patch] = currentVersion.split("-")[0].split(".").map(Number);
|
||||
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
|
||||
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
|
||||
if (input === "major") nextVersion = `${major + 1}.0.0`;
|
||||
}
|
||||
|
||||
if (!isReleaseVersion(nextVersion)) throw new Error(`Invalid SemVer format: '${nextVersion}'`);
|
||||
if (Bun.semver.order(nextVersion, currentVersion) <= 0) throw new Error(`Version must increase: ${currentVersion} -> ${nextVersion}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
if (git(["status", "--porcelain"])) throw new Error("Release preparation requires a clean working tree");
|
||||
const branch = git(["branch", "--show-current"]);
|
||||
if (!["codex/release-v", "release/v"].some(prefix => branch === `${prefix}${nextVersion}`)) {
|
||||
throw new Error(`Prepare the release on codex/release-v${nextVersion} or release/v${nextVersion}; current branch: ${branch || "detached HEAD"}`);
|
||||
}
|
||||
if (git(["tag", "--list", `v${nextVersion}`])) throw new Error(`Tag v${nextVersion} already exists`);
|
||||
// Read all versioned sources before writing any of them.
|
||||
for (const file of ["README.md", "skills/hose-use/SKILL.md"]) readFileSync(join(ROOT, file), "utf8");
|
||||
for (const file of ["specs/openapi/openapi.yaml", ".zcode-plugin/plugin.json"]) {
|
||||
if (existsSync(join(ROOT, file))) {
|
||||
const content = readFileSync(join(ROOT, file), "utf8");
|
||||
if (file.endsWith(".json")) JSON.parse(content);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
|
||||
|
||||
// 1. package.json
|
||||
pkg.version = nextVersion;
|
||||
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
|
||||
console.log("✓ Updated package.json");
|
||||
|
||||
// 2. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `# hose-use (v${nextVersion})`);
|
||||
skillContent = skillContent.replace(/v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?: 合思/g, `v${nextVersion}: 合思`);
|
||||
skillContent = skillContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
skillContent = skillContent.replace(/\(v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: \d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
pluginJson.version = nextVersion;
|
||||
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ is now an explicit dev:override step.
|
||||
// A version bump must not overwrite personal Skill files in the user's environment.
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
rebuild();
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Review the diff, then run bun test && bun run check && bun run check:version`);
|
||||
console.log(` 2. Commit on ${branch}, push that branch and open a PR to main`);
|
||||
console.log(` 3. Wait for CI and review, then merge the PR`);
|
||||
console.log(` 4. Switch to main; git pull --ff-only origin main; git push home main`);
|
||||
console.log(` 5. Create annotated tag v${nextVersion} on the merged release commit`);
|
||||
console.log(` 6. git push home refs/tags/v${nextVersion} (first), then git push origin refs/tags/v${nextVersion}`);
|
||||
console.log(` 7. Verify the Release build, binary archives and checksums on both sources`);
|
||||
console.log(` Optional: bun run dev:override to explicitly sync your global development binary and Skill`);
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
|
||||
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
|
||||
export function isReleaseVersion(value: string): boolean {
|
||||
const match = value.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*))?$/);
|
||||
return !!match && (!match[4] || match[4].split(".").every(part => !/^0\d+$/.test(part)));
|
||||
}
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Update CHANGELOG.md (if exists)`);
|
||||
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
|
||||
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
|
||||
console.log(` 4. git push origin <feature-branch>\n`);
|
||||
if (import.meta.main) {
|
||||
try {
|
||||
bumpVersion(join(import.meta.dirname, ".."), process.argv[2]?.trim() || "");
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import YAML from "yaml";
|
||||
|
||||
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
||||
|
||||
const inputFile = resolve("openapi/openapi.yaml");
|
||||
const outputFile = resolve("dist/openapi.json");
|
||||
const inputFile = resolve("specs/openapi/openapi.yaml");
|
||||
const outputFile = resolve("specs/openapi.json");
|
||||
|
||||
const bundled = bundle(inputFile, new Set());
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf
|
||||
const expected: Array<[string, string | undefined]> = [
|
||||
["package.json", packageVersion],
|
||||
[".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")],
|
||||
["openapi/openapi.yaml", readFileSync(join(root, "openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
|
||||
["dist/openapi.json", readJsonVersion("dist/openapi.json", ["info", "version"])],
|
||||
["specs/openapi/openapi.yaml", readFileSync(join(root, "specs/openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
|
||||
["specs/openapi.json", readJsonVersion("specs/openapi.json", ["info", "version"])],
|
||||
];
|
||||
|
||||
const mismatches = expected.filter(([, value]) => value !== packageVersion);
|
||||
|
||||
@@ -39,7 +39,6 @@ describe("dev hygiene tooling", () => {
|
||||
unreachableCommits: ["deadbeef"],
|
||||
skill: {} as any,
|
||||
binaries: [],
|
||||
legacyConfig: {} as any,
|
||||
};
|
||||
const plan = buildCleanupPlan(snapshot, false);
|
||||
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
|
||||
|
||||
@@ -90,12 +90,6 @@ interface HygieneSnapshot {
|
||||
matches: boolean;
|
||||
error?: string;
|
||||
}>;
|
||||
legacyConfig: {
|
||||
enterprisesDir: string;
|
||||
configFile: string;
|
||||
enterprisesDirExists: boolean;
|
||||
configFileExists: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface HygieneReport {
|
||||
@@ -304,13 +298,6 @@ function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
|
||||
}
|
||||
}
|
||||
|
||||
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
|
||||
const home = homedir();
|
||||
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
|
||||
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
|
||||
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
|
||||
}
|
||||
|
||||
function collectSnapshot(): HygieneSnapshot {
|
||||
return {
|
||||
repository: parseRepository(),
|
||||
@@ -319,7 +306,6 @@ function collectSnapshot(): HygieneSnapshot {
|
||||
unreachableCommits: parseUnreachableCommits(),
|
||||
skill: parseSkill(),
|
||||
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
|
||||
legacyConfig: parseLegacyConfig(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -370,10 +356,6 @@ function buildFindings(snapshot: HygieneSnapshot): Finding[] {
|
||||
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
|
||||
}
|
||||
}
|
||||
const legacy = snapshot.legacyConfig;
|
||||
if (legacy.enterprisesDirExists || legacy.configFileExists) {
|
||||
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
WorkflowSchema,
|
||||
} from "../src/domains/platform/types.js";
|
||||
|
||||
const OUTPUT_DIR = join(process.cwd(), "schemas");
|
||||
const OUTPUT_DIR = join(process.cwd(), "specs");
|
||||
const OUTPUT_FILE = join(OUTPUT_DIR, "workflow-schema.json");
|
||||
|
||||
function writeJson(path: string, data: unknown): void {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
const outputFile = resolve("dist/raw-hose-openapi.json");
|
||||
const outputFile = resolve("specs/openapi.raw.json");
|
||||
|
||||
function standardResponse(description: string, dataSchema: any) {
|
||||
return {
|
||||
|
||||
+119
-78
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
set -euo pipefail
|
||||
|
||||
REPO="yunyingk/hose-use"
|
||||
|
||||
@@ -34,9 +34,10 @@ case "$ARCH" in
|
||||
esac
|
||||
|
||||
# Resolve best writable bin directory without requiring sudo
|
||||
TARGET_DIR=""
|
||||
TARGET_DIR="${HOSE_USE_INSTALL_DIR:-}"
|
||||
if [ -n "$TARGET_DIR" ]; then mkdir -p "$TARGET_DIR"; fi
|
||||
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
if [ -z "$TARGET_DIR" ] && [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
TARGET_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
@@ -49,6 +50,10 @@ fi
|
||||
|
||||
ASSET_NAME="hose-use-${PLATFORM}-${ARCH_NAME}"
|
||||
TARGET_PATH="${TARGET_DIR}/hose-use"
|
||||
if [ -d "$TARGET_PATH" ] || { [ -d "${TARGET_DIR}/hose-aipro" ] && [ ! -L "${TARGET_DIR}/hose-aipro" ]; }; then
|
||||
echo "Error: an install target is a directory; refusing to replace it." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
get_file_size() {
|
||||
local file="$1"
|
||||
@@ -102,7 +107,7 @@ download_candidate() {
|
||||
if curl -fL --progress-bar "$url" -o "$dest"; then
|
||||
local size_bytes
|
||||
size_bytes="$(get_file_size "$dest")"
|
||||
if [ "$size_bytes" -gt 1000000 ]; then
|
||||
if [ "$size_bytes" -gt 0 ]; then
|
||||
echo "✓ Download complete! Total size: $(format_bytes "$size_bytes")"
|
||||
echo "✓ Successfully fetched from host: ${host}"
|
||||
return 0
|
||||
@@ -114,103 +119,139 @@ download_candidate() {
|
||||
}
|
||||
|
||||
echo "==> Target install location: ${TARGET_PATH}"
|
||||
TMP_FILE="$(mktemp)"
|
||||
TMP_DIR="$(mktemp -d)"
|
||||
TMP_FILE="${TMP_DIR}/download"
|
||||
CHECKSUM_FILE="${TMP_DIR}/checksums.txt"
|
||||
INSTALL_STAGE=""
|
||||
trap 'rm -rf "$TMP_DIR"; if [ -n "$INSTALL_STAGE" ]; then rm -f "$INSTALL_STAGE"; fi' EXIT
|
||||
DOWNLOAD_SUCCESS=false
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
|
||||
# Resolve latest Gitea tag if available
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
LATEST_TAG=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
echo "Error: curl is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
hash_file() { sha256sum "$1" | awk '{ print tolower($1) }'; }
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
hash_file() { shasum -a 256 "$1" | awk '{ print tolower($1) }'; }
|
||||
else
|
||||
echo "Error: SHA-256 verification requires sha256sum or shasum." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MIRROR="${HOSE_USE_MIRROR:-auto}"
|
||||
case "$MIRROR" in auto|github|gitea) ;; *) echo "Invalid HOSE_USE_MIRROR: $MIRROR" >&2; exit 1 ;; esac
|
||||
|
||||
# Resolve latest Gitea tag if available. Resolve once, then pin every mirror and
|
||||
# checksum request to that exact version instead of guessing an old release.
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
GITHUB_API_URL="https://api.github.com/repos/${REPO}/releases/latest"
|
||||
LATEST_TAG="${HOSE_USE_VERSION:-}"
|
||||
if [ -n "$LATEST_TAG" ]; then
|
||||
LATEST_TAG="v${LATEST_TAG#v}"
|
||||
else
|
||||
api_urls=()
|
||||
if [ "$MIRROR" != "github" ]; then api_urls+=("$GITEA_API_URL"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then api_urls+=("$GITHUB_API_URL"); fi
|
||||
for api_url in "${api_urls[@]}"; do
|
||||
if release_json=$(curl -fsSL --connect-timeout 4 --max-time 15 "$api_url"); then
|
||||
LATEST_TAG=$(printf '%s' "$release_json" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^" ]*\)".*/\1/p' | head -n 1)
|
||||
if [ -n "$LATEST_TAG" ]; then break; fi
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if ! [[ "$LATEST_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then
|
||||
echo "Error: could not resolve a release version; set HOSE_USE_VERSION explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
release_bases=()
|
||||
if [ "$MIRROR" != "github" ]; then release_bases+=("https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}"); fi
|
||||
if [ "$MIRROR" != "gitea" ]; then
|
||||
release_bases+=("https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
release_bases+=("https://ghfast.top/https://github.com/${REPO}/releases/download/${LATEST_TAG}")
|
||||
fi
|
||||
|
||||
verified_download() {
|
||||
local base="$1" asset="$2" expected actual
|
||||
if ! download_candidate "${base}/checksums.txt" "$CHECKSUM_FILE" "Release checksums"; then
|
||||
echo " ↳ Missing checksums.txt for ${LATEST_TAG}; refusing an unverified install." >&2
|
||||
return 1
|
||||
fi
|
||||
expected=$(awk -v name="$asset" '{ sub(/\r$/, "") } $2 == name || $2 == "*" name { count++; if (length($1) == 64 && $1 ~ /^[0-9a-fA-F]+$/) value=tolower($1); else invalid=1 } END { if (count == 1 && !invalid) print value; else exit 1 }' "$CHECKSUM_FILE") || {
|
||||
echo " ↳ Missing or ambiguous checksum for ${asset}." >&2
|
||||
return 1
|
||||
}
|
||||
if ! download_candidate "${base}/${asset}" "$TMP_FILE" "Release ${LATEST_TAG}"; then return 1; fi
|
||||
actual=$(hash_file "$TMP_FILE")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo " ↳ SHA-256 mismatch for ${asset}; refusing this download." >&2
|
||||
return 1
|
||||
fi
|
||||
echo "✓ SHA-256 verified: ${asset}"
|
||||
}
|
||||
|
||||
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
|
||||
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
|
||||
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Second priority: Raw Executable (Fallback)
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
|
||||
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
|
||||
# 2. Second priority: Raw Executable (Fallback), with the same checksum requirement.
|
||||
for format in archive raw; do
|
||||
asset="$ASSET_NAME"
|
||||
if [ "$format" = "archive" ]; then asset="${asset}.tar.gz"; fi
|
||||
for base in "${release_bases[@]}"; do
|
||||
if verified_download "$base" "$asset"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
DOWNLOADED_FORMAT="$format"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ "$DOWNLOAD_SUCCESS" = "true" ]; then break; fi
|
||||
done
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
echo "Error: Failed to download ${ASSET_NAME} from all candidate mirrors." >&2
|
||||
rm -f "$TMP_FILE"
|
||||
echo "Error: Failed to obtain a verified ${ASSET_NAME} for ${LATEST_TAG} from all candidate mirrors." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
|
||||
echo "==> Extracting archive to ${TARGET_DIR}..."
|
||||
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
|
||||
rm -f "$TMP_FILE"
|
||||
chmod +x "$TARGET_PATH"
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
|
||||
echo "==> Extracting selected binary in temporary staging..."
|
||||
member=""
|
||||
listing=$(tar -tzf "$TMP_FILE")
|
||||
for candidate in "$ASSET_NAME" "./$ASSET_NAME" hose-use ./hose-use; do
|
||||
if printf '%s\n' "$listing" | awk -v name="$candidate" '$0 == name { count++ } END { exit count != 1 }'; then
|
||||
member="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$member" ]; then echo "Error: release archive has no expected platform binary." >&2; exit 1; fi
|
||||
# Stream only the exact member; archive paths and aliases never get written to bin.
|
||||
tar -xOzf "$TMP_FILE" "$member" > "${TMP_DIR}/hose-use"
|
||||
if [ ! -s "${TMP_DIR}/hose-use" ]; then echo "Error: release binary is empty." >&2; exit 1; fi
|
||||
else
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
mv "$TMP_FILE" "${TMP_DIR}/hose-use"
|
||||
fi
|
||||
|
||||
# Stage on the target filesystem so the final rename is atomic.
|
||||
INSTALL_STAGE=$(mktemp "${TARGET_DIR}/.hose-use-install.XXXXXX")
|
||||
cp "${TMP_DIR}/hose-use" "$INSTALL_STAGE"
|
||||
chmod 755 "$INSTALL_STAGE"
|
||||
# Ad-hoc sign on macOS
|
||||
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
|
||||
echo "==> Applying macOS code signature..."
|
||||
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
codesign --force --sign - "$INSTALL_STAGE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
mv -f "$INSTALL_STAGE" "$TARGET_PATH"
|
||||
INSTALL_STAGE=""
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
ln -sfn hose-use "${TARGET_DIR}/hose-aipro"
|
||||
|
||||
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
|
||||
"$TARGET_PATH" skill install >/dev/null 2>&1 || true
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
if "$TARGET_PATH" skill install --yes; then
|
||||
echo "✓ Agent skill installed to ~/.agents/skills/hose-use"
|
||||
else
|
||||
echo "Error: binary installed to ${TARGET_PATH}, but Agent Skill installation failed. Retry: hose-use skill install --yes" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✨ hose-use successfully installed to ${TARGET_PATH}!"
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readlinkSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
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");
|
||||
|
||||
function fixture(options: { badHash?: boolean; missingEntry?: boolean; duplicate?: boolean; rawOnly?: boolean } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-installer-test-"));
|
||||
fixtures.push(root);
|
||||
const tools = join(root, "tools"), source = join(root, "release"), target = join(root, "bin");
|
||||
for (const dir of [tools, source, target]) mkdirSync(dir);
|
||||
const binary = `#!/bin/sh
|
||||
if [ "$1" = "skill" ]; then
|
||||
printf '%s\\n' "$*" > "$HOSE_FIXTURE_LOG"
|
||||
[ "$2" = "install" ] && [ "$3" = "--yes" ] || exit 10
|
||||
[ "\${HOSE_FIXTURE_SKILL_FAIL:-0}" != "1" ] || exit 3
|
||||
else
|
||||
printf 'hose-use v9.9.9\\n'
|
||||
fi
|
||||
`;
|
||||
const asset = "hose-use-linux-x64";
|
||||
writeFileSync(join(source, asset), binary, { mode: 0o755 });
|
||||
symlinkSync(asset, join(source, "hose-aipro"));
|
||||
writeFileSync(join(source, "unrelated.txt"), "must not reach the install directory");
|
||||
const archive = `${asset}.tar.gz`;
|
||||
expect(spawnSync("tar", ["-czf", join(source, archive), "-C", source, asset, "hose-aipro", "unrelated.txt"]).status).toBe(0);
|
||||
const entry = `${options.badHash ? "0".repeat(64) : hash(readFileSync(join(source, archive)))} ${archive}\n`;
|
||||
writeFileSync(join(source, "checksums.txt"), (options.missingEntry ? "" : entry + (options.duplicate ? entry : "")) + `${options.badHash ? "0".repeat(64) : hash(binary)} ${asset}\n`);
|
||||
if (options.rawOnly) rmSync(join(source, archive));
|
||||
const curl = `#!/bin/bash
|
||||
set -eu
|
||||
url=""; dest=""; head_only=false
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-o) dest="$2"; shift 2 ;;
|
||||
--connect-timeout|--max-time) shift 2 ;;
|
||||
-fIs) head_only=true; shift ;;
|
||||
https://*) url="$1"; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
printf '%s\\n' "$url" >> "$HOSE_FIXTURE_REQUESTS"
|
||||
if [ "\${HOSE_FIXTURE_GITEA_FAIL:-0}" = "1" ] && [[ "$url" == *git.ying-qing.cn* ]]; then exit 22; fi
|
||||
if [[ "$url" == */releases/latest ]]; then
|
||||
[ "\${HOSE_FIXTURE_NO_TAG:-0}" != "1" ] || exit 22
|
||||
printf '{"tag_name": "v9.9.9"}'
|
||||
exit 0
|
||||
fi
|
||||
name="\${url##*/}"
|
||||
if [ "$name" = "checksums.txt" ] && [ "\${HOSE_FIXTURE_NO_MANIFEST:-0}" = "1" ]; then exit 22; fi
|
||||
file="$HOSE_FIXTURE_SOURCE/$name"
|
||||
[ -f "$file" ] || exit 22
|
||||
if [ "$head_only" = "true" ]; then exit 0; fi
|
||||
if [ -n "$dest" ]; then cp "$file" "$dest"; else cat "$file"; fi
|
||||
`;
|
||||
writeFileSync(join(tools, "curl"), curl, { mode: 0o755 });
|
||||
writeFileSync(join(tools, "uname"), '#!/bin/sh\nif [ "$1" = "-s" ]; then echo Linux; else echo x86_64; fi\n', { mode: 0o755 });
|
||||
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: 30_000,
|
||||
});
|
||||
return { root, source, target, run, binary };
|
||||
}
|
||||
|
||||
describe("verified standalone installer", () => {
|
||||
test("installs a platform-named archive and alias, then explicitly confirms Skill setup", () => {
|
||||
const f = fixture();
|
||||
const result = f.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
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)}`, () => {
|
||||
const f = fixture(options);
|
||||
// Remove raw fallback, so a missing archive entry cannot be hidden by another valid asset.
|
||||
rmSync(join(f.source, "hose-use-linux-x64"));
|
||||
writeFileSync(join(f.target, "hose-use"), "old binary");
|
||||
const result = f.run();
|
||||
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", () => {
|
||||
const f = fixture();
|
||||
expect(f.run({ HOSE_FIXTURE_NO_MANIFEST: "1" }).status).toBe(1);
|
||||
const unknown = f.run({ HOSE_USE_VERSION: "", HOSE_FIXTURE_NO_TAG: "1" });
|
||||
expect(unknown.status).toBe(1);
|
||||
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 });
|
||||
const result = f.run({ HOSE_FIXTURE_GITEA_FAIL: "1", HOSE_USE_VERSION: "" });
|
||||
expect(result.status).toBe(0);
|
||||
expect(readFileSync(join(f.target, "hose-use"), "utf8")).toBe(f.binary);
|
||||
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();
|
||||
const result = f.run({ HOSE_FIXTURE_SKILL_FAIL: "1" });
|
||||
expect(result.status).toBe(1);
|
||||
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();
|
||||
mkdirSync(join(f.root, "personal"));
|
||||
symlinkSync(join(f.root, "personal"), join(f.target, "hose-aipro"));
|
||||
expect(f.run().status).toBe(0);
|
||||
expect(readdirSync(join(f.root, "personal"))).toEqual([]);
|
||||
expect(readlinkSync(join(f.target, "hose-aipro"))).toBe("hose-use");
|
||||
rmSync(join(f.target, "hose-aipro"));
|
||||
mkdirSync(join(f.target, "hose-aipro"));
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
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";
|
||||
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 }); });
|
||||
|
||||
function repository() {
|
||||
const root = mkdtempSync(join(tmpdir(), "hose-release-test-"));
|
||||
roots.push(root);
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
git("init", "--initial-branch=main");
|
||||
git("config", "user.name", "Release fixture");
|
||||
git("config", "user.email", "fixture@example.test");
|
||||
git("config", "core.hooksPath", "/dev/null");
|
||||
git("config", "commit.gpgsign", "false");
|
||||
git("config", "tag.gpgsign", "false");
|
||||
for (const dir of ["skills/hose-use", "specs/openapi", ".zcode-plugin"]) mkdirSync(join(root, dir), { recursive: true });
|
||||
writeFileSync(join(root, "package.json"), '{"version":"1.0.0"}\n');
|
||||
writeFileSync(join(root, "README.md"), "# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "skills/hose-use/SKILL.md"), "version: 1.0.0\n# hose-use (v1.0.0)\n");
|
||||
writeFileSync(join(root, "specs/openapi/openapi.yaml"), "info:\n version: 1.0.0\n");
|
||||
writeFileSync(join(root, ".zcode-plugin/plugin.json"), '{"version":"1.0.0"}\n');
|
||||
git("add", ".");
|
||||
git("commit", "-m", "fixture");
|
||||
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
||||
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();
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("release-v1.0.1");
|
||||
f.git("switch", "-c", "codex/release-v1.0.1");
|
||||
writeFileSync(join(f.root, "untracked.txt"), "work in progress");
|
||||
expect(() => bumpVersion(f.root, "patch", () => {})).toThrow("clean working tree");
|
||||
rmSync(join(f.root, "untracked.txt"));
|
||||
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();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
let rebuilt = false;
|
||||
expect(bumpVersion(f.root, "patch", () => { rebuilt = true; })).toBe("1.0.1");
|
||||
expect(rebuilt).toBe(true);
|
||||
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();
|
||||
f.git("switch", "-c", "release/v1.0.1");
|
||||
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();
|
||||
f.git("tag", "v1.0.0");
|
||||
expect(() => verifyReleaseTag(f.root, "v1.0.0")).not.toThrow();
|
||||
expect(() => verifyReleaseTag(f.root, "main")).toThrow("Invalid release tag");
|
||||
f.git("tag", "v9.9.9");
|
||||
expect(() => verifyReleaseTag(f.root, "v9.9.9")).toThrow("does not match");
|
||||
f.git("switch", "-c", "unmerged");
|
||||
writeFileSync(join(f.root, "change"), "unreviewed");
|
||||
f.git("add", "."); f.git("commit", "-m", "unmerged fixture");
|
||||
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, "..");
|
||||
const ci = parse(readFileSync(join(root, ".github/workflows/ci.yml"), "utf8"));
|
||||
const release = parse(readFileSync(join(root, ".github/workflows/release.yml"), "utf8"));
|
||||
expect(ci.on.pull_request.branches).toContain("main");
|
||||
expect(ci.permissions.contents).toBe("read");
|
||||
const steps = release.jobs["build-and-publish"].steps;
|
||||
const runs = steps.map((s: { run?: string }) => s.run || "");
|
||||
expect(runs.findIndex((s: string) => s.includes("check:version"))).toBeLessThan(runs.findIndex((s: string) => s.includes("openapi:all")));
|
||||
expect(steps[0].with.ref).toContain("inputs.tag");
|
||||
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
|
||||
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();
|
||||
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");
|
||||
mkdirSync(join(f.root, "tools")); mkdirSync(join(f.root, "dist/bin"), { recursive: true });
|
||||
writeFileSync(join(f.root, "dist/bin/hose-use-linux-x64"), "fixture");
|
||||
writeFileSync(join(f.root, "dist/bin/checksums.txt"), "fixture checksums");
|
||||
writeFileSync(join(f.root, "tools/curl"), `#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
*/assets?*) exit 22 ;;
|
||||
*/releases) printf '{"id":42}'; exit 0 ;;
|
||||
*/releases/42) printf '{"assets":[]}'; exit 0 ;;
|
||||
esac
|
||||
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_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);
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env bun
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
|
||||
const binary = resolve(process.argv[2] || "dist/bin/hose-use");
|
||||
const plugin = process.argv.includes("--plugin");
|
||||
const command = plugin ? process.execPath : binary;
|
||||
const prefix = plugin ? [binary] : [];
|
||||
const cwd = mkdtempSync(join(tmpdir(), "hose-binary-smoke-"));
|
||||
// The binary must work without Bun on PATH or a source checkout in cwd.
|
||||
const env = { PATH: process.platform === "win32" ? process.env.SystemRoot || "C:\\Windows" : "/usr/bin:/bin", HOSE_USE_MCP_ENABLED: "true", HOSE_CONFIG_FILE: join(cwd, "config.json"), HOSE_ENTERPRISES_DIR: cwd };
|
||||
const client = new Client({ name: "hose-binary-smoke", version: "1.0.0" });
|
||||
const transport = new StdioClientTransport({ command, args: plugin ? prefix : ["mcp", "serve"], cwd, env, stderr: "pipe" });
|
||||
let stderr = "";
|
||||
transport.stderr?.on("data", chunk => { stderr += chunk.toString(); });
|
||||
const deadline = setTimeout(() => { void client.close(); }, 15_000);
|
||||
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"]);
|
||||
const result = await client.callTool({ name: "hose_cli", arguments: { command: "version --json" } });
|
||||
assert.ok(!result.isError, JSON.stringify(result));
|
||||
const text = (result.content as Array<{ type: string; text?: string }>).find(c => c.type === "text")?.text;
|
||||
assert.equal(JSON.parse(text || "").version, JSON.parse(version.stdout).version);
|
||||
const invalid = await client.callTool({ name: "hose_cli", arguments: { command: "bill list --limitt 5 --json" } });
|
||||
assert.equal(invalid.isError, true);
|
||||
assert.match(JSON.stringify(invalid.content), /未知选项/);
|
||||
console.log(plugin ? "Plugin bundle version and MCP stdio verified with its Bun runtime." : "Binary version and MCP stdio verified without Bun or source files.");
|
||||
} catch (error) {
|
||||
throw new Error(`Binary smoke failed: ${error instanceof Error ? error.message : error}\n${stderr}`);
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
await client.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bun
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { isReleaseVersion } from "./bump-version.js";
|
||||
|
||||
export function verifyReleaseTag(root: string, tag: string): void {
|
||||
if (!tag.startsWith("v") || !isReleaseVersion(tag.slice(1))) throw new Error(`Invalid release tag: ${tag}`);
|
||||
const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
const taggedCommit = git(["rev-parse", "--verify", `refs/tags/${tag}^{commit}`]);
|
||||
if (git(["rev-parse", "HEAD"]) !== taggedCommit) throw new Error("Release HEAD must be the exact tagged commit");
|
||||
try {
|
||||
git(["merge-base", "--is-ancestor", taggedCommit, "refs/remotes/origin/main"]);
|
||||
} catch {
|
||||
throw new Error("Release tag must be an ancestor of origin/main; merge the PR before tagging");
|
||||
}
|
||||
const { version } = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
|
||||
if (tag !== `v${version}`) throw new Error(`Release tag ${tag} does not match package.json v${version}`);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
verifyReleaseTag(resolve(import.meta.dir, ".."), process.argv[2] || "");
|
||||
console.log("Release tag, HEAD, main ancestry and package version verified.");
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.12
|
||||
version: 0.8.17
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.12)
|
||||
# hose-use (v0.8.17)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -52,6 +52,20 @@ 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 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
|
||||
---
|
||||
|
||||
@@ -67,6 +81,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 +110,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) |
|
||||
@@ -179,6 +195,8 @@ hose-use app list # 查看应用管理列
|
||||
hose-use app get 用车补贴 # 查看指定应用管理的配置与 Web 路由
|
||||
hose-use platform list # 列出企业可见的自建应用平台
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 --stats # 宏观结构画像(总数/启停比率/重名数/编码规则聚类)
|
||||
hose-use platform records 新转转集团 合同 --ndjson --flat # 万级海量数据 $O(1)$ 内存逐行流式输出 JSON Lines
|
||||
hose-use platform records 新转转集团 合同 --all -o /tmp/records.json # 自动翻页导出全量业务对象记录
|
||||
hose-use platform audit 新转转集团 合同 --check-fields="我方签约主体" # 一键巡检必填缺失、停用引用与跨表同步差异
|
||||
hose-use platform record get <记录ID> # 免传应用/对象,直接按记录 ID 获取完整详情
|
||||
@@ -200,6 +218,24 @@ 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 rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
||||
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||
hose-use workflow tail wf_01k83y... --failed-only # 仅在有报错或异常跳过 (SKIPPED) 时即时打印详情
|
||||
hose-use workflow tail wf_01k83y... --once --json # 检视最新或当前运行中的 Job 进度快照并返回结构化数据
|
||||
hose-use workflow lint-script wf_01k83y... # 批量静态校验代码节点语法规范与上游依赖 (支持 --file/--code)
|
||||
hose-use workflow eval-script wf_01k83y... <节点> --sample=1 # 离线沙箱仿真运行 JS 节点并复用样本数据 (支持 --input/--timeout)
|
||||
|
||||
# 6. OpenAPI 密钥与应用中心
|
||||
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
|
||||
|
||||
@@ -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` 下钻单次运行实例:
|
||||
@@ -234,7 +266,142 @@ hose-use workflow publish <pipelineId>
|
||||
|
||||
---
|
||||
|
||||
## 14. 工作流排障与创单排错三大黄金法则(必读)
|
||||
## 14. 从零创建、复制与删除工作流 (`workflow create` / `copy` / `delete`)
|
||||
|
||||
对标合思 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
|
||||
hose-use workflow create --name="每日发票对账" --trigger=clock --platform-id=ID01uzxB4x07fh --yes
|
||||
|
||||
# 2. 从本地 JSON 模板文件一键新建
|
||||
hose-use workflow create --file=workflow-template.json --name="生产流程-A" --yes
|
||||
|
||||
# 别名支持 new, add
|
||||
hose-use workflow new --name="合同归档触发" --trigger=datalink --yes
|
||||
|
||||
# 3. 复制已有工作流为新草稿(默认名称加" 副本",首节点为 Webhook 时自动重新分配独立 urlPath 并清理老样本)
|
||||
hose-use workflow copy <pipelineId> --dry-run
|
||||
hose-use workflow copy <pipelineId> --name="发票监控克隆版" --yes
|
||||
|
||||
# 别名支持 cp, clone
|
||||
hose-use workflow cp <pipelineId> --yes
|
||||
|
||||
# 4. 删除指定工作流(不可逆,必须确认)
|
||||
hose-use workflow delete <pipelineId> --dry-run
|
||||
hose-use workflow delete <pipelineId> --yes
|
||||
|
||||
# 别名支持 rm, remove
|
||||
hose-use workflow rm <pipelineId> --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. 工作流节点级声明式编排与编辑 (`workflow node`)
|
||||
|
||||
针对合思 EASO/Piper 任务流水线内部的复杂节点树(支持 `every` 循环、`condition` 分支多层深度嵌套),提供直接按节点标识(如 `action_xxx`)或层级序号(如 `1`, `2.1`, `2.2.1`)定向查看、追加、修改与移除的能力,避免手动拼接庞大 JSON 报文的低效与格式错误:
|
||||
|
||||
```bash
|
||||
# 1. 树形层级索引查看工作流中所有任务节点与配置摘要 (别名: ls)
|
||||
hose-use workflow node list <pipelineId>
|
||||
hose-use workflow node list <pipelineId> --json
|
||||
|
||||
# 2. 定向查看指定节点的完整属性与映射详情 (别名: show, info)
|
||||
# 支持传节点 name (如 action_dx9cci) 或序号 (如 2 或 2.1)
|
||||
hose-use workflow node get <pipelineId> action_dx9cci
|
||||
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
|
||||
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
|
||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
|
||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||
# 自动标准化重排同层 index 与 levelIndex;内置首节点触发器保护,严禁误删流程唯一的触发源
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
|
||||
hose-use workflow node rm <pipelineId> action_dx9cci --yes
|
||||
hose-use workflow node rm <pipelineId> 3 --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. 实时任务监听与执行日志流 (`workflow tail` / `watch` / `follow`)
|
||||
|
||||
类似 Unix `tail -f` 实时监听工作流在合思云端的任务派发与节点执行树跃迁。当有外部 Webhook 推送、定时 CRON 调度或业务单据流转触发工作流时,无需反复手动敲 `workflow logs` 或 `workflow job` 轮询,即时流式打出节点状态跃迁与详细报错:
|
||||
|
||||
```bash
|
||||
# 1. 类似 tail -f 实时监听流水线任务派发与各节点执行状态跃迁 (别名: watch, follow)
|
||||
hose-use workflow tail <pipelineId>
|
||||
hose-use workflow watch <pipelineId> --interval=1
|
||||
|
||||
# 2. 针对指定单次运行中的 Job 进行实时跟踪直至执行完成
|
||||
hose-use workflow tail <pipelineId> --job=<jobId>
|
||||
hose-use workflow tail 898268773466365973 --job=898577624451395602
|
||||
|
||||
# 3. 仅在有报错或异常跳过 (SKIPPED) 节点时即时告警并打出底层错误
|
||||
hose-use workflow tail <pipelineId> --failed-only
|
||||
|
||||
# 4. 检视最新或当前运行中的 Job 进度快照 (不进入持续循环,适合脚本快速检查)
|
||||
hose-use workflow tail <pipelineId> --once
|
||||
hose-use workflow tail <pipelineId> --once --json
|
||||
|
||||
# 5. 设置最长监听超时 (秒)
|
||||
hose-use workflow tail <pipelineId> --timeout=60
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 17. 工作流代码节点静态校验与离线沙箱仿真 (`workflow lint-script` / `eval-script`)
|
||||
|
||||
合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力:
|
||||
|
||||
```bash
|
||||
# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用
|
||||
hose-use workflow lint-script <pipelineId>
|
||||
hose-use workflow lint <pipelineId> --json
|
||||
|
||||
# 2. 定向检查指定代码节点(支持节点名称或 #序号)
|
||||
hose-use workflow lint-script <pipelineId> action_dx9cci
|
||||
|
||||
# 3. 静态检查本地脚本文件或命令行传入的代码片段
|
||||
hose-use workflow lint-script --file=./scripts/clean.js
|
||||
hose-use workflow lint-script --code="const a = 1; return a * 2;"
|
||||
hose-use workflow lint-script --code="var a = control_123; return a;" --type=mvel
|
||||
|
||||
# 4. 在离线安全沙箱中仿真运行工作流中的某个 JavaScript 节点 (code-js2)
|
||||
# 自动复用最近一次历史真实样本数据作为入参,打印返回值与全部 console.log 日志:
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci
|
||||
|
||||
# 5. 指定历史测试样本序号(如第 2 条样本)进行离线仿真
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --sample=2
|
||||
|
||||
# 6. 自定义输入参数执行离线仿真 (JSON 字符串或本地 JSON 文件)
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --input='{"info":{"amount":100}}'
|
||||
hose-use workflow eval-script <pipelineId> action_dx9cci --input-file=./mock_input.json
|
||||
|
||||
# 7. 纯本地行内代码沙箱快速求值与死循环超时控制 (--timeout 默认 3000ms)
|
||||
hose-use workflow eval-script --code="console.log(items); return items.filter(x => x.active);" --input='{"items":[{"id":1,"active":true},{"id":2,"active":false}]}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 18. 工作流排障与创单排错三大黄金法则(必读)
|
||||
|
||||
在排查“工作流明明运行了但没生成单据”、“工作流显示 COMPLETED 但单据缺失”或“生成单据报错必填项未填”时,必须严格遵循以下三大黄金法则:
|
||||
|
||||
@@ -251,3 +418,26 @@ hose-use workflow publish <pipelineId>
|
||||
- 执行 `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` 进行沙箱调测。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.12",
|
||||
"version": "0.8.17",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.12
|
||||
version: 0.8.17
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,13 +1,13 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 预置规约规则
|
||||
@@ -22,7 +22,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
@@ -37,7 +37,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 1. 创建审批会话
|
||||
@@ -125,7 +125,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
|
||||
+24
-4
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/env bun
|
||||
import { parseArgs, stringOption, booleanOption } from "./cli/parser.js";
|
||||
import { printJson, redactSensitiveText } from "./cli/printer.js";
|
||||
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";
|
||||
import { getSessionClientForRuntime, initCorpRuntime, requireSelectedCorp } from "./cli/helpers.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
@@ -27,14 +29,32 @@ import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
export async function runAiProCli(
|
||||
rawArgs: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
try {
|
||||
return await runAiProCliOnce(rawArgs);
|
||||
} catch (error) {
|
||||
return cliErrorResult(error, isJsonRequested(rawArgs));
|
||||
}
|
||||
}
|
||||
|
||||
async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
if (booleanOption(parsed.options, ["help", "h", "?"])) {
|
||||
const help = printHelp(["aipro", ...(parsed.area && parsed.area !== "help" ? [parsed.area] : [])]);
|
||||
return { stdout: jsonMode ? printJson({ help }) : `${help}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: stringOption(parsed.options, ["corp", "c"]),
|
||||
corpId: stringOption(parsed.options, ["corp"]),
|
||||
jsonMode,
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname } from "node:path";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { writeStdoutChunk } from "./cli/printer.js";
|
||||
|
||||
process.stdout.on("error", (err: any) => {
|
||||
if (err?.code === "EPIPE") process.exit(0);
|
||||
@@ -26,6 +27,7 @@ const result = isAiPro
|
||||
: await runCli(process.argv.slice(2), {
|
||||
appRoot,
|
||||
entryFile,
|
||||
writeStdout: writeStdoutChunk,
|
||||
});
|
||||
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# CLI 引擎层说明
|
||||
|
||||
本目录是三个入口(`src/cli.ts` 主 CLI、`src/aipro-cli.ts` AI PRO CLI、`src/server.ts` MCP 网关)共享的命令引擎:声明式注册、参数解析、写防护、输出渲染与错误映射。入口层只做薄壳,业务编排统一在 `domains/`。
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
|
||||
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
||||
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
||||
- `help.ts`:帮助文本组织。
|
||||
- `commands/`:每个顶层命令域一个 handler 文件,与 `src/domains/` 一一对应;复杂命令(如 `aipro/`)可用子目录形态。
|
||||
- `architecture-boundaries.test.ts`:分层导入约束的机器卡点(入口层禁触 `domains/*/api.ts`、域层禁反向依赖、core 白名单)。
|
||||
|
||||
## 约定
|
||||
|
||||
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
|
||||
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
|
||||
|
||||
## 嵌入调用与流式输出
|
||||
|
||||
`runCli` 默认通过 `CliResult` 返回结果,不直接写进进程 stdout。终端入口可显式传入 `CliRunOptions.writeStdout` 异步回调;处理器必须等待回调完成,保证慢管道有背压。MCP / HTTP 不提供该回调,流式记录应使用 `--output-file`,否则返回用法错误。普通命令的返回结构保持不变。
|
||||
|
||||
参数解析与运行时初始化也经过统一异常边界。`--json` 的错误对象继续写入 `stdout`,保留退出码和恢复建议;人类日志写入 `stderr`。`help <域>`、`<域> --help` 支持同一份域别名,帮助主题不存在时返回用法错误。处理器自身保留的详细用法说明仍可供直接嵌入调用使用。
|
||||
|
||||
优先用 `--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; }
|
||||
});
|
||||
@@ -39,6 +39,17 @@ function resolveImportRelativeToSrc(fromFile: string, specifier: string): string
|
||||
}
|
||||
|
||||
describe("Architecture Layering Boundaries", () => {
|
||||
test("workflow imports use the module directories after the platform migration", () => {
|
||||
const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/;
|
||||
const violations: string[] = [];
|
||||
for (const file of collectTsFiles(SRC_ROOT, true)) {
|
||||
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
|
||||
const target = resolveImportRelativeToSrc(file, specifier);
|
||||
if (target && legacy.test(target)) violations.push(`${relative(SRC_ROOT, file)} -> ${target}`);
|
||||
}
|
||||
}
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
|
||||
const entrypointFiles = [
|
||||
...collectTsFiles(join(SRC_ROOT, "cli")),
|
||||
|
||||
@@ -0,0 +1,861 @@
|
||||
/** Static command vocabulary shared by dispatch, parsing and help. No handler imports. */
|
||||
export type FlagKind = "boolean" | "value" | "boolean-or-value";
|
||||
export interface HelpTopic {
|
||||
summary: string; usage: string; commands: Record<string, string>; options?: string[];
|
||||
}
|
||||
export interface CliCommandMetadata extends HelpTopic {
|
||||
aliases: string[]; commandAliases: Record<string, string>; flags: Record<string, FlagKind>;
|
||||
}
|
||||
|
||||
export const GLOBAL_FLAGS: Record<string, FlagKind> = {
|
||||
...Object.fromEntries("json j help h ? version v V full allow-full allowFull summary stateless stateful dry-run dryRun dryrun yes y confirm force-write forceWrite force".split(" ").map(k => [k, "boolean" as const])),
|
||||
...Object.fromEntries("corp c output-file outputFile o".split(" ").map(k => [k, "value" as const])),
|
||||
};
|
||||
|
||||
function flagList(keys: string, kind: FlagKind): Record<string, FlagKind> {
|
||||
return Object.fromEntries(keys.split(" ").filter(Boolean).map(key => [key, kind]));
|
||||
}
|
||||
|
||||
export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"context": {
|
||||
"summary": "全局运行上下文与身份诊断",
|
||||
"usage": "hose-use context [--json]",
|
||||
"commands": {
|
||||
"context": "输出当前企业、账号、运行模式与认证状态"
|
||||
},
|
||||
"aliases": [
|
||||
"status",
|
||||
"whoami",
|
||||
"env"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
"usage": "hose-use aipro <子命令>",
|
||||
"commands": {
|
||||
"status": "查看网关状态",
|
||||
"bind": "绑定单据",
|
||||
"review": "核验要点",
|
||||
"decide": "执行仲裁",
|
||||
"init": "初始化审批上下文",
|
||||
"scopes": "列出审批规则场景",
|
||||
"translate": "转译单据",
|
||||
"rules": "查看审批规则",
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"logs": "查看审批日志",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"context": "status",
|
||||
"info": "status",
|
||||
"start": "init",
|
||||
"index": "scopes",
|
||||
"indexes": "scopes",
|
||||
"doc": "translate",
|
||||
"markdown": "translate",
|
||||
"render": "translate",
|
||||
"rule": "rules",
|
||||
"mount": "bind",
|
||||
"clauses": "points",
|
||||
"list": "checklist",
|
||||
"eval": "review",
|
||||
"evaluate": "review",
|
||||
"approve": "decide",
|
||||
"reject": "decide",
|
||||
"log": "logs",
|
||||
"history": "logs",
|
||||
"trail": "logs"
|
||||
},
|
||||
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
|
||||
},
|
||||
"auth": {
|
||||
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
"usage": "hose-use auth <子命令>",
|
||||
"commands": {
|
||||
"login": "登录并保存企业凭证",
|
||||
"status": "查看当前认证状态",
|
||||
"refresh": "刷新账号或企业 AccessToken",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"accounts": "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
"import": "导入抓包或协助凭证",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已保存的企业配置"
|
||||
},
|
||||
"aliases": [
|
||||
"login"
|
||||
],
|
||||
"commandAliases": {
|
||||
"whoami": "status",
|
||||
"current": "status",
|
||||
"renew": "refresh",
|
||||
"add": "import",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal",
|
||||
"list": "accounts",
|
||||
"account": "accounts",
|
||||
"accs": "accounts",
|
||||
"switch": "switch-account",
|
||||
"use-account": "switch-account"
|
||||
},
|
||||
flags: { ...flagList("a p app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user accessToken account curl headers phone pwd raw token", "value"), ...flagList("add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite persist plain prod production r refresh reveal save save-staff t test upgrade-all verify i interactive sms sync", "boolean") }
|
||||
},
|
||||
"corps": {
|
||||
"summary": "多企业租户管理",
|
||||
"usage": "hose-use corps <子命令>",
|
||||
"commands": {
|
||||
"list": "列出本地企业配置",
|
||||
"search": "搜索企业与员工",
|
||||
"switch": "切换当前工作企业",
|
||||
"current": "查看当前企业",
|
||||
"link": "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
"elevate": "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
"tag": "标记企业环境",
|
||||
"hose-link": "生成企业免密登录链接",
|
||||
"sync-seal": "导入已有企业配置",
|
||||
"probe-hose": "检查企业接口连通性",
|
||||
"hose-staffs": "查询企业员工",
|
||||
"help": "help 命令"
|
||||
},
|
||||
"aliases": [
|
||||
"corp"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"query": "search",
|
||||
"filter": "search",
|
||||
"set-env": "tag",
|
||||
"mark": "tag",
|
||||
"use": "switch",
|
||||
"whoami": "current",
|
||||
"status": "current",
|
||||
"active": "current",
|
||||
"import-link": "add-link",
|
||||
"auth-link": "hose-link",
|
||||
"login-link": "hose-link",
|
||||
"add-hose-persistent": "add-persistent",
|
||||
"add-openapi": "add-persistent",
|
||||
"add-hose": "add-persistent",
|
||||
"extract-key": "extract-keys",
|
||||
"hose-extract-keys": "extract-keys",
|
||||
"extract-hose-keys": "extract-keys",
|
||||
"elevate-hose": "elevate",
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal"
|
||||
},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"config": {
|
||||
"summary": "全局运行模式与路径配置",
|
||||
"usage": "hose-use config <子命令>",
|
||||
"commands": {
|
||||
"paths": "诊断配置目录链",
|
||||
"get": "查看全局配置",
|
||||
"mode": "切换 stateful/stateless",
|
||||
"set": "更新指定配置项",
|
||||
"test-dir": "设置测试企业目录"
|
||||
},
|
||||
"aliases": [
|
||||
"mode"
|
||||
],
|
||||
"commandAliases": {
|
||||
"path": "paths",
|
||||
"dirs": "paths",
|
||||
"show": "paths",
|
||||
"list": "paths",
|
||||
"status": "get",
|
||||
"info": "get",
|
||||
"test-enterprises-dir": "test-dir"
|
||||
},
|
||||
flags: { ...flagList("clear", "boolean") }
|
||||
},
|
||||
"workflow": {
|
||||
"summary": "工作流查询、草稿、运行排障与生命周期管理",
|
||||
"usage": "hose-use workflow <子命令> [参数] [选项]",
|
||||
"commands": {
|
||||
"list": "列出工作流",
|
||||
"get": "查看工作流详情",
|
||||
"find": "按节点类型搜索",
|
||||
"analyze": "静态分析工作流(含禁用/SKIP/联动覆盖检查)",
|
||||
"job": "查看单次运行实例树、报错节点与MVEL日志",
|
||||
"diff": "对比两个工作流快照的结构与脚本差异",
|
||||
"diff-job": "对比两次执行的节点分支与报错发散点",
|
||||
"test": "端到端一键调试单据(替代前端手工调测)",
|
||||
"node": "声明式节点编排与增删改 (list|get|add|edit|rm)",
|
||||
"nodes": "查询企业已开通工作流节点字典或开通灰度节点 (list|grant)",
|
||||
"tail": "实时监听任务派发与节点执行日志流 (watch|follow)",
|
||||
"create": "从零新建工作流草稿",
|
||||
"copy": "复制克隆工作流",
|
||||
"delete": "删除工作流",
|
||||
"patch": "生成草稿字段补丁",
|
||||
"save": "保存草稿到远端",
|
||||
"toggle": "切换启停状态",
|
||||
"publish": "发布并启用工作流",
|
||||
"history": "查看版本历史",
|
||||
"logs": "查看运行日志",
|
||||
"check": "检查错误管道",
|
||||
"enum": "查询在线枚举字典(不可用时使用内置字典)",
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本"
|
||||
},
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
"--file=<workflow.json> 指定工作流快照",
|
||||
"--failed 只看失败节点",
|
||||
"--parent=<executionId> 展开循环/分支子节点",
|
||||
"--logs=<executionId> 查看节点执行日志",
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"workflows",
|
||||
"wf"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list-all": "list",
|
||||
"ls": "list",
|
||||
"detail": "get",
|
||||
"info": "get",
|
||||
"search": "find",
|
||||
"enable": "publish",
|
||||
"update": "save",
|
||||
"snapshots": "history",
|
||||
"log": "logs",
|
||||
"execution": "job",
|
||||
"health": "check",
|
||||
"analyse": "analyze",
|
||||
"diff-snapshot": "diff",
|
||||
"diff-snapshots": "diff",
|
||||
"compare": "diff",
|
||||
"diff-jobs": "diff-job",
|
||||
"compare-job": "diff-job",
|
||||
"debug": "test",
|
||||
"run-test": "test",
|
||||
"cp": "copy",
|
||||
"clone": "copy",
|
||||
"rm": "delete",
|
||||
"remove": "delete",
|
||||
"new": "create",
|
||||
"add": "create",
|
||||
"nodes": "node",
|
||||
"watch": "tail",
|
||||
"follow": "tail",
|
||||
"lint": "lint-script",
|
||||
"lint-code": "lint-script",
|
||||
"eval": "eval-script",
|
||||
"eval-code": "eval-script",
|
||||
"run-script": "eval-script",
|
||||
"enums": "enum",
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
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 has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a admin-key adminKey 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 filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs 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-id platformId pwd 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": "单据检索、表单规格诊断与审批动作",
|
||||
"usage": "hose-use bill <子命令> [单号|ID] [选项]",
|
||||
"commands": {
|
||||
"list": "查询单据",
|
||||
"get": "查看单据详情",
|
||||
"spec": "查看单据模板字段配置与联动覆盖规则",
|
||||
"flow": "查看审批流程",
|
||||
"approve": "同意审批",
|
||||
"reject": "驳回审批",
|
||||
"transfer": "转交审批",
|
||||
"add-node": "加签审批",
|
||||
"comment": "添加评论",
|
||||
"trace": "穿透诊断单据与当前待办",
|
||||
"schema": "查看单据实体模型",
|
||||
"risk": "查看风险信息",
|
||||
"budget": "查看预算状态",
|
||||
"refs": "解析关联人员与部门",
|
||||
"relations": "查看关联单据",
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
"fee",
|
||||
"fees",
|
||||
"invoice",
|
||||
"invoices"
|
||||
],
|
||||
"commandAliases": {
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"shift": "transfer",
|
||||
"addnode": "add-node",
|
||||
"countersign": "add-node",
|
||||
"counter-sign": "add-node",
|
||||
"remark": "comment",
|
||||
"search": "list",
|
||||
"show": "get",
|
||||
"find": "get",
|
||||
"inspect": "trace",
|
||||
"diagnose": "trace",
|
||||
"schemas": "schema",
|
||||
"entities": "schema",
|
||||
"records": "flow",
|
||||
"timeline": "flow",
|
||||
"review": "risk",
|
||||
"warnings": "risk",
|
||||
"budgets": "budget",
|
||||
"references": "refs",
|
||||
"resolve": "refs",
|
||||
"relation": "relations",
|
||||
"links": "relations",
|
||||
"attachment": "attachments",
|
||||
"files": "attachments",
|
||||
"file-download": "download",
|
||||
"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") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
"risk": "查看风险信息",
|
||||
"list": "查询单据",
|
||||
"approve": "审批同意",
|
||||
"reject": "审批驳回"
|
||||
},
|
||||
"aliases": [
|
||||
"flows",
|
||||
"trace"
|
||||
],
|
||||
"commandAliases": {
|
||||
"records": "history",
|
||||
"timeline": "history",
|
||||
"search": "list",
|
||||
"agree": "approve",
|
||||
"deny": "reject",
|
||||
"trace": "get",
|
||||
"inspect": "get",
|
||||
"diagnose": "get",
|
||||
"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") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
"usage": "hose-use contact <子命令>",
|
||||
"commands": {
|
||||
"list": "列出员工",
|
||||
"search": "搜索员工",
|
||||
"get": "查看员工详情"
|
||||
},
|
||||
"aliases": [
|
||||
"contacts",
|
||||
"staff",
|
||||
"staffs"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("id k keyword l limit query staff-id", "value") }
|
||||
},
|
||||
"task": {
|
||||
"summary": "待办中心与审批任务",
|
||||
"usage": "hose-use task <子命令>",
|
||||
"commands": {
|
||||
"todo": "待我审批",
|
||||
"approved": "我已审批",
|
||||
"submitted": "我发起的",
|
||||
"records": "审批记录",
|
||||
"cc": "抄送任务"
|
||||
},
|
||||
"aliases": [
|
||||
"tasks",
|
||||
"todo"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("read unread", "boolean"), ...flagList("count end-date from limit n offset staff staff-id staffId start start-date to", "value") }
|
||||
},
|
||||
"dimension": {
|
||||
"summary": "系统与自定义档案维度",
|
||||
"usage": "hose-use dimension <子命令>",
|
||||
"commands": {
|
||||
"list": "列出维度",
|
||||
"items": "列出维度项"
|
||||
},
|
||||
"aliases": [
|
||||
"dimensions",
|
||||
"archive",
|
||||
"archives"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count dimension id keyword limit n name q query", "value") }
|
||||
},
|
||||
"feetype": {
|
||||
"summary": "费用类型全生命周期管理与模板规格查询",
|
||||
"usage": "hose-use feetype <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "查看费用类型树",
|
||||
"get": "查看详情与字段",
|
||||
"spec": "查看单据/申请模板字段与联动规则",
|
||||
"create": "新建费用类型",
|
||||
"update": "修改属性",
|
||||
"disable": "停用",
|
||||
"enable": "启用",
|
||||
"move": "移动层级",
|
||||
"fields": "查看字段配置"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览写操作",
|
||||
"--yes/--confirm 确认写操作"
|
||||
],
|
||||
"aliases": [
|
||||
"feetypes",
|
||||
"fee-type",
|
||||
"fee-types",
|
||||
"expense-type",
|
||||
"expense-types",
|
||||
"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") }
|
||||
},
|
||||
"role": {
|
||||
"summary": "企业角色定义与成员",
|
||||
"usage": "hose-use role <子命令>",
|
||||
"commands": {
|
||||
"list": "列出角色",
|
||||
"groups": "列出角色组",
|
||||
"members": "查看角色成员"
|
||||
},
|
||||
"aliases": [
|
||||
"roles"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("code count id keyword limit n name q query role", "value") }
|
||||
},
|
||||
"permission": {
|
||||
"summary": "权限模型快照",
|
||||
"usage": "hose-use permission get",
|
||||
"commands": {
|
||||
"get": "查看角色权限开关"
|
||||
},
|
||||
"aliases": [
|
||||
"permissions"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
},
|
||||
"rule": {
|
||||
"summary": "本地审批规约管理",
|
||||
"usage": "hose-use rule <子命令> [参数]",
|
||||
"commands": {
|
||||
"scopes": "列出适用场景",
|
||||
"scope": "查看场景明细",
|
||||
"list": "列出规则",
|
||||
"get": "查看规则详情",
|
||||
"add": "新增规则",
|
||||
"delete": "删除规则"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览增删",
|
||||
"--yes/--confirm 确认增删"
|
||||
],
|
||||
"aliases": [
|
||||
"rules"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all", "boolean"), ...flagList("b body code id index name s scope status target", "value") }
|
||||
},
|
||||
"approval": {
|
||||
"summary": "确定性审批网关与要点仲裁",
|
||||
"usage": "hose-use approval audit <子命令> [单号]",
|
||||
"commands": {
|
||||
"points": "查看审核要点",
|
||||
"checklist": "查看核验清单",
|
||||
"review": "核验事实",
|
||||
"decide": "生成或执行仲裁决定",
|
||||
"audit": "审批核验与仲裁入口"
|
||||
},
|
||||
"options": [
|
||||
"--apply --yes 执行真实审批流转"
|
||||
],
|
||||
"aliases": [
|
||||
"approvals",
|
||||
"audit"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("apply confirm do execute run y yes", "boolean"), ...flagList("action code comment data e eval evidence findings i id index m message p point proof r reason reasoning s scope sn state status target", "value") }
|
||||
},
|
||||
"message": {
|
||||
"summary": "消息中心与通知管理",
|
||||
"usage": "hose-use message <子命令>",
|
||||
"commands": {
|
||||
"list": "查询消息",
|
||||
"count": "查看未读数",
|
||||
"read": "标记消息已读",
|
||||
"read-all": "全部标记已读"
|
||||
},
|
||||
"aliases": [
|
||||
"messages",
|
||||
"notify",
|
||||
"notifications"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("all read unread", "boolean"), ...flagList("count id limit message-id message-type n offset start type", "value") }
|
||||
},
|
||||
"platform": {
|
||||
"summary": "自建应用、业务对象、全量记录安全更新与台账体检",
|
||||
"usage": "hose-use platform <子命令> [参数]",
|
||||
"commands": {
|
||||
"list": "列出自建应用",
|
||||
"entities": "列出业务对象",
|
||||
"schema": "查看字段定义",
|
||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||
"permissions": "查看权限",
|
||||
"imports": "查看导入任务",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"options": [
|
||||
"--all 自动翻页拉取全量记录",
|
||||
"--ndjson 流式逐行下发 JSON Lines ($O(1)内存)",
|
||||
"--flat 剥离底层实体动态字段前缀并提取引用",
|
||||
"--stats 输出总数/启停/重名/编码规则聚类画像",
|
||||
"--dry-run 只预览记录写操作",
|
||||
"--yes/--confirm 确认记录写操作",
|
||||
"--raw 跳过安全合并直接发送原始补丁"
|
||||
],
|
||||
"aliases": [
|
||||
"platforms",
|
||||
"datalink",
|
||||
"data-link"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"show": "get",
|
||||
"objects": "entities",
|
||||
"fields": "schema",
|
||||
"data": "records",
|
||||
"search": "records",
|
||||
"stats": "records",
|
||||
"profile": "records",
|
||||
"check": "audit",
|
||||
"health": "audit",
|
||||
"record-get": "record",
|
||||
"record-toggle": "record",
|
||||
"record-edit": "record",
|
||||
"record-batch-edit": "record",
|
||||
"batch-edit": "record",
|
||||
"record-update": "record",
|
||||
"update": "record",
|
||||
"batch-update": "record",
|
||||
"record-recompute": "record",
|
||||
"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") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
"usage": "hose-use app <子命令>",
|
||||
"commands": {
|
||||
"list": "列出应用",
|
||||
"get": "查看应用详情"
|
||||
},
|
||||
"aliases": [
|
||||
"apps",
|
||||
"workbench"
|
||||
],
|
||||
"commandAliases": {
|
||||
"ls": "list",
|
||||
"apps": "list",
|
||||
"workbench": "list",
|
||||
"show": "get"
|
||||
},
|
||||
flags: { ...flagList("app id k keyword name q query", "value") }
|
||||
},
|
||||
"menu": {
|
||||
"summary": "桌面端主导航菜单树",
|
||||
"usage": "hose-use menu list",
|
||||
"commands": {
|
||||
"list": "查看主导航",
|
||||
"apps": "查看应用入口"
|
||||
},
|
||||
"aliases": [
|
||||
"menus"
|
||||
],
|
||||
"commandAliases": {
|
||||
"workbench": "apps",
|
||||
"ls": "list",
|
||||
"tree": "list"
|
||||
},
|
||||
flags: { }
|
||||
},
|
||||
"skill": {
|
||||
"summary": "Agent Skill 管理",
|
||||
"usage": "hose-use skill <install|status|dump>",
|
||||
"commands": {
|
||||
"install": "安装内嵌 Skill",
|
||||
"status": "查看安装状态",
|
||||
"dump": "导出 Skill 文件"
|
||||
},
|
||||
"aliases": [
|
||||
"skills"
|
||||
],
|
||||
"commandAliases": {
|
||||
"cat": "dump",
|
||||
"show": "dump",
|
||||
"init": "install",
|
||||
"sync": "install",
|
||||
"get": "status"
|
||||
},
|
||||
flags: { ...flagList("local workspace", "boolean"), ...flagList("dir target", "value") }
|
||||
},
|
||||
"probe": {
|
||||
"summary": "企业连通性诊断",
|
||||
"usage": "hose-use probe [corpId]",
|
||||
"commands": {
|
||||
"probe": "检查认证与 API 连通性"
|
||||
},
|
||||
"aliases": [
|
||||
"diagnose"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"update": {
|
||||
"summary": "版本自更新与发布记录",
|
||||
"usage": "hose-use update [check|--changelog]",
|
||||
"commands": {
|
||||
"update": "检查并升级版本",
|
||||
"check": "只检查可用版本",
|
||||
"changelog": "查看发布记录"
|
||||
},
|
||||
"aliases": [
|
||||
"upgrade",
|
||||
"self-update",
|
||||
"changelog"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("c changelog check check-only f force gh gitea github l log mirror yingqing", "boolean"), ...flagList("limit n repo t tag target version", "value") }
|
||||
},
|
||||
"openapi": {
|
||||
"summary": "OpenAPI 规范导出与路径查询",
|
||||
"usage": "hose-use openapi [paths|info|--raw|keys]",
|
||||
"commands": {
|
||||
"paths": "列出路径概要",
|
||||
"info": "查看规范元数据",
|
||||
"keys": "查看企业接入密钥",
|
||||
"dump": "导出规范"
|
||||
},
|
||||
"aliases": [
|
||||
"schema",
|
||||
"spec"
|
||||
],
|
||||
"commandAliases": {
|
||||
"list": "paths",
|
||||
"ls": "paths",
|
||||
"summary": "info",
|
||||
"export": "dump",
|
||||
"raw": "dump"
|
||||
},
|
||||
flags: { ...flagList("raw elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"keys": {
|
||||
"summary": "企业 OpenAPI 接入凭证",
|
||||
"usage": "hose-use keys [--json] [--reveal] [--save]",
|
||||
"commands": {
|
||||
"keys": "读取当前企业密钥(默认脱敏)"
|
||||
},
|
||||
"options": [
|
||||
"--reveal 仅在明确授权后查看明文",
|
||||
"--save --yes 提取并持久化保存到本地企业配置"
|
||||
],
|
||||
"aliases": [
|
||||
"key",
|
||||
"secret",
|
||||
"secrets"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("elevate f force persist plain r reveal save", "boolean"), ...flagList("app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"store": {
|
||||
"summary": "已购应用与应用商店探查",
|
||||
"usage": "hose-use store <list|search|get>",
|
||||
"commands": {
|
||||
"list": "列出已购应用",
|
||||
"search": "搜索应用商店",
|
||||
"get": "查看应用详情",
|
||||
"keys": "查看企业接入密钥"
|
||||
},
|
||||
"aliases": [
|
||||
"market"
|
||||
],
|
||||
"commandAliases": {
|
||||
"key": "keys",
|
||||
"ls": "list",
|
||||
"find": "search",
|
||||
"info": "get",
|
||||
"detail": "get"
|
||||
},
|
||||
flags: { ...flagList("a all elevate f force persist plain r reveal save", "boolean"), ...flagList("id k keyword name app-key appKey key-id keyId", "value") }
|
||||
},
|
||||
"http": {
|
||||
"summary": "轻量 HTTP Server 与交互文档",
|
||||
"usage": "hose-use http [--port=<port>]",
|
||||
"commands": {
|
||||
"http": "启动 HTTP 服务"
|
||||
},
|
||||
"aliases": [
|
||||
"server",
|
||||
"web"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("h", "boolean-or-value"), ...flagList("host p port", "value") }
|
||||
},
|
||||
"service": {
|
||||
"summary": "常驻守护进程管理",
|
||||
"usage": "hose-use service <start|stop|restart|status|logs|poll>",
|
||||
"commands": {
|
||||
"start": "启动服务",
|
||||
"stop": "停止服务",
|
||||
"restart": "重启服务",
|
||||
"status": "查看服务状态",
|
||||
"logs": "查看服务日志",
|
||||
"poll": "轮询事件"
|
||||
},
|
||||
"aliases": [
|
||||
"daemon"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("count host limit n p port state-file stateFile", "value"), ...flagList("h", "boolean-or-value") }
|
||||
},
|
||||
"mcp": {
|
||||
"summary": "MCP Server",
|
||||
"usage": "hose-use mcp serve",
|
||||
"commands": {
|
||||
"serve": "启动 MCP 服务"
|
||||
},
|
||||
"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("logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export function resolveCommandMetadata(area?: string): { area: string; metadata: CliCommandMetadata } | undefined {
|
||||
if (!area) return undefined;
|
||||
const normalized = area.toLowerCase();
|
||||
for (const [name, metadata] of Object.entries(COMMAND_METADATA)) {
|
||||
if (name === normalized || metadata.aliases.includes(normalized)) return { area: name, metadata };
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveCommandAction(area: string | undefined, action?: string): string | undefined {
|
||||
const metadata = resolveCommandMetadata(area)?.metadata;
|
||||
const key = action?.toLowerCase();
|
||||
return key ? (metadata && Object.hasOwn(metadata.commandAliases, key) ? metadata.commandAliases[key] : key) : undefined;
|
||||
}
|
||||
|
||||
export function localCommandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
const resolved = resolveCommandMetadata(area);
|
||||
const flags = { ...resolved?.metadata.flags };
|
||||
const canonical = resolveCommandAction(area, action);
|
||||
// Most commands retain -c as the global corp selector. A few actions declare
|
||||
// a local meaning (bill code, node code, batch concurrency or bound rule codes).
|
||||
const localC = resolved?.area === "update"
|
||||
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|
||||
|| (resolved?.area === "workflow" && canonical === "node")
|
||||
|| (resolved?.area === "platform" && canonical === "record")
|
||||
|| (resolved?.area === "aipro" && canonical === "bind");
|
||||
if (!localC) delete flags.c;
|
||||
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
|
||||
// --run historically accepts a session ID and, for decide, an apply boolean.
|
||||
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
|
||||
return flags;
|
||||
}
|
||||
|
||||
export function commandFlags(area?: string, action?: string): Record<string, FlagKind> {
|
||||
return { ...GLOBAL_FLAGS, ...localCommandFlags(area, action) };
|
||||
}
|
||||
@@ -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,263 @@
|
||||
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 res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("ID01Xenwiu9w0D");
|
||||
expect(res.stdout).toContain("陈龙");
|
||||
});
|
||||
});
|
||||
@@ -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,146 @@
|
||||
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 explicitCorpId =
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
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?.() || [];
|
||||
let targetCorp =
|
||||
allCorps.find((c) => c.id === explicitCorpId || c.corpId === explicitCorpId) ||
|
||||
(runtime.selectedCorp?.id === explicitCorpId || runtime.selectedCorp?.corpId === explicitCorpId
|
||||
? runtime.selectedCorp
|
||||
: undefined);
|
||||
|
||||
let ticketId = stringOption(parsed.options, ["ticket", "ticket-id"]);
|
||||
|
||||
// 如果第 0 个参数不是企业,可能是工单编号
|
||||
if (!targetCorp && parsed.args[0]) {
|
||||
ticketId = parsed.args[0];
|
||||
targetCorp = runtime.selectedCorp ?? undefined;
|
||||
} else if (targetCorp && parsed.args[1]) {
|
||||
ticketId = parsed.args[1];
|
||||
}
|
||||
|
||||
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,190 @@
|
||||
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.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 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 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"]);
|
||||
|
||||
// 1. 若不要求保存落盘,仅生成直通免密链接输出
|
||||
if (!shouldSave && !shouldSwitch) {
|
||||
const sessionRes = await generateAssistSession(client, {
|
||||
corpId,
|
||||
ticketId,
|
||||
isAdmin,
|
||||
staffName,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(sessionRes, runtime.outputOptions),
|
||||
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 {
|
||||
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. 要求持久化落盘 / 切换为工作企业
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助平台换取免密凭证并落盘为本地企业配置",
|
||||
saveName || `企业 [${corpId}]`,
|
||||
{
|
||||
corpId,
|
||||
isAdmin,
|
||||
staffName: staffName || null,
|
||||
ticketId: ticketId || "自动选择最新有效工单",
|
||||
switchCurrent: shouldSwitch,
|
||||
overwrite,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
// 若指定了 --switch,切换当前激活企业
|
||||
if (shouldSwitch) {
|
||||
runtime.corpContext.switchCorp(corpConfig.id, true);
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
sessionResult,
|
||||
enterprise: {
|
||||
id: corpConfig.id,
|
||||
name: corpConfig.name,
|
||||
staffId: corpConfig.credentials.staffId,
|
||||
hasOpenApi: Boolean(corpConfig.credentials.appKey),
|
||||
switched: shouldSwitch,
|
||||
},
|
||||
}, 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`,
|
||||
激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 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,69 @@
|
||||
import { listAssistTickets } 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 handleTickets(
|
||||
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 tickets <企业ID>\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, 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,175 @@
|
||||
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) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
resolvedRecipient = {
|
||||
id: targetRecipient,
|
||||
name: targetRecipient,
|
||||
userRoleId: "",
|
||||
roles: [],
|
||||
};
|
||||
} else {
|
||||
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.name}" --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,
|
||||
};
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
handleGenerateCorpLink,
|
||||
handleSyncFromSeal,
|
||||
resolveTargetCorpByArgOrContext,
|
||||
} from "./corps.js";
|
||||
} from "./corps/index.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
@@ -253,7 +253,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp?.source),
|
||||
};
|
||||
|
||||
if (currentCorp?.session) {
|
||||
|
||||
@@ -1,752 +0,0 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption, numberOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getBillFlow,
|
||||
formatBillFlowOperator,
|
||||
getBillRisk,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
downloadBillAttachments,
|
||||
getFieldDictionary,
|
||||
approveBill,
|
||||
rejectBill,
|
||||
transferBill,
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
inspectFormSpecification,
|
||||
formatFormPriorityList,
|
||||
hasLinkageOverridePriority,
|
||||
} from "../../domains/bill/tools.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
const getClient = async () => {
|
||||
client ??= await createSessionClient(corp);
|
||||
return client;
|
||||
};
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"单据审批动作",
|
||||
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
|
||||
);
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(await getClient(), corpId, values);
|
||||
};
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, actionOptions());
|
||||
const result = await approveBill(await getClient(), corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "reject":
|
||||
case "deny": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
|
||||
const result = await rejectBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "transfer":
|
||||
case "shift": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await transferBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await addNodeBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "comment":
|
||||
case "remark": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
|
||||
const options = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
|
||||
const result = await commentBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined: {
|
||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||
if (mine) {
|
||||
const { handleTaskCommand } = await import("./task.js");
|
||||
return handleTaskCommand(
|
||||
{
|
||||
...parsed,
|
||||
area: "task",
|
||||
action: "submitted",
|
||||
},
|
||||
runtime
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code", "c"]);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
|
||||
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
|
||||
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
|
||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||
|
||||
const result = await searchAndFormatBills(await getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
b.billName,
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const filterSummary: string[] = [];
|
||||
if (since) filterSummary.push(`近 ${since}`);
|
||||
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
|
||||
if (code) filterSummary.push(`单号: ${code}`);
|
||||
if (keyword) {
|
||||
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
|
||||
}
|
||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||
if (state) filterSummary.push(`状态: ${state}`);
|
||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "get":
|
||||
case "show":
|
||||
case "find": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
for (let i = 0; i < bills.length; i++) {
|
||||
const b = bills[i];
|
||||
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
|
||||
outputs.push(` 单据 ID : ${b.billId}`);
|
||||
outputs.push(` 单据名称 : ${b.billName}`);
|
||||
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
|
||||
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
|
||||
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
|
||||
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
|
||||
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
|
||||
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
|
||||
outputs.push(` 创建时间 : ${b.createTime}`);
|
||||
outputs.push(` 更新时间 : ${b.updateTime}`);
|
||||
outputs.push(`\n --- 结构化表单字段明细 ---`);
|
||||
|
||||
const detailEntries = Object.entries(b.details);
|
||||
if (detailEntries.length === 0) {
|
||||
outputs.push(` (无额外字段数据)`);
|
||||
} else {
|
||||
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
|
||||
for (const [k, v] of detailEntries) {
|
||||
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: outputs.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities": {
|
||||
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
|
||||
const rows = entities.map((e, idx) => [
|
||||
idx + 1,
|
||||
e.id,
|
||||
e.name || "-",
|
||||
e.type || "-",
|
||||
e.fields.length,
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
|
||||
return {
|
||||
stdout: title + tableOutput + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(await getClient(), corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
|
||||
const report = await getBillRisk(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "budget":
|
||||
case "budgets": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
|
||||
const report = await getBillRisk(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
|
||||
const report = await getBillReferences(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
|
||||
const report = await getBillRelations(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "download":
|
||||
case "file-download": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "link":
|
||||
case "url": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use bill link <单号或ID>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到单据: ${target}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const item = items[0];
|
||||
const billId = item.billId;
|
||||
const billCode = item.billCode || target;
|
||||
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
|
||||
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
code: billCode,
|
||||
id: billId,
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
url: webUrl,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
`====== 合思单据 Web 直达链接 ======`,
|
||||
` 单据编号: ${billCode}`,
|
||||
` 单据 ID : ${billId}`,
|
||||
` 所属企业: ${corp.name} (${corpId})`,
|
||||
` 直达链接:`,
|
||||
` ${webUrl}`,
|
||||
``,
|
||||
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: text + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "spec":
|
||||
case "specification": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { addNodeBill, approveBill, commentBill, rejectBill, transferBill } from "../../../domains/bill/tools.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview } from "../../mutation.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleApprove(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, ctx.actionOptions());
|
||||
const result = await approveBill(await ctx.getClient(), corpId, target, ctx.actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleReject(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = ctx.actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
|
||||
const result = await rejectBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleTransfer(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await transferBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAddNode(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await addNodeBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleComment(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
|
||||
const options = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
|
||||
const result = await commentBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
/**
|
||||
* bill 命令族共享的执行上下文:封装 corp 解析、会话客户端懒加载缓存、
|
||||
* 写确认与审批动作选项解析。由 handleBillCommand 每次调用时构建一次。
|
||||
*/
|
||||
export type BillActionContext = ReturnType<typeof createBillActionContext>;
|
||||
|
||||
export function createBillActionContext(parsed: CliParsedArgs, runtime: CliRuntime) {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
const getClient = async () => {
|
||||
client ??= await createSessionClient(corp);
|
||||
return client;
|
||||
};
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"单据审批动作",
|
||||
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
|
||||
);
|
||||
}
|
||||
const { prompt } = await import("../../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(await getClient(), corpId, values);
|
||||
};
|
||||
|
||||
return {
|
||||
parsed,
|
||||
runtime,
|
||||
corp,
|
||||
corpId,
|
||||
action,
|
||||
getClient,
|
||||
actionTarget,
|
||||
requireWriteConfirmation,
|
||||
listOption,
|
||||
actionOptions,
|
||||
resolveApproverIds,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { formatBillFlowOperator, getBillFlow, getBillRisk } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleFlow(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(await ctx.getClient(), corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleRisk(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
|
||||
const report = await getBillRisk(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleBudget(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
|
||||
const report = await getBillRisk(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createBillActionContext } from "./context.js";
|
||||
import { handleApprove, handleReject, handleTransfer, handleAddNode, handleComment } from "./approve.js";
|
||||
import { handleList, handleGet, handleTrace } from "./search.js";
|
||||
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
|
||||
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
|
||||
import { handleSchema, handleLink, handleSpec } from "./meta.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const ctx = createBillActionContext(parsed, runtime);
|
||||
const action = ctx.action;
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree":
|
||||
return handleApprove(ctx);
|
||||
|
||||
case "reject":
|
||||
case "deny":
|
||||
return handleReject(ctx);
|
||||
|
||||
case "transfer":
|
||||
case "shift":
|
||||
return handleTransfer(ctx);
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign":
|
||||
return handleAddNode(ctx);
|
||||
|
||||
case "comment":
|
||||
case "remark":
|
||||
return handleComment(ctx);
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined:
|
||||
return handleList(ctx);
|
||||
|
||||
case "get":
|
||||
case "show":
|
||||
case "find":
|
||||
return handleGet(ctx);
|
||||
|
||||
case "trace":
|
||||
case "inspect":
|
||||
case "diagnose":
|
||||
return handleTrace(ctx);
|
||||
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities":
|
||||
return handleSchema(ctx);
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline":
|
||||
return handleFlow(ctx);
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings":
|
||||
return handleRisk(ctx);
|
||||
|
||||
case "budget":
|
||||
case "budgets":
|
||||
return handleBudget(ctx);
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve":
|
||||
return handleRefs(ctx);
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links":
|
||||
return handleRelations(ctx);
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files":
|
||||
return handleAttachments(ctx);
|
||||
|
||||
case "download":
|
||||
case "file-download":
|
||||
return handleDownload(ctx);
|
||||
|
||||
case "link":
|
||||
case "url":
|
||||
return handleLink(ctx);
|
||||
|
||||
case "spec":
|
||||
case "specification":
|
||||
return handleSpec(ctx);
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import {
|
||||
formatFormPriorityList,
|
||||
getFieldDictionary,
|
||||
getBillByCodeOrId,
|
||||
hasLinkageOverridePriority,
|
||||
inspectFormSpecification,
|
||||
} from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleSchema(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { runtime, corp, corpId } = ctx;
|
||||
const { entities } = await getFieldDictionary(await ctx.getClient(), corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
|
||||
const rows = entities.map((e, idx) => [
|
||||
idx + 1,
|
||||
e.id,
|
||||
e.name || "-",
|
||||
e.type || "-",
|
||||
e.fields.length,
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
|
||||
return {
|
||||
stdout: title + tableOutput + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleLink(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use bill link <单号或ID>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(await ctx.getClient(), corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到单据: ${target}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const item = items[0];
|
||||
const billId = item.billId;
|
||||
const billCode = item.billCode || target;
|
||||
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
|
||||
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
code: billCode,
|
||||
id: billId,
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
url: webUrl,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
`====== 合思单据 Web 直达链接 ======`,
|
||||
` 单据编号: ${billCode}`,
|
||||
` 单据 ID : ${billId}`,
|
||||
` 所属企业: ${corp.name} (${corpId})`,
|
||||
` 直达链接:`,
|
||||
` ${webUrl}`,
|
||||
``,
|
||||
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: text + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSpec(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await ctx.getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { downloadBillAttachments, getBillAttachments, getBillReferences, getBillRelations } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleRefs(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
|
||||
const report = await getBillReferences(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleRelations(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
|
||||
const report = await getBillRelations(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAttachments(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleDownload(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(await ctx.getClient(), corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||
if (mine) {
|
||||
const { handleTaskCommand } = await import("./../task.js");
|
||||
return handleTaskCommand(
|
||||
{
|
||||
...parsed,
|
||||
area: "task",
|
||||
action: "submitted",
|
||||
},
|
||||
runtime
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code", "c"]);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
|
||||
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
|
||||
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
|
||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||
|
||||
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
b.billName,
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const filterSummary: string[] = [];
|
||||
if (since) filterSummary.push(`近 ${since}`);
|
||||
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
|
||||
if (code) filterSummary.push(`单号: ${code}`);
|
||||
if (keyword) {
|
||||
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
|
||||
}
|
||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||
if (state) filterSummary.push(`状态: ${state}`);
|
||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleGet(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(await ctx.getClient(), corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map(async (bill) => getBillRisk(await ctx.getClient(), corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
for (let i = 0; i < bills.length; i++) {
|
||||
const b = bills[i];
|
||||
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
|
||||
outputs.push(` 单据 ID : ${b.billId}`);
|
||||
outputs.push(` 单据名称 : ${b.billName}`);
|
||||
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
|
||||
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
|
||||
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
|
||||
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
|
||||
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
|
||||
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
|
||||
outputs.push(` 创建时间 : ${b.createTime}`);
|
||||
outputs.push(` 更新时间 : ${b.updateTime}`);
|
||||
outputs.push(`\n --- 结构化表单字段明细 ---`);
|
||||
|
||||
const detailEntries = Object.entries(b.details);
|
||||
if (detailEntries.length === 0) {
|
||||
outputs.push(` (无额外字段数据)`);
|
||||
} else {
|
||||
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
|
||||
for (const [k, v] of detailEntries) {
|
||||
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: outputs.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "target", "flowId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要穿透诊断的单号或单据/流程 ID: hose-use bill trace <单号|ID> 或 hose-use flow get <单号|ID>");
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const report = await traceBillFlowDetail(client, corpId, target);
|
||||
|
||||
if (!report.found) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...report,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const approverNames = report.pendingApprovers
|
||||
.map((p) => (p.name ? `${p.name}${p.code ? ` (${p.code})` : ""}` : p.id))
|
||||
.filter(Boolean)
|
||||
.join("、");
|
||||
|
||||
const lines: string[] = [
|
||||
`====== 单据全域穿透诊断 [${report.billCode || report.target}] ======`,
|
||||
printKeyValue({
|
||||
"单据编号": report.billCode || "-",
|
||||
"单据 ID": report.billId || "-",
|
||||
"流程实例 (flowId)": report.flowId || "-",
|
||||
"单据类型": report.specificationName
|
||||
? `${report.specificationName}${report.specificationId ? ` (${report.specificationId})` : ""}`
|
||||
: "-",
|
||||
"单据标题": report.title || "-",
|
||||
"提报人员": report.submitter
|
||||
? `${report.submitter.name || "-"}${report.submitter.id ? ` (${report.submitter.id})` : ""}`
|
||||
: "-",
|
||||
"归属部门": report.department || "-",
|
||||
"提报时间": report.submitDate || "-",
|
||||
"单据金额": report.amount || "-",
|
||||
"全局流转状态": `${report.state || "-"} (${report.rawState || "-"})`,
|
||||
}),
|
||||
"",
|
||||
"── 🩺 待办与审批诊断 ──",
|
||||
` 阶段判定 : ${report.diagnostic.stageLabel}`,
|
||||
` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`,
|
||||
` 待办处理人: ${approverNames || "(当前无待办审批人)"}`,
|
||||
` 是否可审批: ${report.diagnostic.canApprove === null ? "未知(需核对当前身份的实际待办与权限)" : report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`,
|
||||
` 诊断结论 : ${report.diagnostic.summary}`,
|
||||
` 排障建议 : ${report.diagnostic.advice}`,
|
||||
];
|
||||
|
||||
if (report.timeline.length > 0) {
|
||||
lines.push("");
|
||||
lines.push("── ⏱️ 审批流转历史轨迹 (Timeline) ──");
|
||||
const timelineRows = report.timeline.map((item) => [
|
||||
`#${item.index}`,
|
||||
item.time || "-",
|
||||
item.nodeName || "-",
|
||||
item.operator?.name || item.operator?.id || (item.automatic ? "自动执行" : "-"),
|
||||
item.action || item.state || "-",
|
||||
item.comment ? (item.comment.length > 30 ? item.comment.slice(0, 30) + "..." : item.comment) : "-",
|
||||
]);
|
||||
lines.push(
|
||||
printTable(
|
||||
["#", "时间", "节点名称", "操作人", "动作", "审批意见"],
|
||||
timelineRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runAiProCli } from "../../aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { closeDatabase, getDatabase } from "../../core/db/index.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/repository.js";
|
||||
|
||||
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
repo.createRule({
|
||||
@@ -21,7 +21,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "../../core/config/loader.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
|
||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
@@ -75,6 +75,8 @@ export async function handleContextCommand(
|
||||
? {
|
||||
id: currentCorp.id,
|
||||
name: currentCorp.name,
|
||||
env: currentCorp.env,
|
||||
isTest: currentCorp.isTest,
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
@@ -93,6 +95,9 @@ export async function handleContextCommand(
|
||||
total: allCorps.length,
|
||||
validCount: validCorps.length,
|
||||
expiredCount: expiredCorps.length,
|
||||
prodCount: allCorps.filter((c) => c.env === "prod").length,
|
||||
testCount: allCorps.filter((c) => c.env === "test").length,
|
||||
demoCount: allCorps.filter((c) => c.env === "demo").length,
|
||||
activeCorpId: currentCorp?.id || null,
|
||||
},
|
||||
aiProGateway: {
|
||||
@@ -122,6 +127,9 @@ export async function handleContextCommand(
|
||||
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
|
||||
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
|
||||
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
|
||||
const prodCount = allCorps.filter((c) => c.env === "prod").length;
|
||||
const testCount = allCorps.filter((c) => c.env === "test").length;
|
||||
const demoCount = allCorps.filter((c) => c.env === "demo").length;
|
||||
|
||||
const scopesStr =
|
||||
scopes.length > 0
|
||||
@@ -131,13 +139,13 @@ export async function handleContextCommand(
|
||||
const lines = [
|
||||
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
|
||||
` 当前活跃账号 : ${accountStr}${userIdStr}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id}) [${formatCorpEnvLabel(currentCorp.env)}]` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
|
||||
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import { handleContextCommand } from "./context.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
const sampleCorps: CorpConfig[] = [
|
||||
{
|
||||
id: "corp_prod",
|
||||
name: "新转转集团",
|
||||
env: "prod",
|
||||
isTest: false,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_prod", staffId: "staff_1", accessToken: "t1" },
|
||||
},
|
||||
{
|
||||
id: "corp_test",
|
||||
name: "HAB对公测试环境",
|
||||
env: "test",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_test", staffId: "staff_2", accessToken: "t2" },
|
||||
},
|
||||
{
|
||||
id: "corp_demo",
|
||||
name: "营销中心演示企业",
|
||||
env: "demo",
|
||||
isTest: true,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: { corpId: "corp_demo", staffId: "staff_3", accessToken: "t3" },
|
||||
},
|
||||
];
|
||||
|
||||
function createMockRuntime(corps: CorpConfig[] = sampleCorps): CliRuntime {
|
||||
const context = new CorpContext(corps, { stateful: true, defaultCorpId: "corp_prod" });
|
||||
return {
|
||||
corpContext: context,
|
||||
selectedCorp: context.getCurrent()!,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CLI - corps environment attributes & filtering", () => {
|
||||
it("corps list displays environment column with emoji labels", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "list"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("环境");
|
||||
expect(res.stdout).toContain("🏭 正式");
|
||||
expect(res.stdout).toContain("🧪 测试");
|
||||
expect(res.stdout).toContain("🎪 演示");
|
||||
expect(res.stdout).toContain("共 3 家企业 (🏭 正式 1 家, 🧪 测试 1 家, 🎪 演示 1 家)");
|
||||
});
|
||||
|
||||
it("corps list --test filters only test and demo enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { test: true },
|
||||
raw: ["corps", "list", "--test"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("HAB对公测试环境");
|
||||
expect(res.stdout).toContain("营销中心演示企业");
|
||||
expect(res.stdout).not.toContain("新转转集团");
|
||||
expect(res.stdout).toContain("已筛选显示 2 家");
|
||||
});
|
||||
|
||||
it("corps list --prod filters only production enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { prod: true },
|
||||
raw: ["corps", "list", "--prod"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("新转转集团");
|
||||
expect(res.stdout).not.toContain("HAB对公测试环境");
|
||||
expect(res.stdout).not.toContain("营销中心演示企业");
|
||||
expect(res.stdout).toContain("已筛选显示 1 家");
|
||||
});
|
||||
|
||||
it("corps list --env=demo filters precisely demo enterprises", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "list",
|
||||
args: [],
|
||||
options: { env: "demo" },
|
||||
raw: ["corps", "list", "--env=demo"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("营销中心演示企业");
|
||||
expect(res.stdout).not.toContain("新转转集团");
|
||||
expect(res.stdout).not.toContain("HAB对公测试环境");
|
||||
});
|
||||
|
||||
it("corps tag requires mutation confirmation unless confirmed or dry-run", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
await expect(
|
||||
handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "tag",
|
||||
args: ["corp_prod"],
|
||||
options: { test: true },
|
||||
raw: ["corps", "tag", "corp_prod", "--test"],
|
||||
},
|
||||
runtime
|
||||
)
|
||||
).rejects.toThrow("拒绝执行设置企业环境属性");
|
||||
});
|
||||
|
||||
it("corps tag previews change under --dry-run", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "tag",
|
||||
args: ["corp_prod"],
|
||||
options: { test: true, "dry-run": true },
|
||||
raw: ["corps", "tag", "corp_prod", "--test", "--dry-run"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("设置企业环境属性");
|
||||
expect(res.stdout).toContain("newEnv: test");
|
||||
});
|
||||
|
||||
it("corps current displays environment attribute label", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "current",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["corps", "current"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("环境属性");
|
||||
expect(res.stdout).toContain("🏭 正式");
|
||||
});
|
||||
|
||||
it("context command reports environment counts and current corp env tag", async () => {
|
||||
const runtime = createMockRuntime();
|
||||
const res = await handleContextCommand(
|
||||
{
|
||||
area: "context",
|
||||
action: "",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["context"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("新转转集团 (corp_prod) [🏭 正式]");
|
||||
expect(res.stdout).toContain("🏭 正式: 1 家, 🧪 测试: 1 家, 🎪 演示: 1 家");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
@@ -344,6 +344,61 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("supports dynamic staff switching via corps link [corp] --staff=<id>", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const corp = structuredClone(mockCorps[0]);
|
||||
Object.assign(corp.credentials, { appKey: "staff-switch-key", appSecurity: "staff-switch-security" });
|
||||
const dynamicRuntime = { ...searchRuntime, selectedCorp: corp, corpContext: { ...searchRuntime.corpContext, resolve: () => corp } } as CliRuntime;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
const body = url.includes("getAccessToken")
|
||||
? { value: { accessToken: "openapi-staff-switch", corporationId: "alphaPhysicalId", expireTime: Date.now() + 7200000 } }
|
||||
: url.includes("getProvisionalAuth")
|
||||
? { value: { message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=token-new-staff&ekbCorpId=alphaPhysicalId" } }
|
||||
: { items: [] };
|
||||
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "link",
|
||||
args: ["corpAlpha"],
|
||||
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF" },
|
||||
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF"],
|
||||
},
|
||||
dynamicRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.preserveSensitiveStdout).toBe(true);
|
||||
expect(res.stdout).toContain("NEW_ADMIN_STAFF");
|
||||
expect(res.stdout).toContain("动态换签");
|
||||
|
||||
// --json 模式验证
|
||||
const jsonRuntime = { ...dynamicRuntime, jsonMode: true };
|
||||
const jsonRes = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "link",
|
||||
args: ["corpAlpha"],
|
||||
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF", json: true },
|
||||
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF", "--json"],
|
||||
},
|
||||
jsonRuntime
|
||||
);
|
||||
expect(jsonRes.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(jsonRes.stdout);
|
||||
expect(parsed.dynamicStaff).toBe(true);
|
||||
expect(parsed.staffId).toBe("alphaPhysicalId:NEW_ADMIN_STAFF");
|
||||
expect(corp.credentials.accessToken).toBe("token-alpha");
|
||||
expect(corp.credentials.staffId).toBe("STAFF_001");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("supports corps add-persistent --dry-run", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,97 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../../core/auth/login.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corpId = parsed.args[0];
|
||||
if (!corpId) {
|
||||
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`);
|
||||
|
||||
const success = runtime.corpContext.switchCorp(corpId);
|
||||
if (!success) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose-use corps list 查看可用列表。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const current = runtime.corpContext.getCurrent();
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const envLabel = formatCorpEnvLabel(current?.env);
|
||||
return {
|
||||
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id}) [${envLabel}]\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const current = runtime.selectedCorp;
|
||||
if (!current) {
|
||||
return { stdout: "", stderr: "未选中任何企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(current);
|
||||
const isPersistent = canRefreshCorpAccessToken(current);
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
"企业 ID": current.id,
|
||||
"企业名称": current.name,
|
||||
"环境属性": formatCorpEnvLabel(current.env),
|
||||
"员工工号": current.credentials.staffId,
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent, hasOpenApi ? "openapi" : current.source),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
};
|
||||
|
||||
if (current.session) {
|
||||
if (current.session.loginTime) {
|
||||
pairs["会话创建时间"] = new Date(current.session.loginTime).toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
if (current.session.platform) {
|
||||
pairs["官方平台类型"] = current.session.platform;
|
||||
}
|
||||
if (current.session.isAssistPlatform) {
|
||||
pairs["协助登录模式"] = "是 (Assist Platform)";
|
||||
if (current.session.operationUserName || current.session.operationUserId) {
|
||||
pairs["协助操作人员"] = `${current.session.operationUserName || ""} (${current.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (current.session.assistId) {
|
||||
pairs["协助会话 ID"] = current.session.assistId;
|
||||
}
|
||||
}
|
||||
if (current.session.cellphone) {
|
||||
pairs["绑定手机号码"] = current.session.cellphone;
|
||||
}
|
||||
if (current.session.isAdmin !== undefined) {
|
||||
pairs["是否企业管理"] = current.session.isAdmin ? "是" : "否";
|
||||
}
|
||||
}
|
||||
|
||||
const output = printKeyValue(pairs);
|
||||
|
||||
return {
|
||||
stdout: `====== 当前激活企业 ======\n${output}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
elevateCorpWithOpenApiKey,
|
||||
extractOpenApiKeysFromLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
maskOpenApiSecurity,
|
||||
onboardHosePersistent,
|
||||
syncOpenApiFromSealUse,
|
||||
} from "../../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleAddPersistent(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
let jsonPayload: Record<string, unknown> = {};
|
||||
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
|
||||
if (rawJsonArg) {
|
||||
try {
|
||||
jsonPayload = JSON.parse(rawJsonArg);
|
||||
} catch {
|
||||
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
const appKey =
|
||||
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
|
||||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
|
||||
const appSecurity =
|
||||
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
|
||||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
|
||||
const domain =
|
||||
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
|
||||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
|
||||
const corpId =
|
||||
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
|
||||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
|
||||
const staffId =
|
||||
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
|
||||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
|
||||
const staffName =
|
||||
stringOption(parsed.options, ["staff-name", "staffName"]) ||
|
||||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
|
||||
const staffPhone =
|
||||
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
|
||||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
|
||||
const role =
|
||||
stringOption(parsed.options, ["role"]) ||
|
||||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
|
||||
const name =
|
||||
stringOption(parsed.options, ["name"]) ||
|
||||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
|
||||
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
|
||||
source: "openapi",
|
||||
appKey,
|
||||
domain: domain || "auto-probe",
|
||||
staffId: staffId || "auto-discover",
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"通过 OpenAPI 持久化密钥接入企业",
|
||||
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
|
||||
);
|
||||
|
||||
const saved = await onboardHosePersistent({
|
||||
name,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
staffName,
|
||||
staffPhone,
|
||||
role,
|
||||
force,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${saved.id}.json`);
|
||||
const summaryText = printKeyValue({
|
||||
"企业名称": saved.name,
|
||||
"企业 ID": saved.id,
|
||||
"服务节点": saved.baseUrl,
|
||||
"员工工号": saved.credentials.staffId,
|
||||
"员工姓名": saved.staffName || saved.session?.staffName || "-",
|
||||
"接入账号 (appKey)": saved.credentials.appKey,
|
||||
"凭证来源": formatSourceLabel(saved.source, true),
|
||||
"保存路径": savedPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleExtractKeys(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
|
||||
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
|
||||
save: true,
|
||||
overwrite,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接提取并持久化 OpenAPI 密钥",
|
||||
`hose-use corps extract-keys "<url>" --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
|
||||
save,
|
||||
name,
|
||||
overwrite,
|
||||
force,
|
||||
appKey,
|
||||
keyId,
|
||||
});
|
||||
|
||||
const formattedKeys = extracted.keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || "-",
|
||||
appKey: k.appKey,
|
||||
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
}));
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: extracted.corpId,
|
||||
corpName: extracted.corpName || extracted.corpId,
|
||||
baseUrl: extracted.baseUrl,
|
||||
staffId: extracted.staffId,
|
||||
keyCount: formattedKeys.length,
|
||||
keys: formattedKeys,
|
||||
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = formattedKeys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name,
|
||||
k.appKey,
|
||||
k.appSecurity,
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
|
||||
const savedNotice = extracted.savedCorp
|
||||
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleElevateCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], true);
|
||||
|
||||
if (elevateAll) {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
|
||||
count: allCorps.length,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量提取并持久化全部企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate --all --yes`
|
||||
);
|
||||
|
||||
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
|
||||
for (const corp of allCorps) {
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
|
||||
continue;
|
||||
}
|
||||
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
|
||||
if (selected) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
|
||||
} else {
|
||||
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
|
||||
return {
|
||||
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate ${targetCorp.id} --yes`
|
||||
);
|
||||
|
||||
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
|
||||
appKey,
|
||||
keyId,
|
||||
force,
|
||||
});
|
||||
|
||||
if (!selected) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: maskOpenApiSecurity(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
persistent: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSyncFromSeal(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
|
||||
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
|
||||
const verify = booleanOption(parsed.options, ["verify"], false);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
|
||||
filter: filter || null,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从 seal-use 同步企业 OpenAPI 持久化密钥",
|
||||
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
|
||||
);
|
||||
|
||||
const synced = await syncOpenApiFromSealUse({
|
||||
filter,
|
||||
sealEnterprisesDir: sealDir,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(synced, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (synced.items.length === 0) {
|
||||
return {
|
||||
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = synced.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.corpId,
|
||||
item.name,
|
||||
item.appKey,
|
||||
item.staffId,
|
||||
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
|
||||
]);
|
||||
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { stringOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleSearch } from "./query.js";
|
||||
import { handleSwitch, handleCurrent } from "./context.js";
|
||||
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
|
||||
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
|
||||
import { handleTagCorp } from "./tag.js";
|
||||
import { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
// 供 auth.ts 等跨命令复用的 handler 与 helper 维持原有命名导出。
|
||||
export { handleGenerateCorpLink } from "./link.js";
|
||||
export { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
export { handleTagCorp } from "./tag.js";
|
||||
export { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "search":
|
||||
case "find":
|
||||
case "query":
|
||||
case "filter":
|
||||
return handleSearch(parsed, runtime);
|
||||
case "tag":
|
||||
case "set-env":
|
||||
case "mark":
|
||||
return handleTagCorp(parsed, runtime);
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "probe-hose":
|
||||
return handleProbeHose(parsed, runtime);
|
||||
case "hose-staffs":
|
||||
return handleHoseStaffs(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, tag, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function printCorpsHelp(): string {
|
||||
return `
|
||||
用法:
|
||||
hose-use corps <子命令> [参数] [选项]
|
||||
|
||||
子命令:
|
||||
list 列出本地已保存的所有企业配置 (支持 --test, --prod, --demo, --env 筛选,别名: ls)
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId, env,别名: find)
|
||||
tag [企业ID] 标记企业环境属性 (--test / --prod / --demo / --env=<env>) 或 --migrate-all 批量升级持久化 (别名: set-env)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
|
||||
[--staff=<姓名|手机号|ID>] 动态指定换签身份
|
||||
[--persist] 将新身份持久化为企业默认操作人
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
|
||||
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
|
||||
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
|
||||
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
|
||||
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
|
||||
|
||||
选项:
|
||||
--test 筛选测试环境企业 (corps list)
|
||||
--prod 筛选正式生产企业 (corps list)
|
||||
--demo 筛选演示/POC企业 (corps list)
|
||||
--json, -j 以 JSON 格式输出
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
示例:
|
||||
hose-use corps list
|
||||
hose-use corps list --test
|
||||
hose-use corps list --prod
|
||||
hose-use corps tag ID01uzxB4x07fh --test --yes
|
||||
hose-use corps tag ID01PH4Q5CJboX --prod --yes
|
||||
hose-use corps tag --migrate-all --yes
|
||||
`.trim();
|
||||
}
|
||||
|
||||
function handleCorpsHelp(): CliResult {
|
||||
return {
|
||||
stdout: printCorpsHelp() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
importFromLink,
|
||||
} from "../../../core/auth/login.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
fetchHoseOpenApiAccessToken,
|
||||
fetchHoseStaffDetails,
|
||||
getCorpOpenApiCredentials,
|
||||
listHoseStaffsByOpenApi,
|
||||
normalizeBaseUrl,
|
||||
} from "../../../core/auth/openapi-v1.js";
|
||||
import { searchStaffs } from "../../../domains/contact/tools.js";
|
||||
import { NotFoundError, ValidationError } from "../../../core/errors.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { prompt } from "../../helpers.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function resolveStaffForLink(
|
||||
corp: CorpConfig,
|
||||
staffQuery: string
|
||||
): Promise<{ staffId: string; staffName?: string }> {
|
||||
const q = staffQuery.trim();
|
||||
if (!q) {
|
||||
throw new ValidationError("员工检索条件不能为空");
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
|
||||
// 1. 如果输入本身就是完整 staffId 或 ID01 开头的工号
|
||||
if (q.includes(":") || (q.startsWith("ID01") && !q.includes(" "))) {
|
||||
const fullId = q.includes(":") ? q : `${corpId}:${q}`;
|
||||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||||
if (openApiCreds) {
|
||||
try {
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||
appKey: openApiCreds.appKey,
|
||||
appSecurity: openApiCreds.appSecurity,
|
||||
baseUrl,
|
||||
});
|
||||
const details = await fetchHoseStaffDetails(baseUrl, openapiToken, [fullId]);
|
||||
if (details.length > 0 && details[0]?.name) {
|
||||
return { staffId: fullId, staffName: details[0].name };
|
||||
}
|
||||
} catch {
|
||||
// fallback to using fullId
|
||||
}
|
||||
}
|
||||
return { staffId: fullId };
|
||||
}
|
||||
|
||||
// 2. 若企业已配置 OpenAPI 密钥,优先在管理员(admin 角色)中查找
|
||||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||||
if (openApiCreds) {
|
||||
try {
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const staffRes = await listHoseStaffsByOpenApi({
|
||||
appKey: openApiCreds.appKey,
|
||||
appSecurity: openApiCreds.appSecurity,
|
||||
domain: baseUrl,
|
||||
role: "admin",
|
||||
});
|
||||
|
||||
// 优先级 1: 姓名或手机号精确匹配
|
||||
const exactMatch = staffRes.staffs.find(
|
||||
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
|
||||
);
|
||||
if (exactMatch) {
|
||||
return { staffId: exactMatch.id, staffName: exactMatch.name };
|
||||
}
|
||||
|
||||
// 优先级 2: 姓名包含模糊匹配
|
||||
const fuzzyMatch = staffRes.staffs.find((s) => s.name && s.name.includes(q));
|
||||
if (fuzzyMatch) {
|
||||
return { staffId: fuzzyMatch.id, staffName: fuzzyMatch.name };
|
||||
}
|
||||
} catch {
|
||||
// 容错并回退至通讯录查询
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 通道 3: 通讯录常规检索
|
||||
try {
|
||||
const matchedStaffs = await searchStaffs(corp, { keyword: q, limit: 10 });
|
||||
if (matchedStaffs.length > 0) {
|
||||
const exact = matchedStaffs.find(
|
||||
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
|
||||
);
|
||||
const chosen = exact || matchedStaffs[0];
|
||||
const normalizedId = chosen.id.includes(":") ? chosen.id : `${corpId}:${chosen.id}`;
|
||||
return { staffId: normalizedId, staffName: chosen.name };
|
||||
}
|
||||
} catch {
|
||||
// 忽略通讯录未配置异常
|
||||
}
|
||||
|
||||
throw new NotFoundError(
|
||||
`未在企业 [${corp.name}] 中找到匹配 "${q}" 的员工或管理员。请核对姓名/手机号,或直接传入完整员工工号 (staffId)。`
|
||||
);
|
||||
}
|
||||
|
||||
export async function handleGenerateCorpLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0];
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const expiresIn =
|
||||
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
|
||||
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
||||
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
||||
const staffInput = stringOption(parsed.options, ["staff", "user", "operator"]);
|
||||
const persistStaff = booleanOption(parsed.options, ["persist", "save", "save-staff"]);
|
||||
|
||||
let resolvedStaff: { staffId: string; staffName?: string } | undefined;
|
||||
if (staffInput) {
|
||||
resolvedStaff = await resolveStaffForLink(targetCorp, staffInput);
|
||||
}
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
|
||||
expiresIn,
|
||||
pageType,
|
||||
force,
|
||||
staffId: resolvedStaff?.staffId,
|
||||
staffName: resolvedStaff?.staffName,
|
||||
persistStaff,
|
||||
});
|
||||
|
||||
const isSwitched = Boolean(resolvedStaff);
|
||||
const persistSaved = Boolean(persistStaff && isSwitched);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: linkRes.corpId,
|
||||
corpName: linkRes.corpName,
|
||||
staffId: linkRes.staffId,
|
||||
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
|
||||
link: linkRes.url,
|
||||
expiresAt: linkRes.expiresAt,
|
||||
expiresIn: linkRes.expiresIn,
|
||||
token: linkRes.token,
|
||||
persistent: linkRes.persistent,
|
||||
method: linkRes.method,
|
||||
dynamicStaff: isSwitched,
|
||||
persisted: persistSaved,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思企业 Web 免密登录直达链接 ======`,
|
||||
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
|
||||
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}${isSwitched ? " (🔄 动态换签)" : ""}`,
|
||||
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
|
||||
` 过期时间 : ${linkRes.expiresAt}`,
|
||||
...(persistSaved ? [` 配置持久化: ✅ 已保存为该企业默认操作人`] : []),
|
||||
` 直达链接 :`,
|
||||
` ${linkRes.url}`,
|
||||
``,
|
||||
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
}
|
||||
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let targetCorpId = "";
|
||||
try {
|
||||
const parsedUrl = new URL(linkUrl);
|
||||
targetCorpId = parsedUrl.searchParams.get("ekbCorpId") || "";
|
||||
} catch {}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const existsAlready = Boolean(targetCorpId && existsSync(join(targetDir, `${targetCorpId}.json`)));
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接导入企业凭证",
|
||||
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
|
||||
{
|
||||
source: "assistance-link",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
alreadyExists: existsAlready,
|
||||
ttl: ttl || null,
|
||||
expires: expires || null,
|
||||
note: existsAlready && !overwrite ? "检测到本地已存在该企业配置,导入执行时请带上 --overwrite 参数" : undefined,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const nextConfirmCmd = existsAlready && !overwrite
|
||||
? `hose-use corps add-link <url> --overwrite --yes`
|
||||
: `hose-use corps add-link <url> --yes`;
|
||||
|
||||
const confirmOp = existsAlready && !overwrite
|
||||
? `从协助链接导入企业凭证(检测到目标企业 [${targetCorpId}] 已存在,需覆盖更新)`
|
||||
: "从协助链接导入企业凭证";
|
||||
|
||||
requireMutationConfirmation(parsed, runtime, confirmOp, nextConfirmCmd);
|
||||
|
||||
try {
|
||||
const corp = await importFromLink(linkUrl, {
|
||||
name,
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
"企业 ID": corp.id,
|
||||
"集群环境": corp.cluster || "app",
|
||||
"员工工号": corp.credentials.staffId,
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
if (corp.session?.isAssistPlatform) {
|
||||
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||
if (corp.session.operationUserName || corp.session.operationUserId) {
|
||||
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (corp.session.assistId) {
|
||||
summaryPairs["协助会话 ID"] = corp.session.assistId;
|
||||
}
|
||||
}
|
||||
|
||||
const summaryText = printKeyValue(summaryPairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { fetchHoseRoleDefGroups, listHoseStaffsByOpenApi, probeHoseDomain } from "../../../core/auth/login.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const probe = await probeHoseDomain(appKey, appSecurity, domain);
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
|
||||
const payload = {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
name: probe.corpName || probe.corpId,
|
||||
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
|
||||
roleGroups,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
|
||||
"企业 ID": payload.corpId,
|
||||
"企业名称": payload.name,
|
||||
"服务节点": payload.domain,
|
||||
"角色数量": payload.roleCount,
|
||||
})}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
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"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
|
||||
return {
|
||||
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
|
||||
import { getCorpEnv, isCorpTest } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, formatExpiresAt, formatSourceLabel, formatCorpEnvLabel } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
id: "配置ID",
|
||||
name: "企业名称",
|
||||
corpId: "企业ID",
|
||||
staffId: "员工工号",
|
||||
staffName: "员工姓名",
|
||||
accountId: "所属账号",
|
||||
env: "环境属性",
|
||||
};
|
||||
|
||||
export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k", "q", "name", "id"]);
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps search <关键词>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const kw = keyword.trim().toLowerCase();
|
||||
|
||||
// 从 CorpContext 中获取企业列表
|
||||
const rawCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: null;
|
||||
|
||||
const normalizedCorps = rawCorps
|
||||
? rawCorps.map((c) => {
|
||||
const hasOpenApi = Boolean(
|
||||
(c.credentials?.appKey || c.auth?.appKey) &&
|
||||
(c.credentials?.appSecurity || c.auth?.appSecurity)
|
||||
);
|
||||
const env = getCorpEnv(c);
|
||||
const test = isCorpTest(c);
|
||||
return {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.credentials?.corpId || c.id,
|
||||
staffId: c.staffId || c.credentials?.staffId || "",
|
||||
staffName: c.staffName || c.session?.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
hasOpenApi,
|
||||
env,
|
||||
isTest: test,
|
||||
};
|
||||
})
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.id,
|
||||
staffId: c.staffId || "",
|
||||
staffName: c.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
hasOpenApi: c.hasOpenApi,
|
||||
env: c.env || (c.isTest ? "test" : "prod"),
|
||||
isTest: c.isTest ?? (c.env !== "prod"),
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
|
||||
for (const corp of normalizedCorps) {
|
||||
const matchedFields: string[] = [];
|
||||
|
||||
if (corp.id && corp.id.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("id");
|
||||
}
|
||||
if (corp.name && corp.name.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("name");
|
||||
}
|
||||
if (corp.corpId && corp.corpId.toLowerCase().includes(kw) && !matchedFields.includes("corpId") && corp.corpId !== corp.id) {
|
||||
matchedFields.push("corpId");
|
||||
}
|
||||
if (corp.staffId && corp.staffId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffId");
|
||||
}
|
||||
if (corp.staffName && corp.staffName.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffName");
|
||||
}
|
||||
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("accountId");
|
||||
}
|
||||
if (corp.env && (corp.env.toLowerCase() === kw || (kw === "正式" && corp.env === "prod") || (kw === "测试" && corp.env === "test") || (kw === "演示" && corp.env === "demo"))) {
|
||||
matchedFields.push("env");
|
||||
}
|
||||
|
||||
if (matchedFields.length > 0) {
|
||||
matches.push({ ...corp, matchedFields });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
keyword: keyword.trim(),
|
||||
count: matches.length,
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: matches.map((m) => ({
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
corpId: m.corpId,
|
||||
env: m.env,
|
||||
isTest: m.isTest,
|
||||
staffId: m.staffId,
|
||||
staffName: m.staffName || undefined,
|
||||
accountId: m.accountId || undefined,
|
||||
source: m.source,
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
persistent: m.persistent,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (matches.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配 "${keyword.trim()}" 的企业配置\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = matches.map((m, i) => {
|
||||
const isCurrent = m.current;
|
||||
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
|
||||
return [
|
||||
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
formatCorpEnvLabel(m.env),
|
||||
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
|
||||
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
|
||||
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt, m.persistent, m.hasOpenApi ? "openapi" : m.source),
|
||||
];
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 企业搜索结果 (关键词: "${keyword.trim()}", 找到 ${matches.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业\n - 标记 [...] 为命中关键词的字段\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
|
||||
const filterTest = booleanOption(parsed.options, ["test", "t"]);
|
||||
const filterProd = booleanOption(parsed.options, ["prod", "production", "p"]);
|
||||
const filterDemo = booleanOption(parsed.options, ["demo"]);
|
||||
const filterEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
|
||||
|
||||
let filteredCorps = allCorps;
|
||||
if (filterTest) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.isTest || c.env === "test" || c.env === "demo");
|
||||
} else if (filterProd) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === "prod");
|
||||
} else if (filterDemo) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === "demo");
|
||||
} else if (filterEnv) {
|
||||
filteredCorps = filteredCorps.filter((c) => c.env === filterEnv);
|
||||
}
|
||||
|
||||
const prodCount = allCorps.filter((c) => c.env === "prod").length;
|
||||
const testCount = allCorps.filter((c) => c.env === "test").length;
|
||||
const demoCount = allCorps.filter((c) => c.env === "demo").length;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
total: allCorps.length,
|
||||
count: filteredCorps.length,
|
||||
summary: {
|
||||
prodCount,
|
||||
testCount,
|
||||
demoCount,
|
||||
},
|
||||
corporations: filteredCorps,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (allCorps.length === 0) {
|
||||
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (filteredCorps.length === 0) {
|
||||
return {
|
||||
stdout: `没有找到符合筛选条件的企业 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = filteredCorps.map((c, i) => [
|
||||
c.current ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
formatCorpEnvLabel(c.env),
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffId,
|
||||
formatSourceLabel(c.source, c.hasOpenApi),
|
||||
formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
rows
|
||||
);
|
||||
|
||||
const filterHint = (filteredCorps.length !== allCorps.length)
|
||||
? `已筛选显示 ${filteredCorps.length} 家 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`
|
||||
: `共 ${allCorps.length} 家企业 (🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`;
|
||||
|
||||
return {
|
||||
stdout: `====== 已配置企业列表 (${filterHint}) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 支持筛选: --test (仅测试/演示), --prod (仅正式生产), --env=<prod|test|demo>\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import type { CliRuntime } from "../../types.js";
|
||||
|
||||
export function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export function resolveTargetCorpByArgOrContext(
|
||||
targetArg: string | undefined,
|
||||
runtime: CliRuntime
|
||||
): CorpConfig | null {
|
||||
if (targetArg && !isHttpUrl(targetArg)) {
|
||||
try {
|
||||
return runtime.corpContext.resolve(targetArg);
|
||||
} catch {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
const kw = targetArg.trim().toLowerCase();
|
||||
const matched = allCorps.find(
|
||||
(c) =>
|
||||
c.id.toLowerCase() === kw ||
|
||||
(c.corpId && c.corpId.toLowerCase() === kw) ||
|
||||
c.name.toLowerCase().includes(kw)
|
||||
);
|
||||
if (matched) return matched;
|
||||
}
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { saveCorpConfig } from "../../../core/config/loader.js";
|
||||
import { CorpEnv, getCorpEnv } from "../../../core/config/types.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { formatCorpEnvLabel, printJson, printKeyValue, printTable } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleTagCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const isMigrateAll = booleanOption(parsed.options, ["migrate-all", "all", "upgrade-all", "a"]);
|
||||
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
|
||||
if (isMigrateAll) {
|
||||
if (allCorps.length === 0) {
|
||||
return { stdout: "未找到任何企业配置可供迁移升级。\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const previewList = allCorps.map((corp) => {
|
||||
const deducedEnv = getCorpEnv(corp);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
currentEnv: corp.env || "(未显式声明)",
|
||||
targetEnv: deducedEnv,
|
||||
targetIsTest: deducedEnv !== "prod",
|
||||
};
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量显式持久化升级所有企业环境属性",
|
||||
`共 ${allCorps.length} 家企业`,
|
||||
{
|
||||
total: allCorps.length,
|
||||
preview: previewList,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量显式持久化升级所有企业环境属性",
|
||||
"hose-use corps tag --migrate-all --yes"
|
||||
);
|
||||
|
||||
const savedPaths: string[] = [];
|
||||
for (const corp of allCorps) {
|
||||
const targetEnv = getCorpEnv(corp);
|
||||
const updated = {
|
||||
...corp,
|
||||
env: targetEnv,
|
||||
isTest: targetEnv !== "prod",
|
||||
};
|
||||
const filePath = saveCorpConfig(updated);
|
||||
savedPaths.push(filePath);
|
||||
runtime.corpContext.upsertCorp(updated, corp.id === runtime.selectedCorp?.id);
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
migrated: true,
|
||||
count: savedPaths.length,
|
||||
corporations: previewList,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = previewList.map((item, i) => [
|
||||
i + 1,
|
||||
formatCorpEnvLabel(item.targetEnv),
|
||||
item.id,
|
||||
item.name,
|
||||
item.targetEnv,
|
||||
item.targetIsTest ? "是" : "否",
|
||||
]);
|
||||
|
||||
const table = printTable(["#", "环境属性", "企业 ID", "企业名称", "写入环境值", "isTest"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功完成 ${savedPaths.length} 家企业配置环境属性的显式持久化升级:\n\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 单个企业打标
|
||||
const targetArg = parsed.args[0] || stringOption(parsed.options, ["id", "corp", "corpId"]);
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法:",
|
||||
" hose-use corps tag <企业ID|名称> [--test | --prod | --demo | --env=<prod|test|demo>] [--yes]",
|
||||
" hose-use corps tag --migrate-all [--yes] # 一键按名称智能初判持久化升级所有企业配置",
|
||||
"",
|
||||
"选项:",
|
||||
" --test, -t 标记为测试环境 (test)",
|
||||
" --prod, -p 标记为正式生产环境 (prod)",
|
||||
" --demo 标记为演示/POC环境 (demo)",
|
||||
" --env=<env> 显式指定环境属性 (prod / test / demo)",
|
||||
" --migrate-all 批量智能推导并持久化所有企业配置",
|
||||
" --dry-run 仅预览变更,不写入磁盘",
|
||||
" --yes, -y 确认执行写入",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const optTest = booleanOption(parsed.options, ["test", "t"]);
|
||||
const optProd = booleanOption(parsed.options, ["prod", "production", "p"]);
|
||||
const optDemo = booleanOption(parsed.options, ["demo"]);
|
||||
const optEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
|
||||
|
||||
let targetEnv: CorpEnv | undefined;
|
||||
if (optTest) {
|
||||
targetEnv = "test";
|
||||
} else if (optProd) {
|
||||
targetEnv = "prod";
|
||||
} else if (optDemo) {
|
||||
targetEnv = "demo";
|
||||
} else if (optEnv) {
|
||||
if (["prod", "test", "demo"].includes(optEnv)) {
|
||||
targetEnv = optEnv as CorpEnv;
|
||||
} else {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `错误: 非法的环境属性 "${optEnv}",仅支持 prod (正式生产), test (测试环境), demo (演示/POC)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetEnv) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `请指定要标记的环境属性 (--test, --prod, --demo 或 --env=<prod|test|demo>)。\n例如: hose-use corps tag ${targetCorp.id} --test --yes\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const changes = {
|
||||
corpId: targetCorp.id,
|
||||
name: targetCorp.name,
|
||||
currentEnv: targetCorp.env,
|
||||
newEnv: targetEnv,
|
||||
newIsTest: targetEnv !== "prod",
|
||||
};
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "设置企业环境属性", `${targetCorp.name} (${targetCorp.id})`, changes);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"设置企业环境属性",
|
||||
`hose-use corps tag ${targetCorp.id} --env=${targetEnv} --yes`
|
||||
);
|
||||
|
||||
const updatedCorp = {
|
||||
...targetCorp,
|
||||
env: targetEnv,
|
||||
isTest: targetEnv !== "prod",
|
||||
};
|
||||
|
||||
const filePath = saveCorpConfig(updatedCorp);
|
||||
runtime.corpContext.upsertCorp(updatedCorp, targetCorp.id === runtime.selectedCorp?.id);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
success: true,
|
||||
corpId: updatedCorp.id,
|
||||
name: updatedCorp.name,
|
||||
env: updatedCorp.env,
|
||||
isTest: updatedCorp.isTest,
|
||||
configFile: filePath,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const summary = printKeyValue({
|
||||
"企业名称": updatedCorp.name,
|
||||
"企业 ID": updatedCorp.id,
|
||||
"环境属性": `${formatCorpEnvLabel(updatedCorp.env)} (${updatedCorp.env})`,
|
||||
"是否测试企业 (isTest)": updatedCorp.isTest ? "是" : "否",
|
||||
"持久化配置文件": filePath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -516,7 +516,7 @@ export async function handleFeeTypeCommand(
|
||||
|
||||
// ── 8. 查看单据模板定义 (spec / specification) ─────────────────────────────
|
||||
if (["spec", "specification"].includes(action)) {
|
||||
const { handleBillCommand } = await import("./bill.js");
|
||||
const { handleBillCommand } = await import("./bill/index.js");
|
||||
return handleBillCommand({ ...parsed, area: "bill", action: "spec" }, runtime);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleFlowCommand } from "./flow.js";
|
||||
import { handleBillCommand } from "./bill/index.js";
|
||||
import { findCommandByArea } from "../registry.js";
|
||||
import * as sessionModule from "../../core/http/session-client.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
const mockCorp: CorpConfig = {
|
||||
id: "corp-test-1",
|
||||
name: "测试企业",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "mock-token",
|
||||
corpId: "corp-test-1",
|
||||
staffId: "corp-test-1:STAFF_TEST",
|
||||
},
|
||||
};
|
||||
|
||||
const mockRuntime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [mockCorp],
|
||||
getCurrent: () => mockCorp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => mockCorp,
|
||||
} as any,
|
||||
selectedCorp: mockCorp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
};
|
||||
|
||||
describe("CLI - flow & trace 全域透视与穿透诊断命令族", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
it("registry 正确注册 flow 命令与 trace 别名", () => {
|
||||
const flowDef = findCommandByArea("flow");
|
||||
expect(flowDef).toBeDefined();
|
||||
expect(flowDef?.area).toBe("flow");
|
||||
expect(flowDef?.aliases).toContain("trace");
|
||||
|
||||
const traceDef = findCommandByArea("trace");
|
||||
expect(traceDef).toBeDefined();
|
||||
expect(traceDef?.area).toBe("flow");
|
||||
});
|
||||
|
||||
it("未选中企业时返回错误并提示切换企业", async () => {
|
||||
const res = await handleFlowCommand(
|
||||
{
|
||||
area: "flow",
|
||||
action: "get",
|
||||
args: ["ZJ-001"],
|
||||
options: {},
|
||||
raw: ["flow", "get", "ZJ-001"],
|
||||
},
|
||||
{ ...mockRuntime, selectedCorp: null }
|
||||
);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("未选中企业");
|
||||
});
|
||||
|
||||
it("hose-use flow --help 输出帮助信息", async () => {
|
||||
const res = await handleFlowCommand(
|
||||
{
|
||||
area: "flow",
|
||||
action: undefined,
|
||||
args: [],
|
||||
options: { help: true },
|
||||
raw: ["flow", "--help"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("hose-use flow - 审批流全域透视与穿透诊断命令族");
|
||||
expect(res.stdout).toContain("hose-use flow get <单号|ID>");
|
||||
});
|
||||
|
||||
it("hose-use flow <单号> (位置参数) 自动识别并穿透诊断", async () => {
|
||||
const mockRawFlow = {
|
||||
id: "backlog-1",
|
||||
state: "APPROVING",
|
||||
flowId: {
|
||||
id: "flow-1",
|
||||
state: "APPROVING",
|
||||
form: {
|
||||
code: "ZJ-20261014-001",
|
||||
title: "转转合同付款",
|
||||
payMoney: "12500.00",
|
||||
submitterId: { id: "u1", name: "张敏" },
|
||||
expenseDepartment: { name: "财务部" },
|
||||
},
|
||||
plan: {
|
||||
nodes: [
|
||||
{ id: "n1", name: "出纳打款", state: "APPROVING", approverId: { id: "u2", name: "李出纳" } },
|
||||
],
|
||||
},
|
||||
logs: [],
|
||||
},
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
|
||||
} as any;
|
||||
|
||||
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
|
||||
|
||||
const res = await handleFlowCommand(
|
||||
{
|
||||
area: "flow",
|
||||
action: "zj-20261014-001",
|
||||
args: [],
|
||||
positional: ["flow", "ZJ-20261014-001"],
|
||||
options: {},
|
||||
raw: ["flow", "ZJ-20261014-001"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("单据全域穿透诊断 [ZJ-20261014-001]");
|
||||
expect(res.stdout).toContain("提报人员");
|
||||
expect(res.stdout).toContain("张敏");
|
||||
expect(res.stdout).toContain("待办处理人: 李出纳");
|
||||
expect(res.stdout).toContain("出纳打款");
|
||||
});
|
||||
|
||||
it("hose-use flow get <单号> --json 结构化输出", async () => {
|
||||
const mockRawFlow = {
|
||||
id: "backlog-2",
|
||||
state: "PAYING",
|
||||
flowId: {
|
||||
id: "flow-2",
|
||||
state: "PAYING",
|
||||
form: {
|
||||
code: "ZJ-20261014-002",
|
||||
title: "资金调拨",
|
||||
},
|
||||
plan: {
|
||||
nodes: [
|
||||
{ id: "n1", name: "出纳打款", state: "APPROVING" },
|
||||
],
|
||||
},
|
||||
logs: [],
|
||||
},
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
|
||||
} as any;
|
||||
|
||||
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
|
||||
|
||||
const res = await handleFlowCommand(
|
||||
{
|
||||
area: "flow",
|
||||
action: "get",
|
||||
args: ["ZJ-20261014-002"],
|
||||
positional: ["flow", "get", "ZJ-20261014-002"],
|
||||
options: { json: true },
|
||||
raw: ["flow", "get", "ZJ-20261014-002", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(res.stdout);
|
||||
expect(parsed.found).toBe(true);
|
||||
expect(parsed.billCode).toBe("ZJ-20261014-002");
|
||||
expect(parsed.diagnostic.stage).toBe("PAYING");
|
||||
expect(parsed.diagnostic.canApprove).toBe(false);
|
||||
expect(parsed.diagnostic.advice).toContain("400");
|
||||
});
|
||||
|
||||
it("hose-use bill trace <单号> 平滑集成并完成诊断", async () => {
|
||||
const mockRawFlow = {
|
||||
id: "backlog-3",
|
||||
state: "APPROVING",
|
||||
flowId: {
|
||||
id: "flow-3",
|
||||
state: "APPROVING",
|
||||
form: {
|
||||
code: "BX-999",
|
||||
title: "日常差旅报销",
|
||||
},
|
||||
plan: {
|
||||
nodes: [
|
||||
{ id: "n1", name: "总监审批", state: "APPROVING" },
|
||||
],
|
||||
},
|
||||
logs: [],
|
||||
},
|
||||
};
|
||||
|
||||
const mockClient = {
|
||||
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
|
||||
} as any;
|
||||
|
||||
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
|
||||
|
||||
const res = await handleBillCommand(
|
||||
{
|
||||
area: "bill",
|
||||
action: "trace",
|
||||
args: ["BX-999"],
|
||||
positional: ["bill", "trace", "BX-999"],
|
||||
options: {},
|
||||
raw: ["bill", "trace", "BX-999"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("单据全域穿透诊断 [BX-999]");
|
||||
expect(res.stdout).toContain("总监审批");
|
||||
expect(res.stdout).toContain("是否可审批: 未知");
|
||||
});
|
||||
|
||||
it("未找到单据时返回 exitCode 1 与排障建议", async () => {
|
||||
const mockClient = {
|
||||
post: async () => new Response(JSON.stringify({ items: [] })),
|
||||
} as any;
|
||||
|
||||
spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient));
|
||||
|
||||
const res = await handleFlowCommand(
|
||||
{
|
||||
area: "flow",
|
||||
action: "get",
|
||||
args: ["UNKNOWN-BILL"],
|
||||
positional: ["flow", "get", "UNKNOWN-BILL"],
|
||||
options: {},
|
||||
raw: ["flow", "get", "UNKNOWN-BILL"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("[NOT FOUND]");
|
||||
expect(res.stderr).toContain("诊断提示");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createBillActionContext } from "./bill/context.js";
|
||||
import { handleTrace, handleList } from "./bill/search.js";
|
||||
import { handleFlow, handleRisk } from "./bill/flow.js";
|
||||
import { handleApprove, handleReject } from "./bill/approve.js";
|
||||
|
||||
function printFlowHelp(): string {
|
||||
return [
|
||||
"hose-use flow - 审批流全域透视与穿透诊断命令族",
|
||||
"",
|
||||
"用法:",
|
||||
" hose-use flow <单号|ID> 等价于 flow get/trace,快速透视单据流转与诊断待办",
|
||||
" hose-use flow get <单号|ID> 深度穿透单据全貌、当前驻留节点与 400 待办根因诊断",
|
||||
" hose-use flow trace <单号|ID> (别名) 同 flow get",
|
||||
" hose-use flow history <单号|ID> 查看审批历史流转时间线与后续节点",
|
||||
" hose-use flow risk <单号|ID> 查看费控与合规风控诊断",
|
||||
" hose-use flow list [options] 列出当前待审批/已审批单据流",
|
||||
" hose-use flow approve <单号|ID> 执行审批同意 (受 --dry-run 与 --yes 约束)",
|
||||
" hose-use flow reject <单号|ID> 执行审批驳回 (受 --dry-run 与 --yes 约束)",
|
||||
"",
|
||||
"选项:",
|
||||
" --corp=<id> 指定操作企业 (默认激活企业)",
|
||||
" --json 以 JSON 结构化格式输出诊断数据",
|
||||
" --verbose 显示完整调试信息",
|
||||
" -h, --help 显示帮助信息",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export async function handleFlowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
if (parsed.options.help || parsed.action === "help") {
|
||||
return {
|
||||
stdout: printFlowHelp() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const args = [...parsed.args];
|
||||
|
||||
// 1. 无动作无参数且无 --code/--id 选项时,默认展示列表
|
||||
if (!action && args.length === 0 && !parsed.options.code && !parsed.options.id) {
|
||||
const ctx = createBillActionContext(parsed, runtime);
|
||||
return handleList(ctx);
|
||||
}
|
||||
|
||||
// 2. 识别透视与穿透类动词
|
||||
const flowTraceActions = new Set(["get", "trace", "inspect", "diagnose", "show", "find"]);
|
||||
if (action && flowTraceActions.has(action)) {
|
||||
const ctx = createBillActionContext(parsed, runtime);
|
||||
return handleTrace(ctx);
|
||||
}
|
||||
|
||||
// 3. 识别其他常用审批流动作
|
||||
const flowOtherActions = new Set(["history", "records", "timeline", "risk", "list", "search", "approve", "agree", "reject", "deny"]);
|
||||
if (action && flowOtherActions.has(action)) {
|
||||
const ctx = createBillActionContext(parsed, runtime);
|
||||
switch (action) {
|
||||
case "history":
|
||||
case "records":
|
||||
case "timeline":
|
||||
return handleFlow(ctx);
|
||||
case "risk":
|
||||
return handleRisk(ctx);
|
||||
case "list":
|
||||
case "search":
|
||||
return handleList(ctx);
|
||||
case "approve":
|
||||
case "agree":
|
||||
return handleApprove(ctx);
|
||||
case "reject":
|
||||
case "deny":
|
||||
return handleReject(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 用户直接输入单号:hose-use flow <单号|ID>
|
||||
// 从原始 positional[1] 获取未经 lowercase 转换的原始单号/ID
|
||||
const rawTarget = parsed.positional?.[1] || parsed.action;
|
||||
const rewrittenParsed: CliParsedArgs = {
|
||||
...parsed,
|
||||
action: "trace",
|
||||
args: [rawTarget!, ...args],
|
||||
};
|
||||
const ctx = createBillActionContext(rewrittenParsed, runtime);
|
||||
return handleTrace(ctx);
|
||||
}
|
||||
+7
-15
@@ -1,24 +1,16 @@
|
||||
import { spawn } from "child_process";
|
||||
import { join } from "path";
|
||||
import { usageError } from "../errors.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "../types.js";
|
||||
|
||||
export async function handleMcpCommand(
|
||||
parsed: CliParsedArgs,
|
||||
options: CliRunOptions
|
||||
): Promise<CliResult> {
|
||||
const appRoot = options.appRoot || process.cwd();
|
||||
const serverPath = join(appRoot, "src", "server.ts");
|
||||
|
||||
console.error("启动 MCP Server on stdio...");
|
||||
const child = spawn("bun", ["run", serverPath], {
|
||||
stdio: "inherit",
|
||||
cwd: appRoot,
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
child.on("exit", () => resolve());
|
||||
});
|
||||
if (parsed.action && parsed.action !== "serve") {
|
||||
throw usageError(`未知 mcp 子命令: ${parsed.action}。用法: hose-use mcp [serve]`);
|
||||
}
|
||||
// Lazy loading avoids a runner -> registry -> server -> runner startup cycle.
|
||||
const { startServer } = await import("../../server.js");
|
||||
await startServer(options);
|
||||
|
||||
return { stdout: "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handlePlatformCommand } from "./platform.js";
|
||||
import { handlePlatformCommand } from "./platform/index.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import * as services from "../../domains/datalink/services.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
@@ -255,4 +255,275 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(res.stdout).toContain("Dry-Run 预览");
|
||||
expect(editSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("platform records 支持 --sum 数学核算与 --group-by 分组统计", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
|
||||
...mockEntity,
|
||||
fields: [
|
||||
{ name: "fee", label: "租赁费用", type: "money" },
|
||||
{ name: "status", label: "状态", type: "text" },
|
||||
],
|
||||
} as any));
|
||||
spies.push(
|
||||
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
|
||||
data: [
|
||||
{ id: "1", fee: 1000, status: "A" },
|
||||
{ id: "2", fee: 2000, status: "A" },
|
||||
{ id: "3", fee: 3000, status: "B" },
|
||||
],
|
||||
total: 3,
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "records",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { sum: "租赁费用", "group-by": "状态" },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--sum=租赁费用", "--group-by=状态"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("台账数学聚合核算");
|
||||
expect(res.stdout).toContain("总合计 (SUM)");
|
||||
expect(res.stdout).toContain("6000");
|
||||
expect(res.stdout).toContain("按 [状态] 分组统计");
|
||||
});
|
||||
|
||||
it("platform audit 支持 --check-continuous 与 --expect 基线离群诊断", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
|
||||
...mockEntity,
|
||||
fields: [
|
||||
{ name: "seq", label: "摊销序号", type: "number" },
|
||||
{ name: "fee", label: "租赁费用", type: "money" },
|
||||
],
|
||||
} as any));
|
||||
spies.push(
|
||||
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
|
||||
data: [
|
||||
{ id: "1", seq: 1, fee: 78787.55 },
|
||||
{ id: "2", seq: 3, fee: 0 },
|
||||
],
|
||||
total: 2,
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "audit",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { "check-continuous": "摊销序号", expect: "租赁费用 ~= 78787.55" },
|
||||
raw: ["platform", "audit", "platform-1", "entity-1", "--check-continuous=摊销序号", "--expect=租赁费用 ~= 78787.55"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("台账序号连续性体检");
|
||||
expect(res.stdout).toContain("断层缺失期数 (MISSING)");
|
||||
expect(res.stdout).toContain("缺少 [2]");
|
||||
expect(res.stdout).toContain("基线离群异常核对");
|
||||
expect(res.stdout).toContain("偏离差额");
|
||||
});
|
||||
|
||||
it("platform update 支持 --where 声明式筛选与 --set 原地修改(含 --dry-run 与 --yes)", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
|
||||
...mockEntity,
|
||||
fields: [
|
||||
{ name: "fee", label: "租赁费用", type: "money" },
|
||||
{ name: "status", label: "状态", type: "text" },
|
||||
],
|
||||
} as any));
|
||||
spies.push(
|
||||
spyOn(services, "fetchAllEntityRecords").mockResolvedValue({
|
||||
data: [
|
||||
{ id: "r-1", fee: 0, status: "PENDING" },
|
||||
{ id: "r-2", fee: 78787.55, status: "DONE" },
|
||||
],
|
||||
total: 2,
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
})
|
||||
);
|
||||
|
||||
spies.push(
|
||||
spyOn(api, "getRecordDetail").mockResolvedValue({
|
||||
dataLink: { id: "r-1", active: true, fee: 0, status: "PENDING" },
|
||||
})
|
||||
);
|
||||
const editSpy = spyOn(api, "editRecord").mockResolvedValue({ id: "r-1" } as any);
|
||||
spies.push(editSpy);
|
||||
|
||||
// 1. Dry-run 模式测试
|
||||
const dryRes = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "update",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", "dry-run": true },
|
||||
raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
expect(dryRes.exitCode).toBe(0);
|
||||
expect(dryRes.stdout).toContain("Dry-Run 预览");
|
||||
expect(dryRes.stdout).toContain("r-1");
|
||||
expect(editSpy).not.toHaveBeenCalled();
|
||||
|
||||
// 2. 真实确认执行测试 (--yes)
|
||||
const execRes = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "update",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { where: "租赁费用 == 0", set: "租赁费用 = 78787.55", yes: true },
|
||||
raw: ["platform", "update", "platform-1", "entity-1", "--where=租赁费用 == 0", "--set=租赁费用 = 78787.55", "--yes"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
expect(execRes.exitCode).toBe(0);
|
||||
expect(execRes.stdout).toContain("已执行");
|
||||
expect(editSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("platform records 支持 --stats 画像统计(计算状态、重名与编码聚类)", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(
|
||||
spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1", name: "场地A", code: "0-DT-2026-month-1", active: true } },
|
||||
{ id: "r-2", dataLink: { id: "r-2", name: "场地A", code: "0-DT-2026-period-1", active: false } },
|
||||
{ id: "r-3", dataLink: { id: "r-3", name: "场地B", code: "0-DT-2026-month-2", active: true } },
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
})
|
||||
);
|
||||
|
||||
// 1. 命令行表格输出测试
|
||||
const textRes = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "records",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { stats: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
expect(textRes.exitCode).toBe(0);
|
||||
expect(textRes.stdout).toContain("宏观状态与数据画像");
|
||||
expect(textRes.stdout).toContain("启用 2 条");
|
||||
expect(textRes.stdout).toContain("停用 1 条");
|
||||
expect(textRes.stdout).toContain("N-DT-N-month-N");
|
||||
|
||||
// 2. JSON 结构化输出测试
|
||||
const jsonRes = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "records",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { stats: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--stats"],
|
||||
},
|
||||
{ ...dummyRuntime, jsonMode: true }
|
||||
);
|
||||
expect(jsonRes.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(jsonRes.stdout);
|
||||
expect(parsed.total).toBe(3);
|
||||
expect(parsed.activeCount).toBe(2);
|
||||
expect(parsed.inactiveCount).toBe(1);
|
||||
expect(parsed.duplicateNamesCount).toBe(1);
|
||||
});
|
||||
|
||||
it("platform records 支持 --ndjson 流式逐行下发与 --flat 归一化", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
spies.push(
|
||||
spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 2,
|
||||
data: [
|
||||
{
|
||||
id: "r-1",
|
||||
dataLink: { id: "r-1", name: "项目1", code: "P1", active: true, customField: "测试值" },
|
||||
},
|
||||
{
|
||||
id: "r-2",
|
||||
dataLink: { id: "r-2", name: "项目2", code: "P2", active: false, customField: "停用值" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
})
|
||||
);
|
||||
|
||||
const streamedLines: string[] = [];
|
||||
const writeSpy = spyOn(process.stdout, "write").mockImplementation((str: any) => {
|
||||
return true;
|
||||
});
|
||||
spies.push(writeSpy);
|
||||
|
||||
const streamRes = await handlePlatformCommand(
|
||||
{
|
||||
area: "platform",
|
||||
action: "records",
|
||||
args: ["platform-1", "entity-1"],
|
||||
options: { ndjson: true },
|
||||
raw: ["platform", "records", "platform-1", "entity-1", "--ndjson"],
|
||||
},
|
||||
{ ...dummyRuntime, writeStdout: async (chunk) => { streamedLines.push(chunk); } }
|
||||
);
|
||||
|
||||
expect(streamRes.exitCode).toBe(0);
|
||||
expect(streamedLines.length).toBe(2);
|
||||
expect(writeSpy).not.toHaveBeenCalled();
|
||||
|
||||
const row1 = JSON.parse(streamedLines[0].trim());
|
||||
expect(row1.id).toBe("r-1");
|
||||
expect(row1.name).toBe("项目1");
|
||||
expect(row1.code).toBe("P1");
|
||||
expect(row1.active).toBe(true);
|
||||
expect(row1.fields["自定义字段"]).toBe("测试值");
|
||||
});
|
||||
|
||||
it("rejects malformed batch predicates before fetching all records or calling the writer", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue(mockEntity as any));
|
||||
const fetch = spyOn(services, "fetchAllEntityRecords").mockResolvedValue({ data: [], total: 0 } as any);
|
||||
const write = spyOn(services, "batchSafeEditRecords").mockResolvedValue([]);
|
||||
spies.push(fetch, write);
|
||||
await expect(handlePlatformCommand({ area: "platform", action: "batch-edit", args: ["platform-1", "entity-1"], options: { where: "序号 in [1]", set: "active=true", yes: true }, raw: [] }, dummyRuntime)).rejects.toThrow("不支持的筛选条件");
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,783 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import * as api from "../../domains/datalink/services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
resolveEntity,
|
||||
resolvePlatform,
|
||||
selectRecordFields,
|
||||
type BatchEditTargetItem,
|
||||
} from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(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 };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = {
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
|
||||
total: page.total,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
function formatDirectRecordFieldValue(val: unknown): string {
|
||||
if (val === undefined || val === null || val === "") return "";
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const obj = val as Record<string, unknown>;
|
||||
if ("standard" in obj) {
|
||||
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
|
||||
}
|
||||
const nestedDl =
|
||||
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
|
||||
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
if (nestedDl && typeof nestedDl === "object") {
|
||||
const eId = String(nestedDl.entityId || "");
|
||||
const title =
|
||||
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
|
||||
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
|
||||
}
|
||||
if (typeof obj.id === "string" && (obj.name || obj.code)) {
|
||||
return `${obj.name || obj.code} (${obj.id})`;
|
||||
}
|
||||
}
|
||||
return cell(val);
|
||||
}
|
||||
|
||||
async function handleDirectRecordGet(
|
||||
recordId: string,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const record = (detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>;
|
||||
const entityId = String(record.entityId || "");
|
||||
const nameKey = entityId ? `E_${entityId}_name` : "name";
|
||||
const codeKey = entityId ? `E_${entityId}_code` : "code";
|
||||
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
|
||||
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
|
||||
const formatTime = (time: unknown) =>
|
||||
typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象 ID (entityId)", entityId || "-"],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const skipKeys = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"name",
|
||||
"code",
|
||||
nameKey,
|
||||
codeKey,
|
||||
"active",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"visibility",
|
||||
"form",
|
||||
]);
|
||||
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (skipKeys.has(k)) continue;
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
|
||||
rows.push([label, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
rows.push([k, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
if (dataStr) {
|
||||
try {
|
||||
return JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
if (filePath) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function handleBatchEdit(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
appIndex: number,
|
||||
entityIndex: number
|
||||
): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) {
|
||||
throw new Error(
|
||||
"用法: hose-use platform record batch-edit <应用> <业务对象> (--ids=<id1,id2> | --filter=<expr>) (--data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
|
||||
);
|
||||
}
|
||||
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
|
||||
const activeOpt =
|
||||
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
|
||||
if (!dataStr && !filePath) {
|
||||
throw new Error("请通过 --data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量编辑业务对象记录",
|
||||
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
|
||||
);
|
||||
|
||||
let fileContent: unknown;
|
||||
if (filePath) {
|
||||
try {
|
||||
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
let uniformPatch: Record<string, unknown> | undefined;
|
||||
if (dataStr) {
|
||||
try {
|
||||
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
} else if (
|
||||
fileContent &&
|
||||
typeof fileContent === "object" &&
|
||||
!Array.isArray(fileContent) &&
|
||||
!Object.values(fileContent as Record<string, unknown>).every(
|
||||
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
|
||||
)
|
||||
) {
|
||||
uniformPatch = fileContent as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const targets: BatchEditTargetItem[] = [];
|
||||
if (Array.isArray(fileContent)) {
|
||||
for (const entry of fileContent) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const item = entry as Record<string, unknown>;
|
||||
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
|
||||
const patchForm =
|
||||
(item.form as Record<string, unknown>) ??
|
||||
(item.data as Record<string, unknown>) ??
|
||||
uniformPatch ??
|
||||
{};
|
||||
if (recordId) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm,
|
||||
active: typeof item.active === "boolean" ? item.active : activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
|
||||
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
|
||||
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm: patchVal as Record<string, unknown>,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (!uniformPatch) {
|
||||
throw new Error("未解析到有效的批量更新内容");
|
||||
}
|
||||
let recordIds = splitFields(idsOpt);
|
||||
if (recordIds.length === 0 && filterBy) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy }
|
||||
);
|
||||
recordIds = page.data
|
||||
.map((r) => {
|
||||
const dl =
|
||||
r.dataLink && typeof r.dataLink === "object"
|
||||
? (r.dataLink as Record<string, unknown>)
|
||||
: r;
|
||||
return String(dl.id ?? r.id ?? "").trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (recordIds.length === 0) {
|
||||
throw new Error("请通过 --ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
}
|
||||
for (const id of recordIds) {
|
||||
targets.push({
|
||||
recordId: id,
|
||||
patchForm: uniformPatch,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const dryRun = isDryRun(parsed, runtime);
|
||||
const results = await batchSafeEditRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity,
|
||||
targets,
|
||||
{ concurrency, dryRun }
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
|
||||
const failed = results.filter((r) => r.status === "failed").length;
|
||||
const summary = {
|
||||
dryRun,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
total: results.length,
|
||||
succeeded,
|
||||
failed,
|
||||
items: results,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(summary, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = results.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.recordId,
|
||||
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
|
||||
item.payload ? Object.keys(item.payload.form).length : "-",
|
||||
item.error || "-",
|
||||
]);
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
||||
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
||||
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
||||
printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows),
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (action === "batch-edit" || action === "record-batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, 0, 1);
|
||||
}
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (
|
||||
[
|
||||
"get",
|
||||
"show",
|
||||
"detail",
|
||||
"toggle",
|
||||
"state",
|
||||
"edit",
|
||||
"update",
|
||||
"batch-edit",
|
||||
"recompute",
|
||||
"recalc",
|
||||
].includes(firstArg)
|
||||
) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
recordIdIndex = 3;
|
||||
} else {
|
||||
subAction = "get";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (subAction === "batch-edit") {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
|
||||
const remainingArgs = parsed.args.slice(appIndex);
|
||||
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
|
||||
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
|
||||
switch (subAction) {
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
|
||||
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
|
||||
|
||||
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
for (const field of resolved.entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
|
||||
if (val !== undefined && val !== null && val !== "") {
|
||||
let displayVal = val;
|
||||
if (field.type === "date" && typeof val === "number") {
|
||||
displayVal = new Date(val).toLocaleDateString("zh-CN");
|
||||
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
|
||||
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
|
||||
}
|
||||
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "toggle":
|
||||
case "state": {
|
||||
const explicitState = parsed.options.state !== undefined
|
||||
? booleanOption(parsed.options, ["state"], true)
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"切换业务对象记录状态",
|
||||
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
active: explicitState ?? "toggle",
|
||||
});
|
||||
}
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const label = res.active ? "🟢 启用" : "🔴 停用";
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const form = parseJsonDataOption(parsed);
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"编辑业务对象记录",
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
|
||||
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
|
||||
if (isRaw) {
|
||||
payload = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
};
|
||||
} else {
|
||||
let detail: Record<string, unknown> = {};
|
||||
try {
|
||||
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
} catch (error) {
|
||||
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
||||
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
payload = api.buildSafeRecordEditPayload({
|
||||
entityId: resolved.entity.id,
|
||||
recordId,
|
||||
detail,
|
||||
fields: resolved.entity.fields,
|
||||
patchForm: form,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"触发业务对象记录台账重算",
|
||||
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
});
|
||||
}
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
getImportResult,
|
||||
listImportJobs,
|
||||
listAllPlatforms,
|
||||
listPlatformEntities,
|
||||
listPlatforms,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity } from "./shared.js";
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
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 }));
|
||||
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 };
|
||||
}
|
||||
|
||||
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
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 { handleRecords, handleAudit } from "./records.js";
|
||||
import { handleRecordAction } from "./record-actions.js";
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./../app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search":
|
||||
case "stats":
|
||||
case "profile": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-update":
|
||||
case "update":
|
||||
case "batch-update":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import {
|
||||
batchSafeEditRecords,
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
fetchAllEntityRecords,
|
||||
compileRecordPredicate,
|
||||
getRecordDetail,
|
||||
parseSetClause,
|
||||
recomputeRecordLedger,
|
||||
toggleRecordState,
|
||||
type BatchEditTargetItem,
|
||||
type SafeRecordEditOptions,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { cell, requiredTarget, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
function formatDirectRecordFieldValue(val: unknown): string {
|
||||
if (val === undefined || val === null || val === "") return "";
|
||||
if (typeof val === "object" && !Array.isArray(val)) {
|
||||
const obj = val as Record<string, unknown>;
|
||||
if ("standard" in obj) {
|
||||
return `${obj.standard} ${obj.standardStrCode || obj.standardUnit || "CNY"}`;
|
||||
}
|
||||
const nestedDl =
|
||||
obj.data && typeof obj.data === "object" && (obj.data as Record<string, unknown>).dataLink
|
||||
? ((obj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
if (nestedDl && typeof nestedDl === "object") {
|
||||
const eId = String(nestedDl.entityId || "");
|
||||
const title =
|
||||
nestedDl[`E_${eId}_name`] ?? nestedDl.name ?? nestedDl[`E_${eId}_code`] ?? nestedDl.code ?? "";
|
||||
return `${obj.id || nestedDl.id}${title ? ` (${title})` : ""}`;
|
||||
}
|
||||
if (typeof obj.id === "string" && (obj.name || obj.code)) {
|
||||
return `${obj.name || obj.code} (${obj.id})`;
|
||||
}
|
||||
}
|
||||
return cell(val);
|
||||
}
|
||||
|
||||
async function handleDirectRecordGet(
|
||||
recordId: string,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const detail = await getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const record = (detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>;
|
||||
const entityId = String(record.entityId || "");
|
||||
const nameKey = entityId ? `E_${entityId}_name` : "name";
|
||||
const codeKey = entityId ? `E_${entityId}_code` : "code";
|
||||
const nameVal = record.name ?? record["名称"] ?? record[nameKey];
|
||||
const codeVal = record.code ?? record["编码"] ?? record[codeKey];
|
||||
const formatTime = (time: unknown) =>
|
||||
typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象 ID (entityId)", entityId || "-"],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
const skipKeys = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"name",
|
||||
"code",
|
||||
nameKey,
|
||||
codeKey,
|
||||
"active",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"visibility",
|
||||
"form",
|
||||
]);
|
||||
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (skipKeys.has(k)) continue;
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
const label = entityId && k.startsWith(`E_${entityId}_`) ? `${k.slice(`E_${entityId}_`.length)} (${k})` : k;
|
||||
rows.push([label, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
if (v !== undefined && v !== null && v !== "") {
|
||||
rows.push([k, formatDirectRecordFieldValue(v)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情 (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonDataOption(parsed: CliParsedArgs): Record<string, unknown> {
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
if (dataStr) {
|
||||
try {
|
||||
return JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
}
|
||||
if (filePath) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(filePath, "utf8")) as Record<string, unknown>;
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
async function handleBatchEdit(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
appIndex: number,
|
||||
entityIndex: number
|
||||
): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) {
|
||||
throw new Error(
|
||||
"用法: hose-use platform record batch-edit <应用> <业务对象> (--where='<expr>' | --ids=<id1,id2> | --filter=<expr>) (--set='<expr>' | --data='<json>' | --file=<patch.json>) [--concurrency=8] [--dry-run] [--yes]"
|
||||
);
|
||||
}
|
||||
|
||||
const idsOpt = stringOption(parsed.options, ["ids", "id"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
const dataStr = stringOption(parsed.options, ["data", "form", "d"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "f"]);
|
||||
const concurrency = numberOption(parsed.options, ["concurrency", "c"], 8);
|
||||
const activeOpt =
|
||||
parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
|
||||
if (!dataStr && !filePath && !setClause) {
|
||||
throw new Error("请通过 --set='字段=值'、--data='<json>' 或 --file=<patch.json> 提供要批量更新的字段内容");
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量编辑业务对象记录",
|
||||
`hose-use platform record batch-edit ${resolved.platform.id} ${resolved.entity.id} --yes`
|
||||
);
|
||||
|
||||
let fileContent: unknown;
|
||||
if (filePath) {
|
||||
try {
|
||||
fileContent = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取或解析 JSON 文件 [${filePath}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
let uniformPatch: Record<string, unknown> | undefined;
|
||||
if (setClause) {
|
||||
uniformPatch = parseSetClause(setClause, resolved.entity);
|
||||
} else if (dataStr) {
|
||||
try {
|
||||
uniformPatch = JSON.parse(dataStr) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error("提供的 --data 参数不是合法的 JSON 字符串");
|
||||
}
|
||||
} else if (
|
||||
fileContent &&
|
||||
typeof fileContent === "object" &&
|
||||
!Array.isArray(fileContent) &&
|
||||
!Object.values(fileContent as Record<string, unknown>).every(
|
||||
(v) => v && typeof v === "object" && !Array.isArray(v) && !("standard" in (v as Record<string, unknown>))
|
||||
)
|
||||
) {
|
||||
uniformPatch = fileContent as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const targets: BatchEditTargetItem[] = [];
|
||||
if (Array.isArray(fileContent)) {
|
||||
for (const entry of fileContent) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const item = entry as Record<string, unknown>;
|
||||
const recordId = String(item.id ?? item.recordId ?? item.dataLinkId ?? "").trim();
|
||||
const patchForm =
|
||||
(item.form as Record<string, unknown>) ??
|
||||
(item.data as Record<string, unknown>) ??
|
||||
uniformPatch ??
|
||||
{};
|
||||
if (recordId) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm,
|
||||
active: typeof item.active === "boolean" ? item.active : activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (!uniformPatch && fileContent && typeof fileContent === "object") {
|
||||
for (const [recordId, patchVal] of Object.entries(fileContent as Record<string, unknown>)) {
|
||||
if (patchVal && typeof patchVal === "object" && !Array.isArray(patchVal)) {
|
||||
targets.push({
|
||||
recordId,
|
||||
patchForm: patchVal as Record<string, unknown>,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (!uniformPatch) {
|
||||
throw new Error("未解析到有效的批量更新内容");
|
||||
}
|
||||
let recordIds = splitFields(idsOpt);
|
||||
if (recordIds.length === 0 && (whereClause || filterBy)) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy }
|
||||
);
|
||||
let records = page.data;
|
||||
if (predicate) records = records.filter(predicate);
|
||||
recordIds = records
|
||||
.map((r) => {
|
||||
const dl =
|
||||
r.dataLink && typeof r.dataLink === "object"
|
||||
? (r.dataLink as Record<string, unknown>)
|
||||
: r;
|
||||
return String(dl.id ?? r.id ?? "").trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (recordIds.length === 0) {
|
||||
if (whereClause) {
|
||||
return {
|
||||
stdout: `未找到符合条件 [--where="${whereClause}"] 的记录,无需更新。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
throw new Error("请通过 --where=<条件>、--ids=<id1,id2,...> 或 --filter=<表达式> 指定要批量更新的目标记录");
|
||||
}
|
||||
for (const id of recordIds) {
|
||||
targets.push({
|
||||
recordId: id,
|
||||
patchForm: uniformPatch,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const dryRun = isDryRun(parsed, runtime);
|
||||
const results = await batchSafeEditRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity,
|
||||
targets,
|
||||
{ concurrency, dryRun }
|
||||
);
|
||||
|
||||
const succeeded = results.filter((r) => r.status === "updated" || r.status === "preview").length;
|
||||
const failed = results.filter((r) => r.status === "failed").length;
|
||||
const summary = {
|
||||
dryRun,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
total: results.length,
|
||||
succeeded,
|
||||
failed,
|
||||
items: results,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(summary, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = results.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.recordId,
|
||||
item.status === "preview" ? "🔍 预览 (dry-run)" : item.status === "updated" ? "✅ 已更新" : "❌ 失败",
|
||||
item.payload ? Object.keys(item.payload.form).length : "-",
|
||||
item.error || "-",
|
||||
]);
|
||||
|
||||
const outputLines = [
|
||||
`====== 批量安全编辑业务对象记录 (${dryRun ? "Dry-Run 预览" : "已执行"}) ======`,
|
||||
`应用: ${resolved.platform.name} (${resolved.platform.id}) | 业务对象: ${resolved.entity.name} (${resolved.entity.id})`,
|
||||
`总计: ${results.length} | 成功/预览: ${succeeded} | 失败: ${failed}`,
|
||||
];
|
||||
if (uniformPatch) {
|
||||
outputLines.push(`应用变更 Patch: ${JSON.stringify(uniformPatch)}`);
|
||||
}
|
||||
outputLines.push(printTable(["#", "记录 ID", "状态", "合并后字段数", "错误信息"], rows));
|
||||
if (dryRun) {
|
||||
outputLines.push("");
|
||||
outputLines.push("💡 这是 Dry-Run 预演模式,数据未发生任何改变。如需真正执行修改,请追加 --yes(或 --confirm)参数。");
|
||||
}
|
||||
outputLines.push("");
|
||||
|
||||
return {
|
||||
stdout: outputLines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: failed > 0 ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
let entityIndex: number;
|
||||
let recordIdIndex: number;
|
||||
|
||||
if (
|
||||
action === "batch-edit" ||
|
||||
action === "record-batch-edit" ||
|
||||
action === "batch-update"
|
||||
) {
|
||||
return handleBatchEdit(parsed, runtime, 0, 1);
|
||||
}
|
||||
|
||||
if (action.startsWith("record-")) {
|
||||
subAction = action.replace("record-", "");
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else if (action === "update") {
|
||||
subAction = "update";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
} else {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
if (
|
||||
[
|
||||
"get",
|
||||
"show",
|
||||
"detail",
|
||||
"toggle",
|
||||
"state",
|
||||
"edit",
|
||||
"update",
|
||||
"batch-edit",
|
||||
"batch-update",
|
||||
"recompute",
|
||||
"recalc",
|
||||
].includes(firstArg)
|
||||
) {
|
||||
subAction = firstArg;
|
||||
appIndex = 1;
|
||||
entityIndex = 2;
|
||||
recordIdIndex = 3;
|
||||
} else {
|
||||
subAction = "get";
|
||||
appIndex = 0;
|
||||
entityIndex = 1;
|
||||
recordIdIndex = 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (subAction === "batch-edit" || subAction === "batch-update") {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
if ((subAction === "update" || subAction === "edit") && (whereClause || parsed.args.length <= recordIdIndex)) {
|
||||
return handleBatchEdit(parsed, runtime, appIndex, entityIndex);
|
||||
}
|
||||
|
||||
// 支持 hose-use platform record get <recordId> 或 hose-use platform record <recordId> 免应用/实体直接查询
|
||||
const remainingArgs = parsed.args.slice(appIndex);
|
||||
if (["get", "show", "detail"].includes(subAction) && remainingArgs.length === 1) {
|
||||
return handleDirectRecordGet(remainingArgs[0].trim(), runtime);
|
||||
}
|
||||
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
const recordId = requiredTarget(parsed, recordIdIndex, "hose-use platform record <动作> <应用> <业务对象> <记录ID>");
|
||||
|
||||
switch (subAction) {
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameVal = record.name ?? record["名称"] ?? (nameField ? record[nameField.name] : undefined) ?? record[`E_${resolved.entity.id}_name`];
|
||||
const codeVal = record.code ?? record["编码"] ?? (codeField ? record[codeField.name] : undefined) ?? record[`E_${resolved.entity.id}_code`];
|
||||
|
||||
const formatTime = (time: unknown) => typeof time === "number" ? new Date(time).toLocaleString("zh-CN", { hour12: false }) : cell(time);
|
||||
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [
|
||||
["记录 ID", cell(record.id ?? recordId)],
|
||||
["业务对象", `${resolved.entity.name} (${resolved.entity.id})`],
|
||||
["名称", cell(nameVal)],
|
||||
["编码", cell(codeVal)],
|
||||
["状态", record.active === false ? "🔴 停用" : "🟢 启用"],
|
||||
["创建时间", formatTime(record.createTime)],
|
||||
["更新时间", formatTime(record.updateTime)],
|
||||
];
|
||||
|
||||
for (const field of resolved.entity.fields) {
|
||||
if (field.name === nameField?.name || field.name === codeField?.name) continue;
|
||||
const val = record[field.name] ?? record[`E_${resolved.entity.id}_${field.name}`] ?? (record.form as Record<string, unknown> | undefined)?.[field.name] ?? record[field.label];
|
||||
if (val !== undefined && val !== null && val !== "") {
|
||||
let displayVal = val;
|
||||
if (field.type === "date" && typeof val === "number") {
|
||||
displayVal = new Date(val).toLocaleDateString("zh-CN");
|
||||
} else if (field.type === "money" && typeof val === "object" && val !== null && "standard" in (val as any)) {
|
||||
displayVal = `${(val as any).standard} ${(val as any).standardStrCode || "CNY"}`;
|
||||
}
|
||||
rows.push([`${field.label} (${field.name})`, cell(displayVal)]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 记录详情: [${resolved.platform.name}] ${resolved.entity.name} (${recordId}) ======\n${printTable(["字段/属性", "值"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "toggle":
|
||||
case "state": {
|
||||
const explicitState = parsed.options.state !== undefined
|
||||
? booleanOption(parsed.options, ["state"], true)
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"切换业务对象记录状态",
|
||||
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
active: explicitState ?? "toggle",
|
||||
});
|
||||
}
|
||||
const res = await toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const label = res.active ? "🟢 启用" : "🔴 停用";
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 状态已成功切换为 [${label}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "edit":
|
||||
case "update": {
|
||||
const setClause = stringOption(parsed.options, ["set"]);
|
||||
const form = setClause ? parseSetClause(setClause, resolved.entity) : parseJsonDataOption(parsed);
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"编辑业务对象记录",
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
|
||||
let payload: SafeRecordEditOptions extends never ? never : ReturnType<typeof buildSafeRecordEditPayload>;
|
||||
if (isRaw) {
|
||||
payload = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt,
|
||||
};
|
||||
} else {
|
||||
let detail: Record<string, unknown> = {};
|
||||
try {
|
||||
detail = await getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
} catch (error) {
|
||||
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
||||
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
payload = buildSafeRecordEditPayload({
|
||||
entityId: resolved.entity.id,
|
||||
recordId,
|
||||
detail,
|
||||
fields: resolved.entity.fields,
|
||||
patchForm: form,
|
||||
active: activeOpt,
|
||||
});
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
||||
}
|
||||
const result = await editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"触发业务对象记录台账重算",
|
||||
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
});
|
||||
}
|
||||
const result = await recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import {
|
||||
aggregateRecordFields,
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
buildKeywordFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
compileRecordPredicate,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
parseExpectClause,
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
import { usageError } from "../../errors.js";
|
||||
import { open } from "node:fs/promises";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const isStream = booleanOption(parsed.options, ["ndjson", "stream"], false);
|
||||
if (isStream && !runtime.outputOptions?.outputFile && !runtime.writeStdout) {
|
||||
throw usageError("当前调用入口不支持直接 NDJSON 流,请使用 --output-file <path> 保存,或在终端运行该命令。");
|
||||
}
|
||||
const isStatsSubcommand = parsed.args[0] === "stats" || parsed.action === "stats";
|
||||
const appIndex = parsed.args[0] === "stats" ? 1 : 0;
|
||||
const entityIndex = parsed.args[0] === "stats" ? 2 : 1;
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime, appIndex, entityIndex);
|
||||
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 whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
const isProfileStats = isStatsSubcommand || booleanOption(parsed.options, ["stats", "profile"], false);
|
||||
const isRaw = booleanOption(parsed.options, ["raw"], false);
|
||||
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 start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
|
||||
// 1. 高性能流式下发模式 (--ndjson / --stream,内存开销 O(pageSize),专为海量数据外部脚本管道设计)
|
||||
if (isStream) {
|
||||
let streamCount = 0;
|
||||
let bytes = 0;
|
||||
const maxLimit = isAll ? Infinity : count ?? 20;
|
||||
const outputFile = runtime.outputOptions?.outputFile;
|
||||
const file = outputFile ? await open(outputFile, "w", 0o600) : undefined;
|
||||
|
||||
try {
|
||||
if (maxLimit > 0) {
|
||||
for await (const rawRecord of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
if (predicate && !predicate(rawRecord)) continue;
|
||||
|
||||
let outputRecord: Record<string, unknown> = isRaw
|
||||
? (rawRecord as Record<string, unknown>)
|
||||
: (normalizeDatalinkRecord(rawRecord, resolved.entity) as unknown as Record<string, unknown>);
|
||||
|
||||
if (fields.length) {
|
||||
outputRecord = selectRecordFields(outputRecord, fields, resolved.entity.fields);
|
||||
}
|
||||
|
||||
const chunk = redactSensitiveText(JSON.stringify(outputRecord)) + "\n";
|
||||
if (file) await file.writeFile(chunk);
|
||||
else await runtime.writeStdout!(chunk);
|
||||
bytes += Buffer.byteLength(chunk);
|
||||
streamCount++;
|
||||
if (maxLimit !== undefined && streamCount >= maxLimit) break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await file?.close();
|
||||
}
|
||||
return { stdout: outputFile ? printJson({ outputFile, bytes, records: streamCount }) : "", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 2. 宏观画像与统计模式 (--stats 或 platform records stats <应用> <对象>)
|
||||
if (isProfileStats) {
|
||||
const page = await fetchAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
);
|
||||
let records = page.data;
|
||||
if (predicate) records = records.filter(predicate);
|
||||
const stats = calculateEntityRecordStats(records, resolved.entity, page.total);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(stats, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const patternRows: Array<Array<string | number>> = stats.codePatterns.map((p, idx) => [
|
||||
idx + 1,
|
||||
p.pattern,
|
||||
p.sample,
|
||||
p.count,
|
||||
p.activeCount,
|
||||
p.inactiveCount,
|
||||
]);
|
||||
|
||||
const lines = [
|
||||
`====== [${resolved.platform.name}] ${resolved.entity.name} 宏观状态与数据画像 (总数: ${stats.total}) ======`,
|
||||
` - 状态分布: 🟢 启用 ${stats.activeCount} 条 (${stats.activeRate}) | 🔴 停用 ${stats.inactiveCount} 条`,
|
||||
` - 名称画像: ${stats.uniqueNames} 个唯一名称 (其中 ${stats.duplicateNamesCount} 组存在重名,${stats.mixedStatusNamesCount} 组同时包含启用与停用)`,
|
||||
` - 时间跨度: 最早创建 ${stats.earliestCreateTime || "-"} ~ 最晚更新 ${stats.latestUpdateTime || "-"}`,
|
||||
"",
|
||||
"── 编码结构与停用分布 ──",
|
||||
printTable(["#", "编码模式", "样本", "总数", "启用数", "停用数"], patternRows),
|
||||
];
|
||||
|
||||
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 = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
const sumFields = splitFields(sumOption);
|
||||
const aggReport = aggregateRecordFields(data, resolved.entity, { fields: sumFields, groupBy });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(aggReport, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const statRows: Array<Array<string | number>> = Object.entries(aggReport.overall).map(([query, s]) => [
|
||||
query,
|
||||
s.fieldLabel,
|
||||
s.count,
|
||||
s.sum,
|
||||
s.avg,
|
||||
s.min,
|
||||
s.max,
|
||||
]);
|
||||
|
||||
const lines: string[] = [
|
||||
`====== [${resolved.platform.name}] ${resolved.entity.name} 台账数学聚合核算 (统计样本: ${data.length} 条记录) ======`,
|
||||
printTable(
|
||||
["统计字段", "字段标签", "有效样本 (COUNT)", "总合计 (SUM)", "平均值 (AVG)", "最小值 (MIN)", "最大值 (MAX)"],
|
||||
statRows
|
||||
),
|
||||
];
|
||||
|
||||
if (aggReport.groups && aggReport.groups.length > 0) {
|
||||
lines.push("");
|
||||
lines.push(`── 按 [${groupBy}] 分组统计 ──`);
|
||||
const groupRows: Array<Array<string | number>> = [];
|
||||
for (const g of aggReport.groups) {
|
||||
for (const [query, s] of Object.entries(g.aggregates)) {
|
||||
groupRows.push([g.groupValue, g.count, s.fieldLabel, s.sum, s.avg, s.min, s.max]);
|
||||
}
|
||||
}
|
||||
lines.push(
|
||||
printTable(
|
||||
[`分组 (${groupBy})`, "组内条数", "字段", "组内合计", "组内均值", "最小值", "最大值"],
|
||||
groupRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
// 4. 常规记录查询模式 (支持 --flat 扁平归一化)
|
||||
if (isFlat) {
|
||||
data = data.map((item) => normalizeDatalinkRecord(item, resolved.entity) as unknown as Record<string, unknown>);
|
||||
}
|
||||
|
||||
if (fields.length) {
|
||||
data = data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields));
|
||||
}
|
||||
|
||||
const result = {
|
||||
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,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
|
||||
export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error(
|
||||
"请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only] [--check-continuous=序号字段] [--expect=期望表达式]"
|
||||
);
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const checkContinuous = stringOption(parsed.options, ["check-continuous", "checkContinuous", "continuous", "seq", "sequence"]);
|
||||
const expectClause = stringOption(parsed.options, ["expect", "expect-value", "expectValue", "baseline"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
let continuityReport: LedgerContinuityReport | undefined;
|
||||
if (checkContinuous || expectClause) {
|
||||
const expectedValues = expectClause ? parseExpectClause(expectClause) : undefined;
|
||||
continuityReport = auditLedgerContinuityAndBaseline(page.data, resolved.entity, {
|
||||
sequenceField: checkContinuous,
|
||||
expectedValues,
|
||||
});
|
||||
}
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
continuity: continuityReport,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount + (continuityReport?.issues.length ?? 0),
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (continuityReport) {
|
||||
if (continuityReport.sequenceSummary) {
|
||||
const seq = continuityReport.sequenceSummary;
|
||||
outLines.push("");
|
||||
outLines.push(`── 台账序号连续性体检 (字段: ${seq.fieldLabel}) ──`);
|
||||
outLines.push(
|
||||
printKeyValue({
|
||||
"最小期数 (MIN)": seq.min,
|
||||
"最大期数 (MAX)": seq.max,
|
||||
"期望连续期数": seq.expectedCount,
|
||||
"实际有效记录数": seq.actualCount,
|
||||
"断层缺失期数 (MISSING)": seq.missing.length ? `❌ 缺少 [${seq.missing.join(", ")}]` : "✅ 无断层缺失",
|
||||
"重复重号期数 (DUPLICATE)": seq.duplicates.length ? `❌ 重号 [${seq.duplicates.join(", ")}]` : "✅ 无重复重号",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (expectClause) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 基线离群异常核对 (共 ${continuityReport.outliers.length} 条偏离记录) ──`);
|
||||
if (continuityReport.outliers.length > 0) {
|
||||
const outlierRows = continuityReport.outliers.map((o, idx) => [
|
||||
idx + 1,
|
||||
o.recordId,
|
||||
o.fieldLabel,
|
||||
o.value,
|
||||
o.expectedValue,
|
||||
o.diff > 0 ? `+${o.diff}` : o.diff,
|
||||
]);
|
||||
outLines.push(printTable(["#", "记录 ID", "字段", "实际值", "基线期望", "偏离差额"], outlierRows));
|
||||
} else {
|
||||
outLines.push("✅ 所有记录数值均符合期望基线标准,无离群异常");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { resolveEntity, resolvePlatform } from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
export function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
export function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user