Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d921c09b3 | ||
|
|
3fee9a2a6f | ||
|
|
32a509aa0e | ||
|
|
ad771e92e0 | ||
|
|
1739daacf2 | ||
|
|
1c2e97486b | ||
|
|
a5f685045e | ||
|
|
fbdb38bfb2 | ||
|
|
f834822f36 | ||
|
|
37f5e5c74b | ||
|
|
fa55e45acd | ||
|
|
975f76af74 | ||
|
|
deed5a5628 | ||
|
|
576d98a85f | ||
|
|
aea30fbcd5 | ||
|
|
36a4d3b27b | ||
|
|
3f3bd8183b | ||
|
|
8a5dc1133d | ||
|
|
88a0d97974 | ||
|
|
6ce83dd8a7 | ||
|
|
3597ec6694 |
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.8.17",
|
"version": "0.8.20",
|
||||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "yingqing"
|
"name": "yingqing"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# hose-use (v0.8.17)
|
# hose-use (v0.8.20)
|
||||||
|
|
||||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||||
|
|
||||||
|
|||||||
Vendored
+603
-580
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.8.17",
|
"version": "0.8.20",
|
||||||
"module": "src/server.ts",
|
"module": "src/server.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
name: hose-use
|
name: hose-use
|
||||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||||
metadata:
|
metadata:
|
||||||
version: 0.8.17
|
version: 0.8.20
|
||||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||||
---
|
---
|
||||||
|
|
||||||
# hose-use (v0.8.17)
|
# hose-use (v0.8.20)
|
||||||
|
|
||||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||||
@@ -66,6 +66,12 @@ metadata:
|
|||||||
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
||||||
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
|
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
|
||||||
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||||
|
14. **工作流代码节点文件映射与 Token 防膨胀守则 (Workflow Code Node File Mapping & Zero-Token-Waste Rule)**:
|
||||||
|
- **严禁终端内联大段代码**:在新建或修改工作流代码节点(`code-js2` / `code`)时,**严禁使用 `--code="..."` 或在终端命令(如 `bun -e '...'`)中内联几十上百行的长代码**。内联大段代码会导致命令行参数急剧膨胀,在 Tool Calls 中产生严重的输入输出 Token 浪费,且极易因 Shell 引号转义损坏脚本语法;
|
||||||
|
- **必须走本地文件映射与 `--code-file`**:
|
||||||
|
1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get <pipelineId> <nodeName> > ./scripts/xxx.mvel`;
|
||||||
|
2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token);
|
||||||
|
3. **一键同步**:使用 `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -227,8 +233,8 @@ hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhoo
|
|||||||
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
|
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
|
||||||
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
||||||
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
|
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 add wf_01k83y... --type=code-js2 --label="清洗" --code-file=./clean.js --yes # 声明式追加节点 (支持 --code-file 导入)
|
||||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
hose-use workflow node edit wf_01k83y... <节点name或#序号> --code-file=./clean.js --yes # 从本地文件同步最新脚本 (推荐,零 Token 浪费)
|
||||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
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... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||||
|
|||||||
@@ -144,3 +144,11 @@ result;
|
|||||||
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
|
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
|
||||||
|
|
||||||
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
|
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
|
||||||
|
|
||||||
|
## Deployment & CLI Integration (Zero-Token-Waste Rule)
|
||||||
|
|
||||||
|
- **Always maintain MVEL scripts in local dedicated files** (e.g. `./scripts/node_calc.mvel`), never pass long scripts inline in `--code="..."` or in terminal `bun -e '...'` expressions.
|
||||||
|
- **Local syntax check**: `hose-use workflow lint-script --file=./scripts/node_calc.mvel --type=code`
|
||||||
|
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
|
||||||
|
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
|
||||||
|
|
||||||
@@ -321,15 +321,17 @@ hose-use workflow node get <pipelineId> 2 --json
|
|||||||
|
|
||||||
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
||||||
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
||||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
|
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地脚本文件导入代码
|
||||||
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=code-js2 --label="数据过滤" --code-file=./scripts/filter.js --yes
|
||||||
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
||||||
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
||||||
|
|
||||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||||
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
|
# 支持修改 --label, --desc, --code, --code-file, 或通过 --set="key=value" 定向覆盖任意属性
|
||||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
|
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地文件导入脚本
|
||||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
|
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --dry-run
|
||||||
|
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --yes
|
||||||
|
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --yes
|
||||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||||
|
|
||||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"openapi": "3.1.0",
|
"openapi": "3.1.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "hose-use API & MCP Tools Specification",
|
"title": "hose-use API & MCP Tools Specification",
|
||||||
"version": "0.8.17",
|
"version": "0.8.20",
|
||||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
openapi: 3.1.0
|
openapi: 3.1.0
|
||||||
info:
|
info:
|
||||||
title: hose-use API & MCP Tools Specification
|
title: hose-use API & MCP Tools Specification
|
||||||
version: 0.8.17
|
version: 0.8.20
|
||||||
description: >-
|
description: >-
|
||||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||||
servers:
|
servers:
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import ky from "ky";
|
||||||
|
import { saveAssistPlatformSession } from "../core/auth/assist-platform-store.js";
|
||||||
|
import { saveCorpConfig } from "../core/config/loader.js";
|
||||||
|
import { CorpContext } from "../core/config/manager.js";
|
||||||
|
import { BusinessError } from "../core/errors.js";
|
||||||
|
import { importAssistSessionToLocal, inspectAssistIdentity } from "../domains/assist-platform/services.js";
|
||||||
|
import { runCli } from "./runner.js";
|
||||||
|
|
||||||
|
const envKeys = ["HOSE_STATE_DIR", "HOSE_ASSIST_PLATFORM_FILE", "HOSE_CONFIG_FILE", "HOSE_ENTERPRISES_DIR"] as const;
|
||||||
|
const token = "fixture-session-token";
|
||||||
|
const loginUrl = `https://session.example/web/thirdparty.html?accessToken=${token}&ekbCorpId=NEW`;
|
||||||
|
const baseUrl = "https://session.example";
|
||||||
|
|
||||||
|
describe("assist session lifecycle regressions", () => {
|
||||||
|
let root: string;
|
||||||
|
let corps: string;
|
||||||
|
let originalEnv: Array<string | undefined>;
|
||||||
|
let originalFetch: typeof fetch;
|
||||||
|
let requests: string[];
|
||||||
|
let handleRequest: (req: Request) => Response | Promise<Response>;
|
||||||
|
let staffAvailable: boolean;
|
||||||
|
let rolesAvailable: boolean;
|
||||||
|
let jwtAdmin: boolean | undefined;
|
||||||
|
let keysResponse: () => Response;
|
||||||
|
let logCredentials: boolean;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
root = mkdtempSync(join(tmpdir(), "hose-assist-session-"));
|
||||||
|
corps = join(root, "corps");
|
||||||
|
mkdirSync(corps);
|
||||||
|
originalEnv = envKeys.map((key) => process.env[key]);
|
||||||
|
process.env.HOSE_STATE_DIR = root;
|
||||||
|
process.env.HOSE_ASSIST_PLATFORM_FILE = join(root, "assist.json");
|
||||||
|
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
|
||||||
|
process.env.HOSE_ENTERPRISES_DIR = corps;
|
||||||
|
saveAssistPlatformSession({ token: "fixture-platform-token", baseUrl: "https://assist.example/api", updatedAt: Date.now() });
|
||||||
|
requests = [];
|
||||||
|
staffAvailable = true;
|
||||||
|
rolesAvailable = true;
|
||||||
|
jwtAdmin = false;
|
||||||
|
logCredentials = false;
|
||||||
|
keysResponse = () => Response.json({ items: [] });
|
||||||
|
handleRequest = async (req) => {
|
||||||
|
const url = req.url;
|
||||||
|
if (url.includes("assistPlatform/getToken")) {
|
||||||
|
if (logCredentials) {
|
||||||
|
console.log(`diagnostic ${loginUrl}`);
|
||||||
|
console.error(`diagnostic ${loginUrl}`);
|
||||||
|
}
|
||||||
|
return Response.json({ value: { token, loginUrl, baseUrl } });
|
||||||
|
}
|
||||||
|
if (url.includes("organization/staffs/me")) {
|
||||||
|
return staffAvailable
|
||||||
|
? Response.json({ value: { staff: { id: "NEW:staff", name: "员工", admin: false }, permissions: [] } })
|
||||||
|
: new Response("Forbidden", { status: 403 });
|
||||||
|
}
|
||||||
|
if (url.includes("/roles")) {
|
||||||
|
return rolesAvailable ? Response.json({ items: [] }) : new Response("Forbidden", { status: 403 });
|
||||||
|
}
|
||||||
|
if (url.includes("actions/jwt")) {
|
||||||
|
const payload = Buffer.from(JSON.stringify({ staffId: "NEW:staff", staffName: "JWT员工", isAdmin: jwtAdmin, corporationName: "新企业" })).toString("base64url");
|
||||||
|
return Response.json({ id: `fixture.${payload}.signature` });
|
||||||
|
}
|
||||||
|
if (url.includes("/account/v2/session")) {
|
||||||
|
return Response.json({ value: { id: "session", corporationId: "NEW", loginStaffId: "NEW:staff", platform: "ASSIST" } });
|
||||||
|
}
|
||||||
|
if (url.includes("/innerapi/v1/key")) return keysResponse();
|
||||||
|
throw new Error(`Unexpected mocked request: ${url}`);
|
||||||
|
};
|
||||||
|
originalFetch = globalThis.fetch;
|
||||||
|
globalThis.fetch = (async (input: string | Request | URL, init?: RequestInit) => {
|
||||||
|
const req = input instanceof Request ? input : new Request(input.toString(), init);
|
||||||
|
requests.push(req.url);
|
||||||
|
return handleRequest(req);
|
||||||
|
}) as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
envKeys.forEach((key, index) => {
|
||||||
|
if (originalEnv[index] === undefined) delete process.env[key];
|
||||||
|
else process.env[key] = originalEnv[index];
|
||||||
|
});
|
||||||
|
rmSync(root, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const enterArgs = ["assist-platform", "enter", "NEW", "--ticket", "T"];
|
||||||
|
const importSession = (options: { elevate?: boolean } = {}) => importAssistSessionToLocal(
|
||||||
|
ky.create({ prefix: "https://assist.example/api" }),
|
||||||
|
{ corpId: "NEW", ticketId: "T", enterprisesDir: corps, ...options }
|
||||||
|
);
|
||||||
|
|
||||||
|
it("dry-run previews every enter branch without authentication, requests or persistence", async () => {
|
||||||
|
rmSync(process.env.HOSE_ASSIST_PLATFORM_FILE!);
|
||||||
|
for (const extra of [[], ["--save"], ["--switch"], ["--save", "--switch", "--yes"]]) {
|
||||||
|
for (const json of [[], ["--json"]]) {
|
||||||
|
const result = await runCli([...enterArgs, ...extra, "--dry-run", ...json]);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(json.length ? JSON.parse(result.stdout).dryRun : result.stdout.includes("[DRY-RUN]")).toBe(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
expect(existsSync(join(corps, "NEW.json"))).toBe(false);
|
||||||
|
expect(existsSync(process.env.HOSE_CONFIG_FILE!)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runCli preserves delivered login URLs in text and JSON while redacting captured diagnostics", async () => {
|
||||||
|
logCredentials = true;
|
||||||
|
for (const extra of [[], ["--json"]]) {
|
||||||
|
const result = await runCli([...enterArgs, ...extra]);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(result.preserveSensitiveStdout).toBe(true);
|
||||||
|
expect(result.stdout).toContain(loginUrl);
|
||||||
|
expect(result.stderr).not.toContain(token);
|
||||||
|
expect(result.stderr).toContain("accessToken=<redacted>");
|
||||||
|
if (extra.length) expect(JSON.parse(result.stdout).loginUrl).toBe(loginUrl);
|
||||||
|
else expect(result.stdout).toContain("diagnostic https://session.example/web/thirdparty.html?accessToken=<redacted>");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("registers a newly imported enterprise before switching and persists its default", async () => {
|
||||||
|
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(JSON.parse(result.stdout).enterprise.switched).toBe(true);
|
||||||
|
expect(JSON.parse(result.stdout).sessionResult.loginUrl).toBe(loginUrl);
|
||||||
|
expect(JSON.parse(readFileSync(process.env.HOSE_CONFIG_FILE!, "utf8")).defaultCorpId).toBe("NEW");
|
||||||
|
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a failed switch without claiming success after saving the enterprise", async () => {
|
||||||
|
const switchMock = spyOn(CorpContext.prototype, "switchCorp").mockReturnValue(false);
|
||||||
|
try {
|
||||||
|
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
|
||||||
|
expect(result.exitCode).not.toBe(0);
|
||||||
|
expect(JSON.parse(result.stdout).message).toContain("配置已保存,但切换当前工作企业失败");
|
||||||
|
expect(result.stdout).not.toContain('"switched": true');
|
||||||
|
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||||
|
} finally { switchMock.mockRestore(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps error output redacted in text and JSON", async () => {
|
||||||
|
handleRequest = () => { throw new BusinessError(`换票失败 ${loginUrl}`); };
|
||||||
|
for (const extra of [[], ["--json"]]) {
|
||||||
|
const result = await runCli([...enterArgs, ...extra]);
|
||||||
|
expect(result.exitCode).not.toBe(0);
|
||||||
|
expect(result.preserveSensitiveStdout).not.toBe(true);
|
||||||
|
expect(result.stdout + result.stderr).not.toContain(token);
|
||||||
|
expect(result.stdout + result.stderr).toContain("accessToken=<redacted>");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("saves a valid temporary session without keys or key permission and tolerates multiple keys", async () => {
|
||||||
|
for (const response of [
|
||||||
|
() => Response.json({ items: [] }),
|
||||||
|
() => new Response("Forbidden", { status: 403 }),
|
||||||
|
() => Response.json({ items: [{ appKey: "a", appSecurity: "fixture-a" }, { appKey: "b", appSecurity: "fixture-b" }] }),
|
||||||
|
]) {
|
||||||
|
keysResponse = response;
|
||||||
|
const { corpConfig } = await importSession();
|
||||||
|
expect(corpConfig.credentials.accessToken).toBe(token);
|
||||||
|
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
|
||||||
|
}
|
||||||
|
requests = [];
|
||||||
|
await importSession({ elevate: false });
|
||||||
|
expect(requests.some((url) => url.includes("/innerapi/v1/key"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks failed or partial identity probes unknown instead of falsely reporting normal risk", async () => {
|
||||||
|
staffAvailable = false;
|
||||||
|
let identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||||
|
expect(identity.isAdmin).toBeNull();
|
||||||
|
expect(identity.isSeniorExecutive).toBeNull();
|
||||||
|
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||||
|
expect(identity.profileComplete).toBe(false);
|
||||||
|
expect(identity.unavailableFields).toContain("staff");
|
||||||
|
staffAvailable = true;
|
||||||
|
rolesAvailable = false;
|
||||||
|
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||||
|
expect(identity.isAdmin).toBe(false);
|
||||||
|
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||||
|
expect(identity.unavailableFields).toContain("roles");
|
||||||
|
rolesAvailable = true;
|
||||||
|
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||||
|
expect(identity.riskLevel).toBe("NORMAL");
|
||||||
|
expect(identity.profileComplete).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves a known JWT admin and records incomplete profile metadata on disk", async () => {
|
||||||
|
staffAvailable = false;
|
||||||
|
jwtAdmin = true;
|
||||||
|
const { corpConfig, sessionResult } = await importSession();
|
||||||
|
expect(corpConfig.session?.isAdmin).toBe(true);
|
||||||
|
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||||
|
expect(corpConfig.session?.staffName).toBe("JWT员工");
|
||||||
|
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
|
||||||
|
const persisted = JSON.parse(readFileSync(join(corps, "NEW.json"), "utf8"));
|
||||||
|
expect(persisted.session.identityComplete).toBe(false);
|
||||||
|
expect(persisted.session.identityUnavailableFields).toContain("staff");
|
||||||
|
expect(persisted.session.isAdmin).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not reuse a different employee's administrator or risk profile", async () => {
|
||||||
|
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:other", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
|
||||||
|
staffAvailable = false;
|
||||||
|
jwtAdmin = undefined;
|
||||||
|
const { corpConfig } = await importSession();
|
||||||
|
expect(corpConfig.session?.isAdmin).toBeUndefined();
|
||||||
|
expect(corpConfig.session?.permissions).toEqual([]);
|
||||||
|
expect(corpConfig.session?.riskLevel).toBe("UNKNOWN");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not treat malformed permissions or roles as an empty complete profile", async () => {
|
||||||
|
handleRequest = (req) => req.url.includes("/staffs/me")
|
||||||
|
? Response.json({ value: { staff: { id: "NEW:staff", admin: false }, permissions: [{}] } })
|
||||||
|
: Response.json({ items: [{}] });
|
||||||
|
const identity = await inspectAssistIdentity(token, "NEW", baseUrl);
|
||||||
|
expect(identity.profileComplete).toBe(false);
|
||||||
|
expect(identity.unavailableFields).toContain("permissions");
|
||||||
|
expect(identity.unavailableFields).toContain("roles");
|
||||||
|
expect(identity.riskLevel).toBe("UNKNOWN");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains known permissions for the same staff when a later probe is incomplete", async () => {
|
||||||
|
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
|
||||||
|
staffAvailable = false;
|
||||||
|
jwtAdmin = undefined;
|
||||||
|
const { corpConfig } = await importSession();
|
||||||
|
expect(corpConfig.session?.isAdmin).toBe(true);
|
||||||
|
expect(corpConfig.session?.permissions).toContain("SYS_ADMIN");
|
||||||
|
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("merges known partial roles with the same staff's previous roles before risk analysis", async () => {
|
||||||
|
saveCorpConfig({
|
||||||
|
id: "NEW",
|
||||||
|
name: "旧企业",
|
||||||
|
baseUrl,
|
||||||
|
source: "assist",
|
||||||
|
credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" },
|
||||||
|
session: { roles: ["普通员工"], riskLevel: "NORMAL" },
|
||||||
|
}, corps);
|
||||||
|
const originalHandler = handleRequest;
|
||||||
|
handleRequest = (req) => req.url.includes("/roles")
|
||||||
|
? Response.json({ items: [{ roleDefName: "财务总监" }, {}] })
|
||||||
|
: originalHandler(req);
|
||||||
|
|
||||||
|
const { corpConfig, sessionResult } = await importSession();
|
||||||
|
|
||||||
|
expect(sessionResult.identity?.roleNames).toEqual(["财务总监", "普通员工"]);
|
||||||
|
expect(sessionResult.identity?.seniorTitles).toContain("财务总监");
|
||||||
|
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
|
||||||
|
expect(corpConfig.session?.roles).toEqual(["财务总监", "普通员工"]);
|
||||||
|
expect(corpConfig.session?.roleTitles).toContain("财务总监");
|
||||||
|
expect(corpConfig.session?.riskLevel).toBe("HIGH");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"dictionary": "enum",
|
"dictionary": "enum",
|
||||||
"dict": "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") }
|
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||||
},
|
},
|
||||||
"bill": {
|
"bill": {
|
||||||
"summary": "单据检索、表单规格诊断与审批动作",
|
"summary": "单据检索、表单规格诊断与审批动作",
|
||||||
@@ -339,7 +339,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"url": "link",
|
"url": "link",
|
||||||
"specification": "spec"
|
"specification": "spec"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||||
},
|
},
|
||||||
"flow": {
|
"flow": {
|
||||||
"summary": "审批流全域透视与穿透诊断",
|
"summary": "审批流全域透视与穿透诊断",
|
||||||
@@ -368,7 +368,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"show": "get",
|
"show": "get",
|
||||||
"find": "get"
|
"find": "get"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||||
},
|
},
|
||||||
"contact": {
|
"contact": {
|
||||||
"summary": "企业通讯录与人员检索",
|
"summary": "企业通讯录与人员检索",
|
||||||
@@ -445,7 +445,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"costtype"
|
"costtype"
|
||||||
],
|
],
|
||||||
"commandAliases": {},
|
"commandAliases": {},
|
||||||
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
|
flags: { ...flagList("a all fields flat flatten ids ids-only include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query subtree subtree-id target title to", "value") }
|
||||||
},
|
},
|
||||||
"role": {
|
"role": {
|
||||||
"summary": "企业角色定义与成员",
|
"summary": "企业角色定义与成员",
|
||||||
@@ -541,6 +541,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||||
|
"gen-props": "生成业务对象字段常量与代码模板 (支持 MVEL / JS)",
|
||||||
"permissions": "查看权限",
|
"permissions": "查看权限",
|
||||||
"imports": "查看导入任务",
|
"imports": "查看导入任务",
|
||||||
"get": "查看应用详情"
|
"get": "查看应用详情"
|
||||||
@@ -580,11 +581,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
"update": "record",
|
"update": "record",
|
||||||
"batch-update": "record",
|
"batch-update": "record",
|
||||||
"record-recompute": "record",
|
"record-recompute": "record",
|
||||||
|
"gen-mvel-props": "gen-props",
|
||||||
|
"props": "gen-props",
|
||||||
"permission": "permissions",
|
"permission": "permissions",
|
||||||
"auth": "permissions",
|
"auth": "permissions",
|
||||||
"import-jobs": "imports"
|
"import-jobs": "imports"
|
||||||
},
|
},
|
||||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword lang language limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") }
|
||||||
},
|
},
|
||||||
"app": {
|
"app": {
|
||||||
"summary": "桌面端工作台应用管理",
|
"summary": "桌面端工作台应用管理",
|
||||||
@@ -819,7 +822,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
|||||||
},
|
},
|
||||||
flags: {
|
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("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")
|
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -255,9 +255,21 @@ describe("CLI Commands - assist-platform (合思协助平台)", () => {
|
|||||||
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"],
|
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"],
|
||||||
};
|
};
|
||||||
|
|
||||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
const originalFetch = globalThis.fetch;
|
||||||
expect(res.stdout).toContain("[DRY-RUN]");
|
globalThis.fetch = (async () => Response.json({
|
||||||
expect(res.stdout).toContain("ID01Xenwiu9w0D");
|
items: [{
|
||||||
expect(res.stdout).toContain("陈龙");
|
id: "role-chenlong",
|
||||||
|
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
|
||||||
|
}],
|
||||||
|
})) as unknown as typeof globalThis.fetch;
|
||||||
|
try {
|
||||||
|
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||||
|
expect(res.stdout).toContain("[DRY-RUN]");
|
||||||
|
expect(res.stdout).toContain("ID01Xenwiu9w0D");
|
||||||
|
expect(res.stdout).toContain("陈龙");
|
||||||
|
expect(res.stdout).toContain("chenlong3016");
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -13,10 +13,8 @@ export async function handleApprove(
|
|||||||
parsed: CliParsedArgs,
|
parsed: CliParsedArgs,
|
||||||
runtime: CliRuntime
|
runtime: CliRuntime
|
||||||
): Promise<CliResult> {
|
): Promise<CliResult> {
|
||||||
const explicitCorpId =
|
const corpOption = stringOption(parsed.options, ["corp", "corpid", "id"]);
|
||||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
const explicitCorpId = corpOption || parsed.args[0] || runtime.selectedCorp?.id;
|
||||||
parsed.args[0] ||
|
|
||||||
runtime.selectedCorp?.id;
|
|
||||||
|
|
||||||
if (!explicitCorpId) {
|
if (!explicitCorpId) {
|
||||||
return {
|
return {
|
||||||
@@ -31,22 +29,38 @@ export async function handleApprove(
|
|||||||
|
|
||||||
// 1. 识别 corpId 与 ticketId
|
// 1. 识别 corpId 与 ticketId
|
||||||
const allCorps = runtime.corpContext?.getAllCorps?.() || [];
|
const allCorps = runtime.corpContext?.getAllCorps?.() || [];
|
||||||
let targetCorp =
|
const findCorp = (id: string) =>
|
||||||
allCorps.find((c) => c.id === explicitCorpId || c.corpId === explicitCorpId) ||
|
allCorps.find((c) => c.id === id || c.corpId === id) ||
|
||||||
(runtime.selectedCorp?.id === explicitCorpId || runtime.selectedCorp?.corpId === explicitCorpId
|
(runtime.selectedCorp?.id === id || runtime.selectedCorp?.corpId === id
|
||||||
? runtime.selectedCorp
|
? runtime.selectedCorp
|
||||||
: undefined);
|
: undefined);
|
||||||
|
let targetCorp = findCorp(explicitCorpId);
|
||||||
let ticketId = stringOption(parsed.options, ["ticket", "ticket-id"]);
|
const ticketOption = stringOption(parsed.options, ["ticket", "ticket-id"]);
|
||||||
|
let positionalTicketId: string | undefined;
|
||||||
|
|
||||||
// 如果第 0 个参数不是企业,可能是工单编号
|
// 如果第 0 个参数不是企业,可能是工单编号
|
||||||
if (!targetCorp && parsed.args[0]) {
|
if (corpOption) {
|
||||||
ticketId = parsed.args[0];
|
// 显式企业选项下,唯一位置参数始终是工单,不能被本地企业命中结果覆盖。
|
||||||
|
positionalTicketId = parsed.args[0];
|
||||||
|
} else if (!targetCorp && parsed.args[0]) {
|
||||||
|
positionalTicketId = parsed.args[0];
|
||||||
targetCorp = runtime.selectedCorp ?? undefined;
|
targetCorp = runtime.selectedCorp ?? undefined;
|
||||||
} else if (targetCorp && parsed.args[1]) {
|
} else if (targetCorp && parsed.args[1]) {
|
||||||
ticketId = parsed.args[1];
|
positionalTicketId = parsed.args[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const maxArgs = !corpOption && parsed.args[0] && findCorp(parsed.args[0]) ? 2 : 1;
|
||||||
|
if (parsed.args.length > maxArgs ||
|
||||||
|
(ticketOption && positionalTicketId && ticketOption !== positionalTicketId)) {
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: "[ERROR] 企业或工单参数存在歧义或冲突。请使用 approve <工单ID> --corp <企业ID>,且 --ticket 必须与位置工单一致。\n",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let ticketId = ticketOption || positionalTicketId;
|
||||||
|
|
||||||
if (!targetCorp) {
|
if (!targetCorp) {
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { BusinessError } from "../../../core/errors.js";
|
||||||
import {
|
import {
|
||||||
generateAssistSession,
|
generateAssistSession,
|
||||||
importAssistSessionToLocal,
|
importAssistSessionToLocal,
|
||||||
@@ -29,6 +30,10 @@ function formatIdentityLines(ident?: AssistIdentityProfile): {
|
|||||||
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
|
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (ident.profileComplete === false) {
|
||||||
|
profilePairs["身份画像状态"] = "信息不完整,无法排除更高权限风险";
|
||||||
|
}
|
||||||
|
|
||||||
if (ident.isSeniorExecutive && ident.riskWarning) {
|
if (ident.isSeniorExecutive && ident.riskWarning) {
|
||||||
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
|
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
|
||||||
warningText =
|
warningText =
|
||||||
@@ -47,7 +52,6 @@ export async function handleEnter(
|
|||||||
parsed: CliParsedArgs,
|
parsed: CliParsedArgs,
|
||||||
runtime: CliRuntime
|
runtime: CliRuntime
|
||||||
): Promise<CliResult> {
|
): Promise<CliResult> {
|
||||||
const client = resolveAssistClient(parsed, runtime);
|
|
||||||
const corpId =
|
const corpId =
|
||||||
parsed.args[0] ||
|
parsed.args[0] ||
|
||||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||||
@@ -72,6 +76,28 @@ export async function handleEnter(
|
|||||||
const overwrite = booleanOption(parsed.options, ["overwrite"]);
|
const overwrite = booleanOption(parsed.options, ["overwrite"]);
|
||||||
const saveName = stringOption(parsed.options, ["alias", "corp-name"]);
|
const saveName = stringOption(parsed.options, ["alias", "corp-name"]);
|
||||||
|
|
||||||
|
if (isDryRun(parsed, runtime)) {
|
||||||
|
return mutationPreview(
|
||||||
|
parsed,
|
||||||
|
runtime,
|
||||||
|
shouldSave || shouldSwitch
|
||||||
|
? "从协助平台换取免密凭证并落盘为本地企业配置"
|
||||||
|
: "从协助平台换取免密凭证并生成直通链接",
|
||||||
|
saveName || `企业 [${corpId}]`,
|
||||||
|
{
|
||||||
|
corpId,
|
||||||
|
isAdmin,
|
||||||
|
staffName: staffName || null,
|
||||||
|
ticketId: ticketId || "自动选择最新有效工单",
|
||||||
|
save: shouldSave || shouldSwitch,
|
||||||
|
switchCurrent: shouldSwitch,
|
||||||
|
overwrite,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = resolveAssistClient(parsed, runtime);
|
||||||
|
|
||||||
// 1. 若不要求保存落盘,仅生成直通免密链接输出
|
// 1. 若不要求保存落盘,仅生成直通免密链接输出
|
||||||
if (!shouldSave && !shouldSwitch) {
|
if (!shouldSave && !shouldSwitch) {
|
||||||
const sessionRes = await generateAssistSession(client, {
|
const sessionRes = await generateAssistSession(client, {
|
||||||
@@ -84,6 +110,7 @@ export async function handleEnter(
|
|||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson(sessionRes, runtime.outputOptions),
|
stdout: printJson(sessionRes, runtime.outputOptions),
|
||||||
|
preserveSensitiveStdout: true,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -101,6 +128,7 @@ export async function handleEnter(
|
|||||||
Object.assign(pairs, profilePairs);
|
Object.assign(pairs, profilePairs);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
preserveSensitiveStdout: true,
|
||||||
stdout:
|
stdout:
|
||||||
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
|
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
|
||||||
`${warningText}\n操作提示:\n` +
|
`${warningText}\n操作提示:\n` +
|
||||||
@@ -112,23 +140,6 @@ export async function handleEnter(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. 要求持久化落盘 / 切换为工作企业
|
// 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`;
|
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
|
||||||
requireMutationConfirmation(
|
requireMutationConfirmation(
|
||||||
parsed,
|
parsed,
|
||||||
@@ -146,13 +157,18 @@ export async function handleEnter(
|
|||||||
overwrite: overwrite ?? true,
|
overwrite: overwrite ?? true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 导入文件后同步注册到当前运行态,确保新企业可立即切换
|
||||||
|
runtime.corpContext.upsertCorp(corpConfig);
|
||||||
|
|
||||||
// 若指定了 --switch,切换当前激活企业
|
// 若指定了 --switch,切换当前激活企业
|
||||||
if (shouldSwitch) {
|
const switched = shouldSwitch && runtime.corpContext.switchCorp(corpConfig.id, true);
|
||||||
runtime.corpContext.switchCorp(corpConfig.id, true);
|
if (shouldSwitch && !switched) {
|
||||||
|
throw new BusinessError(`企业 [${corpConfig.id}] 配置已保存,但切换当前工作企业失败,请运行 hose-use corps switch ${corpConfig.id} 重试`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
|
preserveSensitiveStdout: true,
|
||||||
stdout: printJson({
|
stdout: printJson({
|
||||||
success: true,
|
success: true,
|
||||||
sessionResult,
|
sessionResult,
|
||||||
@@ -161,7 +177,7 @@ export async function handleEnter(
|
|||||||
name: corpConfig.name,
|
name: corpConfig.name,
|
||||||
staffId: corpConfig.credentials.staffId,
|
staffId: corpConfig.credentials.staffId,
|
||||||
hasOpenApi: Boolean(corpConfig.credentials.appKey),
|
hasOpenApi: Boolean(corpConfig.credentials.appKey),
|
||||||
switched: shouldSwitch,
|
switched,
|
||||||
},
|
},
|
||||||
}, runtime.outputOptions),
|
}, runtime.outputOptions),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
@@ -176,7 +192,7 @@ export async function handleEnter(
|
|||||||
授权工单: sessionResult.ticketId,
|
授权工单: sessionResult.ticketId,
|
||||||
凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话",
|
凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话",
|
||||||
配置文件: `enterprises/${corpConfig.id}.json`,
|
配置文件: `enterprises/${corpConfig.id}.json`,
|
||||||
激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
|
激活状态: switched ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
|
||||||
};
|
};
|
||||||
|
|
||||||
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
|
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { listAssistTickets } from "../../../domains/assist-platform/services.js";
|
import { listAssistTickets } from "../../../domains/assist-platform/services.js";
|
||||||
import { stringOption } from "../../parser.js";
|
import { booleanOption, stringOption } from "../../parser.js";
|
||||||
import { printJson, printTable } from "../../printer.js";
|
import { printJson, printTable } from "../../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
import { resolveAssistClient } from "./common.js";
|
import { resolveAssistClient } from "./common.js";
|
||||||
@@ -9,6 +9,7 @@ export async function handleTickets(
|
|||||||
runtime: CliRuntime
|
runtime: CliRuntime
|
||||||
): Promise<CliResult> {
|
): Promise<CliResult> {
|
||||||
const client = resolveAssistClient(parsed, runtime);
|
const client = resolveAssistClient(parsed, runtime);
|
||||||
|
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||||
const corpId =
|
const corpId =
|
||||||
parsed.args[0] ||
|
parsed.args[0] ||
|
||||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||||
@@ -17,7 +18,7 @@ export async function handleTickets(
|
|||||||
if (!corpId) {
|
if (!corpId) {
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: "用法: hose-use assist-platform tickets <企业ID>\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
|
stderr: "用法: hose-use assist-platform tickets <企业ID> [--all]\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -26,7 +27,7 @@ export async function handleTickets(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({ corporationId: corpId, count: tickets.length, tickets }, runtime.outputOptions),
|
stdout: printJson({ corporationId: corpId, count: tickets.length, all: isAll, tickets }, runtime.outputOptions),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -86,20 +86,11 @@ export async function handleTransfer(
|
|||||||
try {
|
try {
|
||||||
resolvedRecipient = await resolveTransferRecipient(client, targetRecipient);
|
resolvedRecipient = await resolveTransferRecipient(client, targetRecipient);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (isDryRun(parsed, runtime)) {
|
return {
|
||||||
resolvedRecipient = {
|
stdout: "",
|
||||||
id: targetRecipient,
|
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
|
||||||
name: targetRecipient,
|
exitCode: 1,
|
||||||
userRoleId: "",
|
};
|
||||||
roles: [],
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return {
|
|
||||||
stdout: "",
|
|
||||||
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
|
|
||||||
exitCode: 1,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ticketId) {
|
if (!ticketId) {
|
||||||
@@ -136,7 +127,7 @@ export async function handleTransfer(
|
|||||||
parsed,
|
parsed,
|
||||||
runtime,
|
runtime,
|
||||||
operation,
|
operation,
|
||||||
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.name}" --yes`
|
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.id}" --yes`
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = await transferAssistTicket(client, {
|
const result = await transferAssistTicket(client, {
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||||
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
import { parseArgs } from "../parser.js";
|
||||||
|
import type { CliRuntime } from "../types.js";
|
||||||
|
import { handleApprove } from "./assist-platform/approve.js";
|
||||||
|
import { handleTransfer } from "./assist-platform/transfer.js";
|
||||||
|
|
||||||
|
const corp: CorpConfig = {
|
||||||
|
id: "CORP", corpId: "CORP", name: "测试企业", source: "manual",
|
||||||
|
baseUrl: "https://corp.invalid",
|
||||||
|
credentials: { accessToken: "mock-token", corpId: "CORP", staffId: "ADMIN" },
|
||||||
|
};
|
||||||
|
const otherCorp: CorpConfig = { ...corp, id: "OTHER-CORP", corpId: "OTHER-CORP" };
|
||||||
|
const sameNameUsers = [
|
||||||
|
{ id: "ROLE1", userId: { id: "user3016", name: "张三", code: "3016" } },
|
||||||
|
{ id: "ROLE2", userId: { id: "user3020", name: "张三", code: "3020" } },
|
||||||
|
];
|
||||||
|
|
||||||
|
function runtime(selectedCorp: CorpConfig | null = corp): CliRuntime {
|
||||||
|
return {
|
||||||
|
jsonMode: true, selectedCorp,
|
||||||
|
corpContext: { getAllCorps: () => [corp, otherCorp] } as CliRuntime["corpContext"],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let originalFetch: typeof globalThis.fetch;
|
||||||
|
let originalStore: string | undefined;
|
||||||
|
let stateDir: string;
|
||||||
|
let requests: Request[];
|
||||||
|
let responses: (request: Request) => Response | Promise<Response>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalFetch = globalThis.fetch;
|
||||||
|
originalStore = process.env.HOSE_ASSIST_PLATFORM_FILE;
|
||||||
|
stateDir = mkdtempSync(join(tmpdir(), "hose-assist-targets-"));
|
||||||
|
process.env.HOSE_ASSIST_PLATFORM_FILE = join(stateDir, "session.json");
|
||||||
|
requests = [];
|
||||||
|
responses = () => Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
|
||||||
|
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||||
|
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||||
|
// Bun 的 Request.clone 声明采用 undici Headers;运行态仍是同一个 Request 类型。
|
||||||
|
requests.push(request.clone() as unknown as Request);
|
||||||
|
return responses(request);
|
||||||
|
}) as typeof globalThis.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
if (originalStore === undefined) delete process.env.HOSE_ASSIST_PLATFORM_FILE;
|
||||||
|
else process.env.HOSE_ASSIST_PLATFORM_FILE = originalStore;
|
||||||
|
rmSync(stateDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("assist-platform approve 的明确工单目标", () => {
|
||||||
|
it.each([
|
||||||
|
["REQUESTED", "--corp", "CORP"],
|
||||||
|
["CORP", "REQUESTED"],
|
||||||
|
["CORP", "--ticket", "REQUESTED"],
|
||||||
|
["--corp", "CORP", "--ticket", "REQUESTED"],
|
||||||
|
["REQUESTED"],
|
||||||
|
["--ticket", "REQUESTED"],
|
||||||
|
["REQUESTED", "--corp", "CORP", "--ticket", "REQUESTED"],
|
||||||
|
].map((args) => ({ args })))("预览保留工单参数 %j,不自动查询其他工单", async ({ args }) => {
|
||||||
|
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--dry-run"]), runtime());
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("REQUESTED");
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("显式 --corp 下首参即使也是已知企业 ID,仍作为工单", async () => {
|
||||||
|
const parsed = parseArgs(["assist-platform", "approve", "OTHER-CORP", "--corp", "CORP", "--dry-run"]);
|
||||||
|
const result = await handleApprove(parsed, runtime());
|
||||||
|
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-CORP");
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("--yes 真实提交路径只审批显式工单,不能自动替换为列表首项", async () => {
|
||||||
|
responses = (request) => request.method === "PUT"
|
||||||
|
? Response.json({ value: { id: "REQUESTED", corporationId: "CORP" } })
|
||||||
|
: Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
|
||||||
|
const result = await handleApprove(
|
||||||
|
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "CORP", "--yes"]), runtime()
|
||||||
|
);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(requests).toHaveLength(1);
|
||||||
|
expect(requests[0].method).toBe("PUT");
|
||||||
|
expect(requests[0].url).toContain("/$REQUESTED/updateStatus?corpId=CORP");
|
||||||
|
expect(await requests[0].json()).toEqual({ id: "REQUESTED", status: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["REQUESTED", "--corp", "CORP", "--ticket", "OTHER-TICKET"],
|
||||||
|
["CORP", "REQUESTED", "--ticket", "OTHER-TICKET"],
|
||||||
|
["UNKNOWN-CORP", "REQUESTED"],
|
||||||
|
["CORP", "REQUESTED", "--corp", "OTHER-CORP"],
|
||||||
|
["CORP", "REQUESTED", "EXTRA"],
|
||||||
|
].map((args) => ({ args })))("拒绝歧义或冲突参数 %j,且不查询或提交", async ({ args }) => {
|
||||||
|
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--yes"]), runtime());
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stderr).toContain("歧义或冲突");
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("显式企业未知时不能回退当前企业", async () => {
|
||||||
|
const result = await handleApprove(
|
||||||
|
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "UNKNOWN", "--yes"]), runtime()
|
||||||
|
);
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stderr).toContain("UNKNOWN");
|
||||||
|
expect(requests).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("只有未指定工单时才自动查询待授权工单", async () => {
|
||||||
|
const result = await handleApprove(parseArgs([
|
||||||
|
"assist-platform", "approve", "--corp", "CORP", "--token", "mock-token", "--dry-run",
|
||||||
|
]), runtime());
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-TICKET");
|
||||||
|
expect(requests).toHaveLength(1);
|
||||||
|
expect(requests[0].url).toContain("assistPlatform/$CORP/search");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("assist-platform transfer 预览与执行的收件人解析", () => {
|
||||||
|
it.each(["--dry-run", "--yes"])("%s 遇到同名用户都拒绝且不提交", async (mode) => {
|
||||||
|
responses = () => Response.json({ items: sameNameUsers });
|
||||||
|
const result = await handleTransfer(parseArgs([
|
||||||
|
"assist-platform", "transfer", "CORP", "TICKET", "--to", "张三", "--token", "mock-token", mode,
|
||||||
|
]), runtime());
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stderr).toContain("唯一工号或账号");
|
||||||
|
expect(requests).toHaveLength(1);
|
||||||
|
expect(requests[0].url).toContain("userRole/search");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("查询失败的 dry-run 也不能显示成功解析的预览", async () => {
|
||||||
|
responses = () => new Response("unauthorized", { status: 401 });
|
||||||
|
const result = await handleTransfer(parseArgs([
|
||||||
|
"assist-platform", "transfer", "CORP", "TICKET", "--to", "user3016", "--token", "mock-token", "--dry-run",
|
||||||
|
]), runtime());
|
||||||
|
expect(result.exitCode).toBe(1);
|
||||||
|
expect(result.stdout).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("唯一工号的 dry-run 显示实际账号,与 --yes 的请求一致", async () => {
|
||||||
|
responses = (request) => request.url.includes("userRole/search")
|
||||||
|
? Response.json({ items: sameNameUsers })
|
||||||
|
: Response.json({ value: true });
|
||||||
|
const args = ["assist-platform", "transfer", "CORP", "TICKET", "--to", "3016", "--token", "mock-token"];
|
||||||
|
const preview = await handleTransfer(parseArgs([...args, "--dry-run"]), runtime());
|
||||||
|
expect(JSON.parse(preview.stdout).changes.recipientId).toBe("user3016");
|
||||||
|
const result = await handleTransfer(parseArgs([...args, "--yes"]), runtime());
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
const writes = requests.filter((request) => request.url.includes("assistPlatform/transfer"));
|
||||||
|
expect(writes).toHaveLength(1);
|
||||||
|
expect(await writes[0].json()).toEqual({ assistId: "TICKET", recipient: "user3016" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -207,7 +207,8 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const client = await ctx.getClient();
|
const client = await ctx.getClient();
|
||||||
const report = await traceBillFlowDetail(client, corpId, target);
|
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
|
||||||
|
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
|
||||||
|
|
||||||
if (!report.found) {
|
if (!report.found) {
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
|||||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||||
import { handleCorpsCommand } from "./corps/index.js";
|
import { handleCorpsCommand } from "./corps/index.js";
|
||||||
import type { CliRuntime } from "../types.js";
|
import type { CliRuntime } from "../types.js";
|
||||||
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
|
||||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||||
it("successfully parses standard thirdparty.html assistance links", () => {
|
it("successfully parses standard thirdparty.html assistance links", () => {
|
||||||
@@ -418,4 +419,86 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
|||||||
expect(res.exitCode).toBe(0);
|
expect(res.exitCode).toBe(0);
|
||||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("supports corps hose-staffs with auto-resolved corp credentials", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
try {
|
||||||
|
globalThis.fetch = (async (input: unknown) => {
|
||||||
|
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as { url: string }).url;
|
||||||
|
if (urlStr.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
value: {
|
||||||
|
accessToken: "mock-open-token",
|
||||||
|
corporationId: "corpKeyed",
|
||||||
|
corporation: { id: "corpKeyed", name: "已配密钥企业" },
|
||||||
|
},
|
||||||
|
}), { status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("/api/openapi/v1/roleDefGroups")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: "g1",
|
||||||
|
name: "默认组",
|
||||||
|
roleDefs: [
|
||||||
|
{ id: "corpKeyed:admin", name: "主管理员" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}), { status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("/api/openapi/v1/roledefs/")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
value: {
|
||||||
|
id: "corpKeyed:admin",
|
||||||
|
name: "主管理员",
|
||||||
|
count: 1,
|
||||||
|
contents: [{ staffs: ["corpKeyed:staff1"] }],
|
||||||
|
},
|
||||||
|
}), { status: 200 });
|
||||||
|
}
|
||||||
|
if (urlStr.includes("/api/openapi/v1/staffs/getStaffIds")) {
|
||||||
|
return new Response(JSON.stringify({
|
||||||
|
items: [
|
||||||
|
{ id: "corpKeyed:staff1", name: "测试管理员", code: "001", active: true },
|
||||||
|
],
|
||||||
|
}), { status: 200 });
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({}), { status: 200 });
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const corpWithKeys: CorpConfig = {
|
||||||
|
id: "corpKeyed",
|
||||||
|
name: "已配密钥企业",
|
||||||
|
baseUrl: "https://app.ekuaibao.com",
|
||||||
|
source: "openapi",
|
||||||
|
credentials: {
|
||||||
|
accessToken: "token-x",
|
||||||
|
corpId: "corpKeyed",
|
||||||
|
staffId: "corpKeyed:STAFF",
|
||||||
|
appKey: "my-key-123",
|
||||||
|
appSecurity: "my-sec-456",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await handleCorpsCommand(
|
||||||
|
{
|
||||||
|
area: "corps",
|
||||||
|
action: "hose-staffs",
|
||||||
|
args: [],
|
||||||
|
options: { role: "admin", json: true },
|
||||||
|
raw: ["corps", "hose-staffs", "--role=admin", "--json"],
|
||||||
|
},
|
||||||
|
{ ...searchRuntime, selectedCorp: corpWithKeys, jsonMode: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.roleName).toBe("主管理员");
|
||||||
|
expect(data.staffs).toHaveLength(1);
|
||||||
|
expect(data.staffs[0].name).toBe("测试管理员");
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -43,15 +43,21 @@ export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
let appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
let appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
let domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||||
|
|
||||||
|
if ((!appKey || !appSecurity) && runtime.selectedCorp?.credentials?.appKey && runtime.selectedCorp?.credentials?.appSecurity) {
|
||||||
|
appKey = runtime.selectedCorp.credentials.appKey;
|
||||||
|
appSecurity = runtime.selectedCorp.credentials.appSecurity;
|
||||||
|
domain = domain || runtime.selectedCorp.baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
if (!appKey || !appSecurity) {
|
if (!appKey || !appSecurity) {
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
stderr: "用法: hose-use corps hose-staffs [--corp=<id>] [--app-key=<key> --app-security=<secret>] [--role=admin]\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,6 +106,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
|||||||
total: 3,
|
total: 3,
|
||||||
items: mockTree,
|
items: mockTree,
|
||||||
rawTree: mockTree,
|
rawTree: mockTree,
|
||||||
|
ids: ["COST01", "COST02", "COST19"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const res = await handleFeeTypeCommand(
|
const res = await handleFeeTypeCommand(
|
||||||
@@ -134,6 +135,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
|||||||
total: 2,
|
total: 2,
|
||||||
items: mockTree,
|
items: mockTree,
|
||||||
rawTree: mockTree,
|
rawTree: mockTree,
|
||||||
|
ids: ["COST01", "COST02"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||||
|
|||||||
@@ -84,11 +84,15 @@ export async function handleFeeTypeCommand(
|
|||||||
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
||||||
const keyword =
|
const keyword =
|
||||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||||
|
const subtree = stringOption(parsed.options, ["subtree", "subtree-id", "parent-id"]);
|
||||||
|
const idsOnly = booleanOption(parsed.options, ["ids-only", "ids"]) || false;
|
||||||
|
|
||||||
const result = await listFeeTypes(await getClient(), corpId, {
|
const result = await listFeeTypes(await getClient(), corpId, {
|
||||||
all: includeAll,
|
all: includeAll,
|
||||||
flat: isFlat,
|
flat: isFlat || Boolean(subtree) || idsOnly,
|
||||||
keyword,
|
keyword,
|
||||||
|
subtreeParentId: subtree || undefined,
|
||||||
|
idsOnly,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
@@ -100,7 +104,7 @@ export async function handleFeeTypeCommand(
|
|||||||
total: result.total,
|
total: result.total,
|
||||||
includeDisabled: includeAll,
|
includeDisabled: includeAll,
|
||||||
keyword: keyword || null,
|
keyword: keyword || null,
|
||||||
items: result.items,
|
...(idsOnly ? { ids: result.ids } : { items: result.items }),
|
||||||
},
|
},
|
||||||
runtime.outputOptions
|
runtime.outputOptions
|
||||||
),
|
),
|
||||||
@@ -109,8 +113,16 @@ export async function handleFeeTypeCommand(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (idsOnly) {
|
||||||
|
return {
|
||||||
|
stdout: JSON.stringify(result.ids) + "\n",
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
let rows: (string | number)[][] = [];
|
let rows: (string | number)[][] = [];
|
||||||
if (!isFlat && !keyword) {
|
if (!isFlat && !keyword && !subtree) {
|
||||||
rows = renderTreeRows(result.rawTree);
|
rows = renderTreeRows(result.rawTree);
|
||||||
} else {
|
} else {
|
||||||
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
||||||
@@ -126,7 +138,7 @@ export async function handleFeeTypeCommand(
|
|||||||
|
|
||||||
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
||||||
includeAll ? ",含停用" : ""
|
includeAll ? ",含停用" : ""
|
||||||
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
|
}${keyword ? `,过滤: "${keyword}"` : ""}${subtree ? `,子树: "${subtree}"` : ""}) ======`;
|
||||||
const tableStr = rows.length
|
const tableStr = rows.length
|
||||||
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
||||||
: "暂无匹配的费用类型";
|
: "暂无匹配的费用类型";
|
||||||
|
|||||||
@@ -525,5 +525,38 @@ describe("CLI - platform 命令与 record 动作", () => {
|
|||||||
expect(fetch).not.toHaveBeenCalled();
|
expect(fetch).not.toHaveBeenCalled();
|
||||||
expect(write).not.toHaveBeenCalled();
|
expect(write).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("platform gen-props 生成 MVEL 和 JS 格式的字段模板", async () => {
|
||||||
|
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||||
|
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||||
|
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
|
||||||
|
id: "E_contract",
|
||||||
|
name: "合同",
|
||||||
|
code: "CONTRACT",
|
||||||
|
fields: [
|
||||||
|
{ name: "E_contract_name", label: "合同名称", type: "text", optional: false },
|
||||||
|
{ name: "E_contract_amount", label: "合同金额", type: "money", optional: true },
|
||||||
|
],
|
||||||
|
} as any));
|
||||||
|
|
||||||
|
// MVEL 模板 (默认)
|
||||||
|
const mvelRes = await handlePlatformCommand(
|
||||||
|
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: {}, raw: [] },
|
||||||
|
dummyRuntime
|
||||||
|
);
|
||||||
|
expect(mvelRes.exitCode).toBe(0);
|
||||||
|
expect(mvelRes.stdout).toContain('String TARGET_ENTITY_ID = "E_contract";');
|
||||||
|
expect(mvelRes.stdout).toContain('String FIELD_合同名称 = FIELD_PREFIX + "name";');
|
||||||
|
expect(mvelRes.stdout).toContain('row.put(FIELD_合同名称, "");');
|
||||||
|
|
||||||
|
// JS 模板
|
||||||
|
const jsRes = await handlePlatformCommand(
|
||||||
|
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: { lang: "js" }, raw: [] },
|
||||||
|
dummyRuntime
|
||||||
|
);
|
||||||
|
expect(jsRes.exitCode).toBe(0);
|
||||||
|
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||||
|
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,10 +50,55 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||||
const entities = resolved.entity ? [resolved.entity] : await listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
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 fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
const output = entities.map((entity) => ({
|
||||||
|
...entity,
|
||||||
|
fields: fieldKeyword
|
||||||
|
? entity.fields.filter((field) =>
|
||||||
|
[field.name, field.label, field.type, field.fieldKey, field.displayName].some(
|
||||||
|
(value) => typeof value === "string" && value.toLowerCase().includes(fieldKeyword)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
: entity.fields,
|
||||||
|
}));
|
||||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
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)]));
|
const rows = output.flatMap((entity) =>
|
||||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
entity.fields.map((field): Array<string | number | boolean | null | undefined> => {
|
||||||
|
const roleTag =
|
||||||
|
field.role === "title"
|
||||||
|
? "⭐ 主标题 (_name)"
|
||||||
|
: field.role === "code"
|
||||||
|
? "🔢 业务编码 (_code)"
|
||||||
|
: field.role === "system"
|
||||||
|
? "⚙️ 系统字段"
|
||||||
|
: "📝 业务字段";
|
||||||
|
return [
|
||||||
|
entity.name,
|
||||||
|
field.name,
|
||||||
|
field.label,
|
||||||
|
field.type,
|
||||||
|
roleTag,
|
||||||
|
field.optional === false ? "必填" : "可选",
|
||||||
|
cell(field.entity),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const table = printTable(
|
||||||
|
["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"],
|
||||||
|
rows
|
||||||
|
);
|
||||||
|
const tips = [
|
||||||
|
"",
|
||||||
|
"💡 字段命名与工作流配置避坑提示:",
|
||||||
|
" 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。",
|
||||||
|
" 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);",
|
||||||
|
" 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
return {
|
||||||
|
stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
@@ -77,3 +122,90 @@ export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
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 };
|
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function handleGenProps(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||||
|
if (!resolved.entity) {
|
||||||
|
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform gen-props <应用> <业务对象> [--lang=mvel|js]");
|
||||||
|
}
|
||||||
|
|
||||||
|
const lang = (stringOption(parsed.options, ["lang", "language"]) || "mvel").toLowerCase();
|
||||||
|
const entity = resolved.entity;
|
||||||
|
const entityId = entity.id;
|
||||||
|
const entityName = entity.name;
|
||||||
|
const prefix = entityId ? `${entityId}_` : "";
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(
|
||||||
|
{
|
||||||
|
platform: resolved.platform,
|
||||||
|
entity: {
|
||||||
|
id: entity.id,
|
||||||
|
name: entity.name,
|
||||||
|
code: entity.code,
|
||||||
|
prefix,
|
||||||
|
fields: entity.fields.map((f) => ({
|
||||||
|
fieldKey: f.name,
|
||||||
|
label: f.label,
|
||||||
|
type: f.type,
|
||||||
|
suffix: f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines: string[] = [];
|
||||||
|
if (lang === "js" || lang === "javascript") {
|
||||||
|
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (JS / QuickJS) ======`);
|
||||||
|
lines.push(`const ENTITY_ID = "${entityId}";`);
|
||||||
|
lines.push(`const FIELD_PREFIX = "${prefix}";`);
|
||||||
|
lines.push("");
|
||||||
|
lines.push("// ── 字段物理键定义 ──");
|
||||||
|
lines.push("const FIELDS = {");
|
||||||
|
for (const f of entity.fields) {
|
||||||
|
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||||
|
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||||
|
lines.push(` "${safeLabel}": FIELD_PREFIX + "${suffix}", // ${f.type || "text"}${f.optional === false ? " [必填]" : ""}`);
|
||||||
|
}
|
||||||
|
lines.push("};");
|
||||||
|
lines.push("");
|
||||||
|
lines.push("// ── 写入数据对象示例 ──");
|
||||||
|
lines.push("const recordData = {");
|
||||||
|
for (const f of entity.fields) {
|
||||||
|
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||||
|
lines.push(` [FIELDS["${safeLabel}"]]: "", // ${f.label}`);
|
||||||
|
}
|
||||||
|
lines.push("};");
|
||||||
|
} else {
|
||||||
|
// 默认 MVEL 模板
|
||||||
|
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (MVEL) ======`);
|
||||||
|
lines.push(`String TARGET_ENTITY_ID = "${entityId}";`);
|
||||||
|
lines.push(`String FIELD_PREFIX = "${prefix}";`);
|
||||||
|
lines.push("");
|
||||||
|
lines.push("// ── 物理字段键常量 ──");
|
||||||
|
for (const f of entity.fields) {
|
||||||
|
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||||
|
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||||
|
lines.push(`String ${constName} = FIELD_PREFIX + "${suffix}"; // ${f.label} (${f.type || "text"})${f.optional === false ? " [必填]" : ""}`);
|
||||||
|
}
|
||||||
|
lines.push("");
|
||||||
|
lines.push("// ── DataLink 行构建模板 (row.put) ──");
|
||||||
|
lines.push("Map row = new HashMap();");
|
||||||
|
for (const f of entity.fields) {
|
||||||
|
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||||
|
lines.push(`row.put(${constName}, ""); // ${f.label}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: `${lines.join("\n")}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { booleanOption } from "../../parser.js";
|
import { booleanOption } from "../../parser.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js";
|
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports, handleGenProps } from "./app-info.js";
|
||||||
import { handleRecords, handleAudit } from "./records.js";
|
import { handleRecords, handleAudit } from "./records.js";
|
||||||
import { handleRecordAction } from "./record-actions.js";
|
import { handleRecordAction } from "./record-actions.js";
|
||||||
|
|
||||||
@@ -47,9 +47,12 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
|||||||
case "permissions":
|
case "permissions":
|
||||||
case "permission":
|
case "permission":
|
||||||
case "auth": return handlePermissions(parsed, runtime);
|
case "auth": return handlePermissions(parsed, runtime);
|
||||||
|
case "gen-props":
|
||||||
|
case "gen-mvel-props":
|
||||||
|
case "props": return handleGenProps(parsed, runtime);
|
||||||
case "imports":
|
case "imports":
|
||||||
case "import-jobs": return handleImports(parsed, runtime);
|
case "import-jobs": return handleImports(parsed, runtime);
|
||||||
default:
|
default:
|
||||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, gen-props, permissions, imports\n`, exitCode: 1 };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
auditEntityRecords,
|
auditEntityRecords,
|
||||||
auditLedgerContinuityAndBaseline,
|
auditLedgerContinuityAndBaseline,
|
||||||
buildKeywordFilter,
|
buildKeywordFilter,
|
||||||
|
buildServerFieldFilter,
|
||||||
calculateEntityRecordStats,
|
calculateEntityRecordStats,
|
||||||
fetchAllEntityRecords,
|
fetchAllEntityRecords,
|
||||||
compileRecordPredicate,
|
compileRecordPredicate,
|
||||||
@@ -12,6 +13,7 @@ import {
|
|||||||
searchEntityRecords,
|
searchEntityRecords,
|
||||||
selectRecordFields,
|
selectRecordFields,
|
||||||
} from "../../../domains/datalink/services.js";
|
} from "../../../domains/datalink/services.js";
|
||||||
|
import type { DatalinkRecord } from "../../../domains/datalink/types.js";
|
||||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||||
@@ -32,7 +34,17 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||||
|
|
||||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
const searchFields = splitFields(
|
||||||
|
stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "searchField"])
|
||||||
|
);
|
||||||
|
const rawFilter = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||||
|
let filterBy: string | undefined;
|
||||||
|
if (rawFilter) {
|
||||||
|
filterBy = buildServerFieldFilter(rawFilter, resolved.entity);
|
||||||
|
} else if (keyword) {
|
||||||
|
filterBy = buildKeywordFilter(keyword, { entity: resolved.entity, searchFields });
|
||||||
|
}
|
||||||
|
|
||||||
const whereClause = stringOption(parsed.options, ["where"]);
|
const whereClause = stringOption(parsed.options, ["where"]);
|
||||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||||
@@ -41,7 +53,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||||
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
||||||
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
|
const fetchAll = isAll || Boolean(sumOption || isProfileStats);
|
||||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||||
@@ -125,12 +137,36 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = fetchAll
|
let data: DatalinkRecord[] = [];
|
||||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
let total = 0;
|
||||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
|
||||||
|
|
||||||
let data = page.data;
|
if (fetchAll) {
|
||||||
if (predicate) data = data.filter(predicate);
|
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize });
|
||||||
|
total = page.total;
|
||||||
|
data = page.data;
|
||||||
|
if (predicate) data = data.filter(predicate);
|
||||||
|
} else if (predicate) {
|
||||||
|
// 客户端谓词早退机制:一旦匹配到 count 条记录,立即停止拉取后续页面,杜绝无限制全量扫描
|
||||||
|
let matched = 0;
|
||||||
|
const targetLimit = count ?? 20;
|
||||||
|
for await (const record of iterateAllEntityRecords(
|
||||||
|
resolved.clients.ekbClient,
|
||||||
|
resolved.corpId,
|
||||||
|
resolved.entity.id,
|
||||||
|
{ filterBy, pageSize }
|
||||||
|
)) {
|
||||||
|
total++;
|
||||||
|
if (predicate(record)) {
|
||||||
|
data.push(record);
|
||||||
|
matched++;
|
||||||
|
if (matched >= targetLimit) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const page = await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||||
|
total = page.total;
|
||||||
|
data = page.data;
|
||||||
|
}
|
||||||
|
|
||||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||||
if (sumOption) {
|
if (sumOption) {
|
||||||
@@ -191,7 +227,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
platform: resolved.platform,
|
platform: resolved.platform,
|
||||||
entity: resolved.entity,
|
entity: resolved.entity,
|
||||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
|
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
|
||||||
total: page.total,
|
total: total || data.length,
|
||||||
returned: data.length,
|
returned: data.length,
|
||||||
data,
|
data,
|
||||||
};
|
};
|
||||||
@@ -209,7 +245,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
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 [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||||
});
|
});
|
||||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${total || data.length}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ export async function handleProbeCommand(
|
|||||||
env: currentCorp.env,
|
env: currentCorp.env,
|
||||||
isTest: currentCorp.isTest,
|
isTest: currentCorp.isTest,
|
||||||
staffId: currentCorp.credentials.staffId,
|
staffId: currentCorp.credentials.staffId,
|
||||||
|
staffName: currentCorp.staffName || currentCorp.session?.staffName,
|
||||||
baseUrl: currentCorp.baseUrl,
|
baseUrl: currentCorp.baseUrl,
|
||||||
source: currentCorp.source,
|
source: currentCorp.source,
|
||||||
accountId: currentCorp.accountId,
|
accountId: currentCorp.accountId,
|
||||||
@@ -52,6 +53,35 @@ export async function handleProbeCommand(
|
|||||||
loginStaffId: sessionRes.value?.loginStaffId,
|
loginStaffId: sessionRes.value?.loginStaffId,
|
||||||
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 自愈补全员工姓名 (Self-Healing Profile Hydration)
|
||||||
|
if (!currentCorp.staffName && !currentCorp.session?.staffName) {
|
||||||
|
if (hasOpenApi && currentCorp.credentials.appKey && currentCorp.credentials.appSecurity && currentCorp.credentials.staffId) {
|
||||||
|
try {
|
||||||
|
const { fetchHoseOpenApiAccessToken, fetchHoseStaffDetails } = await import("../../core/auth/openapi-v1.js");
|
||||||
|
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||||
|
baseUrl: currentCorp.baseUrl,
|
||||||
|
appKey: currentCorp.credentials.appKey,
|
||||||
|
appSecurity: currentCorp.credentials.appSecurity,
|
||||||
|
});
|
||||||
|
const details = await fetchHoseStaffDetails(currentCorp.baseUrl || "https://app.ekuaibao.com", openapiToken, [currentCorp.credentials.staffId]);
|
||||||
|
if (details[0]?.name) {
|
||||||
|
currentCorp.staffName = details[0].name;
|
||||||
|
if (!currentCorp.session) {
|
||||||
|
currentCorp.session = { staffName: details[0].name } as any;
|
||||||
|
} else {
|
||||||
|
currentCorp.session.staffName = details[0].name;
|
||||||
|
}
|
||||||
|
if (details[0].cellphone && currentCorp.session) {
|
||||||
|
currentCorp.session.cellphone = details[0].cellphone;
|
||||||
|
}
|
||||||
|
(results.enterprise as any).staffName = details[0].name;
|
||||||
|
const { saveCorpConfig } = await import("../../core/config/loader.js");
|
||||||
|
saveCorpConfig(currentCorp);
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
results.ekbSession = {
|
results.ekbSession = {
|
||||||
status: "error",
|
status: "error",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||||
import * as helpers from "../helpers.js";
|
import * as helpers from "../helpers.js";
|
||||||
|
import * as platformServices from "../../domains/platform/services.js";
|
||||||
import type { CliRuntime } from "../types.js";
|
import type { CliRuntime } from "../types.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
|
|
||||||
@@ -1655,6 +1656,42 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
|||||||
expect(editRes.exitCode).toBe(0);
|
expect(editRes.exitCode).toBe(0);
|
||||||
expect(editRes.stdout).toContain("修改已保存至工作流");
|
expect(editRes.stdout).toContain("修改已保存至工作流");
|
||||||
|
|
||||||
|
// 5.1 node map
|
||||||
|
const mapRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "node",
|
||||||
|
args: ["map", "pipe_node_test", "action_js_1"],
|
||||||
|
options: { yes: true },
|
||||||
|
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", "--yes"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(mapRes.exitCode).toBe(1);
|
||||||
|
expect(mapRes.stderr).toContain("请通过 --mapping-file=<路径> 指定");
|
||||||
|
|
||||||
|
const tmpMappingFile = (await import("os")).tmpdir() + "/test-fields-" + Date.now() + ".json";
|
||||||
|
await (await import("fs/promises")).writeFile(
|
||||||
|
tmpMappingFile,
|
||||||
|
JSON.stringify([{ name: "test_field", label: "测试字段", value: "test_val" }]),
|
||||||
|
"utf-8"
|
||||||
|
);
|
||||||
|
|
||||||
|
const mapSuccessRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "node",
|
||||||
|
args: ["map", "pipe_node_test", "action_js_1"],
|
||||||
|
options: { "mapping-file": tmpMappingFile, yes: true },
|
||||||
|
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", `--mapping-file=${tmpMappingFile}`, "--yes"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(mapSuccessRes.exitCode).toBe(0);
|
||||||
|
expect(mapSuccessRes.stdout).toContain("已批量应用映射");
|
||||||
|
|
||||||
|
await (await import("fs/promises")).unlink(tmpMappingFile).catch(() => {});
|
||||||
|
|
||||||
// 6. node rm
|
// 6. node rm
|
||||||
const rmRes = await handleWorkflowCommand(
|
const rmRes = await handleWorkflowCommand(
|
||||||
{
|
{
|
||||||
@@ -1989,5 +2026,307 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
|||||||
expect(wfEvalRes.stdout).toContain("执行成功 ✅");
|
expect(wfEvalRes.stdout).toContain("执行成功 ✅");
|
||||||
expect(wfEvalRes.stdout).toContain('"total": 100');
|
expect(wfEvalRes.stdout).toContain('"total": 100');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("workflow logs correctly detects and formats running/delayed jobs and in-progress count", async () => {
|
||||||
|
const mockDetail = {
|
||||||
|
id: "pipe_delay_test",
|
||||||
|
pipelineName: "审批延时测试流程",
|
||||||
|
state: 1,
|
||||||
|
tasks: [
|
||||||
|
{ name: "trigger_1", type: "clock", label: "定时触发" },
|
||||||
|
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
|
||||||
|
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockLogs = {
|
||||||
|
executeCount: 3,
|
||||||
|
successCount: 2,
|
||||||
|
errorCount: 0,
|
||||||
|
number: 1,
|
||||||
|
size: 10,
|
||||||
|
totalPages: 1,
|
||||||
|
totalItems: 3,
|
||||||
|
jobList: [
|
||||||
|
{
|
||||||
|
state: 0,
|
||||||
|
jobName: "审批延时测试流程",
|
||||||
|
jobId: "job_running_001",
|
||||||
|
executeTime: "2026-10-21 17:15:00",
|
||||||
|
status: "STARTED",
|
||||||
|
runType: "DEBUG",
|
||||||
|
successTaskCount: 1,
|
||||||
|
errorTaskCount: 0,
|
||||||
|
hasError: "不存在",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
state: 0,
|
||||||
|
jobName: "审批延时测试流程",
|
||||||
|
jobId: "job_completed_002",
|
||||||
|
executeTime: "2026-10-21 17:10:00",
|
||||||
|
status: "COMPLETED",
|
||||||
|
runType: "DEBUG",
|
||||||
|
successTaskCount: 3,
|
||||||
|
errorTaskCount: 0,
|
||||||
|
hasError: "不存在",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockClient = {
|
||||||
|
get: (url: string) => ({
|
||||||
|
json: async () => {
|
||||||
|
if (url.includes("/log")) return { code: 200, data: mockLogs };
|
||||||
|
return { code: 200, data: mockDetail };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
spies.push(
|
||||||
|
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||||
|
ekbClient: mockClient as any,
|
||||||
|
easoClient: mockClient as any,
|
||||||
|
corp: mockCorp,
|
||||||
|
} as any)
|
||||||
|
);
|
||||||
|
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
|
||||||
|
|
||||||
|
// 1. All logs view
|
||||||
|
const allLogsRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "logs",
|
||||||
|
args: ["pipe_delay_test"],
|
||||||
|
options: {},
|
||||||
|
raw: ["workflow", "logs", "pipe_delay_test"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(allLogsRes.exitCode).toBe(0);
|
||||||
|
expect(allLogsRes.stdout).toContain("运行中/延时");
|
||||||
|
expect(allLogsRes.stdout).toContain("1 (正在执行或延时等待中)");
|
||||||
|
expect(allLogsRes.stdout).toContain("⏳ 运行中");
|
||||||
|
expect(allLogsRes.stdout).toContain("✅ 已完成");
|
||||||
|
expect(allLogsRes.stdout).toContain("⏳ 执行中");
|
||||||
|
|
||||||
|
// 2. Client-side filtering by --state=RUNNING
|
||||||
|
const runningOnlyRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "logs",
|
||||||
|
args: ["pipe_delay_test"],
|
||||||
|
options: { state: "RUNNING" },
|
||||||
|
raw: ["workflow", "logs", "pipe_delay_test", "--state=RUNNING"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(runningOnlyRes.exitCode).toBe(0);
|
||||||
|
expect(runningOnlyRes.stdout).toContain("job_running_001");
|
||||||
|
expect(runningOnlyRes.stdout).not.toContain("job_completed_002");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("workflow job correctly displays mid-flight delayed job progress and non-interruptive hints", async () => {
|
||||||
|
const mockDetail = {
|
||||||
|
id: "pipe_delay_test",
|
||||||
|
pipelineName: "审批延时测试流程",
|
||||||
|
state: 1,
|
||||||
|
tasks: [
|
||||||
|
{ name: "trigger_1", type: "clock", label: "定时触发" },
|
||||||
|
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
|
||||||
|
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockRunningJob = {
|
||||||
|
id: "job_running_001",
|
||||||
|
pipelineId: "pipe_delay_test",
|
||||||
|
status: "STARTED",
|
||||||
|
state: 0,
|
||||||
|
startTime: 1792574000000,
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockExecutionTree = [
|
||||||
|
{ id: "exec_1", name: "trigger_1", label: "定时触发", type: "clock", status: "COMPLETED", durationTime: 10 },
|
||||||
|
{ id: "exec_2", name: "action_delay_1", label: "延时等待节点", type: "task-dynamic-delay", status: "STARTED" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockClient = {
|
||||||
|
get: (url: string) => ({
|
||||||
|
json: async () => {
|
||||||
|
if (url.includes("/execution")) return { code: 200, data: mockExecutionTree };
|
||||||
|
if (url.includes("/failed")) return { code: 200, data: { items: [] } };
|
||||||
|
if (url.includes("/jobs/job_running_001")) return { code: 200, data: mockRunningJob };
|
||||||
|
return { code: 200, data: mockDetail };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
spies.push(
|
||||||
|
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||||
|
ekbClient: mockClient as any,
|
||||||
|
easoClient: mockClient as any,
|
||||||
|
corp: mockCorp,
|
||||||
|
} as any)
|
||||||
|
);
|
||||||
|
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
|
||||||
|
|
||||||
|
// 1. Overview view
|
||||||
|
const jobRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "job",
|
||||||
|
args: ["job_running_001"],
|
||||||
|
options: {},
|
||||||
|
raw: ["workflow", "job", "job_running_001"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(jobRes.exitCode).toBe(0);
|
||||||
|
expect(jobRes.stdout).toContain("⏳ 运行中 (STARTED)");
|
||||||
|
expect(jobRes.stdout).toContain("当前正在执行第 2 步(延时等待中或任务处理中)");
|
||||||
|
expect(jobRes.stdout).not.toContain("本次调度在第 2 步中断");
|
||||||
|
expect(jobRes.stdout).toContain("⏳ 延时等待中");
|
||||||
|
|
||||||
|
// 2. Timeline view
|
||||||
|
const timelineRes = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "job",
|
||||||
|
args: ["job_running_001"],
|
||||||
|
options: { timeline: true },
|
||||||
|
raw: ["workflow", "job", "job_running_001", "--timeline"],
|
||||||
|
},
|
||||||
|
mockRuntime
|
||||||
|
);
|
||||||
|
expect(timelineRes.exitCode).toBe(0);
|
||||||
|
expect(timelineRes.stdout).toContain("✅ 已完成");
|
||||||
|
expect(timelineRes.stdout).toContain("⏳ 延时等待中");
|
||||||
|
expect(timelineRes.stdout).toContain("⏳ 等待前序步骤执行完成");
|
||||||
|
expect(timelineRes.stdout).not.toContain("因前序步骤中断");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("CLI - workflow list 轻量化与名称搜索", () => {
|
||||||
|
let spies: ReturnType<typeof spyOn>[] = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const spy of spies) {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
spies = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
const mockWorkflows = [
|
||||||
|
{
|
||||||
|
id: "wf_001",
|
||||||
|
pipelineName: "待摊台账拆分计划",
|
||||||
|
state: 1,
|
||||||
|
runningCount: 0,
|
||||||
|
errorCount: 0,
|
||||||
|
updateTime: "2026-08-26 23:31:04",
|
||||||
|
updateUser: "张三",
|
||||||
|
platformId: "p_1",
|
||||||
|
platformName: "合同台账",
|
||||||
|
tasks: [
|
||||||
|
{ name: "t1", type: "trigger", code: "long script 1..." },
|
||||||
|
{ name: "t2", type: "code", code: "long script 2..." },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "wf_002",
|
||||||
|
pipelineName: "费用报销审批同步",
|
||||||
|
state: 0,
|
||||||
|
runningCount: 0,
|
||||||
|
errorCount: 0,
|
||||||
|
updateTime: "2026-09-01 10:00:00",
|
||||||
|
updateUser: "李四",
|
||||||
|
platformId: "p_2",
|
||||||
|
platformName: "费用应用",
|
||||||
|
tasks: [{ name: "t1", type: "trigger", code: "long script 3..." }],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
it("默认以轻量化模式输出 JSON,剥离庞大的 tasks 数组并提供 nodeCount", async () => {
|
||||||
|
spies.push(
|
||||||
|
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||||
|
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||||
|
workflows: mockWorkflows as any,
|
||||||
|
errors: [],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "list",
|
||||||
|
args: [],
|
||||||
|
options: { json: true },
|
||||||
|
raw: ["workflow", "list", "--json"],
|
||||||
|
},
|
||||||
|
{ ...mockRuntime, jsonMode: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.workflows).toHaveLength(2);
|
||||||
|
expect(data.workflows[0].tasks).toBeUndefined();
|
||||||
|
expect(data.workflows[0].nodeCount).toBe(2);
|
||||||
|
expect(data.workflows[1].nodeCount).toBe(1);
|
||||||
|
expect(data.totalWorkflows).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("传入 --full 或 --with-tasks 时保留完整的 tasks 节点结构", async () => {
|
||||||
|
spies.push(
|
||||||
|
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||||
|
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||||
|
workflows: mockWorkflows as any,
|
||||||
|
errors: [],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "list",
|
||||||
|
args: [],
|
||||||
|
options: { json: true, full: true },
|
||||||
|
raw: ["workflow", "list", "--json", "--full"],
|
||||||
|
},
|
||||||
|
{ ...mockRuntime, jsonMode: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.workflows[0].tasks).toHaveLength(2);
|
||||||
|
expect(data.workflows[0].tasks[0].code).toBe("long script 1...");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("支持通过 --keyword 或 -q 过滤工作流名称", async () => {
|
||||||
|
spies.push(
|
||||||
|
spyOn(helpers, "createClientsForCorp").mockResolvedValue({} as any),
|
||||||
|
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||||
|
workflows: mockWorkflows as any,
|
||||||
|
errors: [],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await handleWorkflowCommand(
|
||||||
|
{
|
||||||
|
area: "workflow",
|
||||||
|
action: "list",
|
||||||
|
args: [],
|
||||||
|
options: { keyword: "待摊", json: true },
|
||||||
|
raw: ["workflow", "list", "--keyword=待摊", "--json"],
|
||||||
|
},
|
||||||
|
{ ...mockRuntime, jsonMode: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.exitCode).toBe(0);
|
||||||
|
const data = JSON.parse(res.stdout);
|
||||||
|
expect(data.workflows).toHaveLength(1);
|
||||||
|
expect(data.workflows[0].id).toBe("wf_001");
|
||||||
|
expect(data.workflows[0].pipelineName).toBe("待摊台账拆分计划");
|
||||||
|
expect(data.totalWorkflows).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { isClientGoodOpened } from "./analyze.js";
|
||||||
|
|
||||||
|
describe("workflow analyze enterprise application status", () => {
|
||||||
|
it("uses the enterprise opening status and ignores marketplace online status", () => {
|
||||||
|
expect(isClientGoodOpened({ status: "OPENED", onLineStatus: "OFFLINE" })).toBe(true);
|
||||||
|
expect(isClientGoodOpened({ status: "EXPIRE", onLineStatus: "ONLINE" })).toBe(false);
|
||||||
|
expect(isClientGoodOpened({ status: "CLOSED", onLineStatus: "ONLINE" })).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,6 +10,10 @@ import { printJson, printTable, printKeyValue } from "../../printer.js";
|
|||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
import { createWorkflowDetailClient } from "./shared.js";
|
import { createWorkflowDetailClient } from "./shared.js";
|
||||||
|
|
||||||
|
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
|
||||||
|
return item.status?.toUpperCase() === "OPENED";
|
||||||
|
}
|
||||||
|
|
||||||
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||||
@@ -44,7 +48,7 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
|
|||||||
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
|
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
|
||||||
const codes = new Set<string>();
|
const codes = new Set<string>();
|
||||||
for (const item of goods) {
|
for (const item of goods) {
|
||||||
const isOpened = item.status?.toUpperCase() === "OPENED" || item.onLineStatus?.toUpperCase() === "ONLINE";
|
const isOpened = isClientGoodOpened(item);
|
||||||
if (isOpened && Array.isArray(item.powers)) {
|
if (isOpened && Array.isArray(item.powers)) {
|
||||||
for (const power of item.powers) {
|
for (const power of item.powers) {
|
||||||
if (typeof power === "string") {
|
if (typeof power === "string") {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
|
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
|
||||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
@@ -33,50 +33,121 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
|||||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||||
state: stringOption(parsed.options, ["state"]),
|
state: stringOption(parsed.options, ["state"]),
|
||||||
page: numberOption(parsed.options, ["page"]),
|
page: numberOption(parsed.options, ["page"]),
|
||||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size", "limit", "count", "n"]),
|
||||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||||
});
|
});
|
||||||
|
const stateOption = stringOption(parsed.options, ["state"]);
|
||||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||||
const isJobError = (job: any): boolean => {
|
const isJobError = (job: any): boolean => {
|
||||||
|
const s = (job.status || "").toUpperCase();
|
||||||
|
if (s === "STARTED" || s === "RUNNING") return false;
|
||||||
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
||||||
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
||||||
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
const filteredJobList = hasErrorFilter
|
|
||||||
? rawResult.jobList.filter(isJobError)
|
|
||||||
: rawResult.jobList;
|
|
||||||
const result = hasErrorFilter
|
|
||||||
? { ...rawResult, jobList: filteredJobList }
|
|
||||||
: rawResult;
|
|
||||||
|
|
||||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
let filteredJobList = rawResult.jobList;
|
||||||
|
if (hasErrorFilter) {
|
||||||
|
filteredJobList = filteredJobList.filter(isJobError);
|
||||||
|
} else if (stateOption) {
|
||||||
|
const norm = stateOption.trim().toUpperCase();
|
||||||
|
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
||||||
|
filteredJobList = filteredJobList.filter(isJobError);
|
||||||
|
} else if (norm === "COMPLETED" || norm === "SUCCESS") {
|
||||||
|
filteredJobList = filteredJobList.filter((j: any) => (j.status || "").toUpperCase() === "COMPLETED" && !isJobError(j));
|
||||||
|
} else if (norm === "RUNNING" || norm === "STARTED" || norm === "IN_PROGRESS") {
|
||||||
|
filteredJobList = filteredJobList.filter((j: any) => {
|
||||||
|
const s = (j.status || "").toUpperCase();
|
||||||
|
return s === "STARTED" || s === "RUNNING";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const inProgressCount = Math.max(
|
||||||
|
0,
|
||||||
|
(rawResult.executeCount ?? 0) - (rawResult.successCount ?? 0) - (rawResult.errorCount ?? 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
...rawResult,
|
||||||
|
jobList: filteredJobList,
|
||||||
|
inProgressCount,
|
||||||
|
};
|
||||||
|
|
||||||
|
let workflowName = rawResult.jobList[0]?.jobName;
|
||||||
|
let workflowState: string | undefined;
|
||||||
|
try {
|
||||||
|
const detail = await getWorkflowDetail(client, pipelineId);
|
||||||
|
if (detail) {
|
||||||
|
workflowName = detail.pipelineName || detail.label || workflowName;
|
||||||
|
workflowState = detail.state === 1 ? "🟢 启用中" : "⚪ 已停用";
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ ...result, workflowName, workflowState }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatRunType = (runType?: string): string => {
|
||||||
|
if (!runType) return "-";
|
||||||
|
const upper = runType.toUpperCase();
|
||||||
|
if (upper === "DEBUG") return "🧪 调试";
|
||||||
|
if (upper === "RUN") return "🏃 运行";
|
||||||
|
return runType;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatJobStatus = (status?: string, state?: unknown): string => {
|
||||||
|
const s = (status || "").toUpperCase();
|
||||||
|
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中";
|
||||||
|
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成";
|
||||||
|
if (s === "FAILED" || s === "ERROR") return "❌ 失败";
|
||||||
|
if (s === "STOP" || s === "STOPPED") return "🛑 终止";
|
||||||
|
if (s === "CANCELLED" || s === "CANCELED") return "🚫 取消";
|
||||||
|
if (!s && (state === 0 || state === "0")) return "COMPLETED";
|
||||||
|
return s || String(state ?? "-");
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatErrorColumn = (job: any): string => {
|
||||||
|
const s = (job.status || "").toUpperCase();
|
||||||
|
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
||||||
|
if (isJobError(job)) return "⚠️ 包含错误";
|
||||||
|
return "正常";
|
||||||
|
};
|
||||||
|
|
||||||
const rows = result.jobList.map((job: any, idx) => [
|
const rows = result.jobList.map((job: any, idx) => [
|
||||||
idx + 1,
|
idx + 1,
|
||||||
job.jobId || job.id || "-",
|
job.jobId || job.id || "-",
|
||||||
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
|
formatRunType(job.runType),
|
||||||
|
formatJobStatus(job.status, job.state),
|
||||||
job.successTaskCount ?? 0,
|
job.successTaskCount ?? 0,
|
||||||
job.errorTaskCount ?? 0,
|
job.errorTaskCount ?? 0,
|
||||||
isJobError(job) ? "⚠️ 包含错误" : "正常",
|
formatErrorColumn(job),
|
||||||
job.durationTime ?? "-",
|
job.durationTime ?? "-",
|
||||||
job.executeTime || job.startTime || "-",
|
job.executeTime || job.startTime || "-",
|
||||||
]);
|
]);
|
||||||
const tableStr = rows.length
|
const tableStr = rows.length
|
||||||
? printTable(
|
? printTable(
|
||||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
["#", "Job ID", "类型 (runType)", "状态 (state)", "成功节点", "失败节点", "有错误", "耗时(ms)", "开始时间"],
|
||||||
rows
|
rows
|
||||||
)
|
)
|
||||||
: "暂无匹配的运行记录";
|
: "暂无匹配的运行记录";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: [
|
stdout: [
|
||||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
`====== 工作流运行日志 [${pipelineId}]${workflowName ? ` · ${workflowName}` : ""}${workflowState ? ` (${workflowState})` : ""} ======`,
|
||||||
printKeyValue({
|
printKeyValue({
|
||||||
|
...(workflowName ? { "工作流名称": workflowName } : {}),
|
||||||
|
...(workflowState ? { "当前状态": workflowState } : {}),
|
||||||
"执行次数": result.executeCount,
|
"执行次数": result.executeCount,
|
||||||
"成功次数": result.successCount,
|
"成功次数": result.successCount,
|
||||||
"错误次数": result.errorCount,
|
"错误次数": result.errorCount,
|
||||||
|
...(result.inProgressCount > 0 ? { "运行中/延时": `${result.inProgressCount} (正在执行或延时等待中)` } : {}),
|
||||||
"日志条数": result.totalItems,
|
"日志条数": result.totalItems,
|
||||||
"当前返回记录": result.jobList.length,
|
"当前返回记录": result.jobList.length,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
getJobExecutionLevel,
|
getJobExecutionLevel,
|
||||||
getJobExecutionTree,
|
getJobExecutionTree,
|
||||||
getJobFailedExecutions,
|
getJobFailedExecutions,
|
||||||
|
getWorkflowDetail,
|
||||||
isTaskExecutionFailed,
|
isTaskExecutionFailed,
|
||||||
listPlatforms,
|
listPlatforms,
|
||||||
explainConditionBranches,
|
explainConditionBranches,
|
||||||
@@ -16,7 +17,7 @@ import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
|||||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
import { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
import { PLATFORM_ID_OPTION_KEYS, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||||
|
|
||||||
async function createJobPiperClient(
|
async function createJobPiperClient(
|
||||||
parsed: CliParsedArgs,
|
parsed: CliParsedArgs,
|
||||||
@@ -119,6 +120,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
|
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
|
||||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||||
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
|
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
|
||||||
|
const isTimeline = booleanOption(parsed.options, ["timeline", "progress", "steps"]);
|
||||||
|
|
||||||
// 1. --logs=<executionId>
|
// 1. --logs=<executionId>
|
||||||
if (logsExecutionId) {
|
if (logsExecutionId) {
|
||||||
@@ -389,7 +391,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
// 4. Default mode: Job overview + top-level tree + failed executions + timeline
|
||||||
const [job, tree, failedPage] = await Promise.all([
|
const [job, tree, failedPage] = await Promise.all([
|
||||||
getJob(client, jobId),
|
getJob(client, jobId),
|
||||||
getJobExecutionTree(client, jobId),
|
getJobExecutionTree(client, jobId),
|
||||||
@@ -401,19 +403,120 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
items: [] as WorkflowTaskExecution[],
|
items: [] as WorkflowTaskExecution[],
|
||||||
})),
|
})),
|
||||||
]);
|
]);
|
||||||
|
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
|
||||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||||
|
|
||||||
const conditionDiagnoses = explainConditionBranches(tree);
|
const conditionDiagnoses = explainConditionBranches(tree);
|
||||||
|
|
||||||
|
const timeline = workflowDetail?.tasks?.map((t: any, idx: number) => {
|
||||||
|
const executed = tree.find((node) => node.name === t.name);
|
||||||
|
let statusText = "⏳ 未执行";
|
||||||
|
let errorDetail = "-";
|
||||||
|
if (executed) {
|
||||||
|
if (executed.status === "COMPLETED") statusText = "✅ 已完成";
|
||||||
|
else if (executed.status === "FAILED") {
|
||||||
|
statusText = "❌ 失败中断";
|
||||||
|
const msg = (executed.error?.message || "执行失败").replace(/\s+/g, " ");
|
||||||
|
errorDetail = msg.length > 100 ? `${msg.slice(0, 97)}...` : msg;
|
||||||
|
} else if (executed.status === "STARTED" || executed.status === "RUNNING") {
|
||||||
|
statusText = t.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 正在执行中";
|
||||||
|
} else {
|
||||||
|
statusText = executed.status;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const runningPrior = tree.find((node) => node.status === "STARTED" || node.status === "RUNNING");
|
||||||
|
const failedPrior = tree.find((node) => node.status === "FAILED");
|
||||||
|
if (runningPrior) {
|
||||||
|
statusText = "⏳ 等待前序步骤执行完成";
|
||||||
|
} else if (failedPrior) {
|
||||||
|
statusText = "⏳ 未执行 (因前序步骤中断)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
index: idx + 1,
|
||||||
|
name: t.name,
|
||||||
|
displayName: t.displayName || t.label || t.name,
|
||||||
|
type: t.type,
|
||||||
|
status: statusText,
|
||||||
|
duration: executed ? String((executed as any).durationTime ?? executed.executionTime ?? "-") : "-",
|
||||||
|
detail: errorDetail,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isTimeline && timeline && timeline.length > 0) {
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson(
|
||||||
|
{
|
||||||
|
jobId,
|
||||||
|
pipelineId: job.pipelineId,
|
||||||
|
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
|
||||||
|
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||||
|
jobStatus: job.state ?? job.status,
|
||||||
|
totalTasks: timeline.length,
|
||||||
|
executedTasks: tree.length,
|
||||||
|
unexecutedTasks: timeline.length - tree.length,
|
||||||
|
timeline,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const timelineRows = timeline.map((it: any) => [
|
||||||
|
it.index,
|
||||||
|
it.name,
|
||||||
|
it.displayName,
|
||||||
|
it.type,
|
||||||
|
it.status,
|
||||||
|
it.duration,
|
||||||
|
it.detail,
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
stdout: [
|
||||||
|
`====== 工作流全链路步骤进度 [${job.id}] ======`,
|
||||||
|
printKeyValue({
|
||||||
|
"Job ID": job.id,
|
||||||
|
"工作流 ID": job.pipelineId,
|
||||||
|
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||||
|
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||||
|
"Job 状态": job.state ?? job.status,
|
||||||
|
"定义总步骤数": timeline.length,
|
||||||
|
"已调度步骤数": tree.length,
|
||||||
|
"未执行步骤数": timeline.length - tree.length,
|
||||||
|
}),
|
||||||
|
"",
|
||||||
|
printTable(
|
||||||
|
["#", "节点标识", "步骤名称", "类型", "执行状态", "耗时(ms)", "详细说明"],
|
||||||
|
timelineRows
|
||||||
|
),
|
||||||
|
"",
|
||||||
|
].join("\n"),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson(
|
stdout: printJson(
|
||||||
{
|
{
|
||||||
jobId,
|
jobId,
|
||||||
job,
|
job,
|
||||||
|
workflow: workflowDetail
|
||||||
|
? {
|
||||||
|
id: workflowDetail.id,
|
||||||
|
name: workflowDetail.pipelineName || workflowDetail.label,
|
||||||
|
state: workflowDetail.state,
|
||||||
|
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||||
|
totalTasks: workflowDetail.tasks?.length ?? tree.length,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
executionTree: tree,
|
executionTree: tree,
|
||||||
failedExecutions,
|
failedExecutions,
|
||||||
conditionDiagnoses,
|
conditionDiagnoses,
|
||||||
|
timeline,
|
||||||
},
|
},
|
||||||
runtime.outputOptions
|
runtime.outputOptions
|
||||||
),
|
),
|
||||||
@@ -422,16 +525,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const treeRows = tree.map((node, idx) => [
|
const formatJobStatusLabel = (status?: string, state?: unknown): string => {
|
||||||
idx + 1,
|
const s = (status || "").toUpperCase();
|
||||||
node.id,
|
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中 (STARTED)";
|
||||||
node.name || "-",
|
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成 (COMPLETED)";
|
||||||
node.label || node.displayName || "-",
|
if (s === "FAILED" || s === "ERROR") return "❌ 失败 (FAILED)";
|
||||||
node.type || "-",
|
if (s === "STOP" || s === "STOPPED") return "🛑 终止 (STOPPED)";
|
||||||
node.status || "-",
|
if (s === "CANCELLED" || s === "CANCELED") return "🚫 已取消";
|
||||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
return s || String(state ?? "-");
|
||||||
node.error?.message || "-",
|
};
|
||||||
]);
|
|
||||||
|
const treeRows = tree.map((node, idx) => {
|
||||||
|
const isRunning = node.status === "STARTED" || node.status === "RUNNING";
|
||||||
|
const statusLabel = isRunning
|
||||||
|
? (node.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 运行中")
|
||||||
|
: node.status || "-";
|
||||||
|
return [
|
||||||
|
idx + 1,
|
||||||
|
node.id,
|
||||||
|
node.name || "-",
|
||||||
|
node.label || node.displayName || "-",
|
||||||
|
node.type || "-",
|
||||||
|
statusLabel,
|
||||||
|
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||||
|
node.error?.message || "-",
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
const failedRows = failedExecutions.map((item, idx) => [
|
const failedRows = failedExecutions.map((item, idx) => [
|
||||||
idx + 1,
|
idx + 1,
|
||||||
@@ -444,18 +563,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
item.error?.message || "-",
|
item.error?.message || "-",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const hasUnexecuted = workflowDetail && workflowDetail.tasks && workflowDetail.tasks.length > tree.length;
|
||||||
|
const isJobRunning = (job.status || "").toUpperCase() === "STARTED" || (job.status || "").toUpperCase() === "RUNNING";
|
||||||
const outLines = [
|
const outLines = [
|
||||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||||
printKeyValue({
|
printKeyValue({
|
||||||
"Job ID": job.id,
|
"Job ID": job.id,
|
||||||
"工作流 ID (pipelineId)": job.pipelineId,
|
"工作流 ID (pipelineId)": job.pipelineId,
|
||||||
"Job 状态 (state)": job.state ?? job.status,
|
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||||
|
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||||
|
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
|
||||||
"开始时间": job.startTime || "-",
|
"开始时间": job.startTime || "-",
|
||||||
"结束时间": job.endTime || "-",
|
"结束时间": job.endTime || "-",
|
||||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||||
"顶层节点数": tree.length,
|
"定义总步骤数": workflowDetail?.tasks?.length ?? tree.length,
|
||||||
|
"已调度节点数": tree.length,
|
||||||
|
...(hasUnexecuted ? { "未执行步骤数": workflowDetail.tasks.length - tree.length } : {}),
|
||||||
"异常/跳过节点数": failedExecutions.length,
|
"异常/跳过节点数": failedExecutions.length,
|
||||||
}),
|
}),
|
||||||
|
...(hasUnexecuted
|
||||||
|
? [
|
||||||
|
"",
|
||||||
|
isJobRunning
|
||||||
|
? `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,当前正在执行第 ${tree.length} 步(延时等待中或任务处理中),后续 ${workflowDetail.tasks.length - tree.length} 个步骤尚未调度。运行 'hose-use workflow job ${job.id} --timeline' 可查看实时节点进度。`
|
||||||
|
: `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,本次调度在第 ${tree.length} 步中断,后续 ${workflowDetail.tasks.length - tree.length} 个步骤未执行。运行 'hose-use workflow job ${job.id} --timeline' 查看全链路步骤时间线。`,
|
||||||
|
]
|
||||||
|
: []),
|
||||||
"",
|
"",
|
||||||
"── 顶层节点执行树 ──",
|
"── 顶层节点执行树 ──",
|
||||||
treeRows.length
|
treeRows.length
|
||||||
@@ -496,6 +629,11 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const codeSummaries = extractCodeNodeSummaries(tree, flattenExecutionTree);
|
||||||
|
if (codeSummaries.length > 0) {
|
||||||
|
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, job.id));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `${outLines.join("\n")}\n`,
|
stdout: `${outLines.join("\n")}\n`,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
|
|||||||
@@ -14,36 +14,62 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
|||||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||||
|
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||||
|
const isFull = booleanOption(parsed.options, ["full", "with-tasks", "withTasks"], false);
|
||||||
|
|
||||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||||
const workflows = filterPlatformId
|
let workflows = filterPlatformId
|
||||||
? rawResult.workflows.filter(
|
? rawResult.workflows.filter(
|
||||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||||
)
|
)
|
||||||
: rawResult.workflows;
|
: rawResult.workflows;
|
||||||
const result = filterPlatformId
|
|
||||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
if (keyword) {
|
||||||
: rawResult;
|
const kw = keyword.toLowerCase();
|
||||||
|
workflows = workflows.filter(
|
||||||
|
(wf) =>
|
||||||
|
wf.pipelineName.toLowerCase().includes(kw) ||
|
||||||
|
wf.id.toLowerCase().includes(kw) ||
|
||||||
|
Boolean(wf.platformName && wf.platformName.toLowerCase().includes(kw))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认轻量化模式:列表态剥离庞大的 tasks 节点树与代码脚本,只输出核心元数据和节点数统计
|
||||||
|
const outputWorkflows = isFull
|
||||||
|
? workflows
|
||||||
|
: workflows.map(({ tasks, ...rest }) => ({
|
||||||
|
...rest,
|
||||||
|
nodeCount: tasks?.length ?? 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
...rawResult,
|
||||||
|
workflows: outputWorkflows,
|
||||||
|
totalWorkflows: workflows.length,
|
||||||
|
};
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.workflows.length === 0) {
|
if (workflows.length === 0) {
|
||||||
|
const emptyMsg = keyword
|
||||||
|
? `企业 [${runtime.selectedCorp!.name}] 下未找到包含关键词 "${keyword}" 的工作流\n`
|
||||||
|
: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`;
|
||||||
return {
|
return {
|
||||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
stdout: emptyMsg,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const rows = result.workflows.map((wf, i) => [
|
const rows = workflows.map((wf, i) => [
|
||||||
i + 1,
|
i + 1,
|
||||||
wf.id,
|
wf.id,
|
||||||
wf.pipelineName,
|
wf.pipelineName,
|
||||||
wf.platformName || wf.platformId || "-",
|
wf.platformName || wf.platformId || "-",
|
||||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||||
wf.tasks?.length ?? "-",
|
wf.tasks?.length ?? (wf as any).nodeCount ?? "-",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const table = printTable(
|
const table = printTable(
|
||||||
@@ -51,8 +77,15 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
|||||||
rows
|
rows
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const filterDesc = [
|
||||||
|
filterPlatformId ? `应用: ${filterPlatformId}` : "",
|
||||||
|
keyword ? `关键词: "${keyword}"` : "",
|
||||||
|
].filter(Boolean).join(", ");
|
||||||
|
|
||||||
|
const titleSuffix = filterDesc ? ` (过滤: ${filterDesc}, 共 ${workflows.length} 条)` : ` (共 ${workflows.length} 条)`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
addWorkflowTask,
|
addWorkflowTask,
|
||||||
editWorkflowTask,
|
editWorkflowTask,
|
||||||
removeWorkflowTask,
|
removeWorkflowTask,
|
||||||
|
applyNodeMapping,
|
||||||
getWorkflowAvailableNodes,
|
getWorkflowAvailableNodes,
|
||||||
grantWorkflowNodes,
|
grantWorkflowNodes,
|
||||||
} from "../../../domains/platform/services.js";
|
} from "../../../domains/platform/services.js";
|
||||||
@@ -20,7 +21,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
|||||||
import { createPiperClientForCorp } from "../../helpers.js";
|
import { createPiperClientForCorp } from "../../helpers.js";
|
||||||
import { createWorkflowDetailClient } from "./shared.js";
|
import { createWorkflowDetailClient } from "./shared.js";
|
||||||
|
|
||||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||||
|
|
||||||
export async function handleNodeCommand(
|
export async function handleNodeCommand(
|
||||||
@@ -78,6 +79,7 @@ export async function handleNodeCommand(
|
|||||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||||
|
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||||
"",
|
"",
|
||||||
"子命令 (企业灰度节点级别):",
|
"子命令 (企业灰度节点级别):",
|
||||||
@@ -110,6 +112,8 @@ export async function handleNodeCommand(
|
|||||||
case "update":
|
case "update":
|
||||||
case "set":
|
case "set":
|
||||||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||||||
|
case "map":
|
||||||
|
return handleMapNode(pipelineId, nodeTarget, parsed, runtime);
|
||||||
case "rm":
|
case "rm":
|
||||||
case "remove":
|
case "remove":
|
||||||
case "delete":
|
case "delete":
|
||||||
@@ -248,7 +252,17 @@ async function handleAddNode(
|
|||||||
stderr: [
|
stderr: [
|
||||||
"请指定新增节点类型: --type=<类型>",
|
"请指定新增节点类型: --type=<类型>",
|
||||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
|
"",
|
||||||
|
"常用选项:",
|
||||||
|
" --type=<type> 节点类型 (如 code-js2 / code)",
|
||||||
|
" --label=<标题> 节点显示名称",
|
||||||
|
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||||||
|
" --code=<代码片段> 传入代码字符串(仅限简短代码)",
|
||||||
|
" --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||||||
|
" --after=<前置节点name> 插入指定节点之后",
|
||||||
|
" --yes 确认追加",
|
||||||
|
"",
|
||||||
|
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||||
].join("\n") + "\n",
|
].join("\n") + "\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
@@ -329,7 +343,21 @@ async function handleEditNode(
|
|||||||
if (!nodeTarget) {
|
if (!nodeTarget) {
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
|
stderr: [
|
||||||
|
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||||
|
"",
|
||||||
|
"常用选项:",
|
||||||
|
" --label=<新名称> 更新节点显示标题",
|
||||||
|
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||||||
|
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||||||
|
" --desc=<描述> 更新节点描述",
|
||||||
|
" --set='key=value' 定向修改节点自定义属性",
|
||||||
|
" --dry-run 只预览变更",
|
||||||
|
" --yes 确认保存修改",
|
||||||
|
"",
|
||||||
|
"示例:",
|
||||||
|
" hose-use workflow node edit 900682164608835609 action_cdd6fv --code-file=./clean.mvel --yes",
|
||||||
|
].join("\n") + "\n",
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -359,6 +387,14 @@ async function handleEditNode(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||||
|
if (mappingFile) {
|
||||||
|
const fs = await import("fs/promises");
|
||||||
|
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||||||
|
const mappingData = JSON.parse(rawContent);
|
||||||
|
return handleMapNode(pipelineId, nodeTarget, parsed, runtime, mappingData);
|
||||||
|
}
|
||||||
|
|
||||||
requireMutationConfirmation(
|
requireMutationConfirmation(
|
||||||
parsed,
|
parsed,
|
||||||
runtime,
|
runtime,
|
||||||
@@ -384,7 +420,7 @@ async function handleEditNode(
|
|||||||
updatedFields: {
|
updatedFields: {
|
||||||
...(label ? { label } : {}),
|
...(label ? { label } : {}),
|
||||||
...(desc ? { desc } : {}),
|
...(desc ? { desc } : {}),
|
||||||
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
|
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||||
...customSet,
|
...customSet,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -400,8 +436,103 @@ async function handleEditNode(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let codeTip = "";
|
||||||
|
if (!codeFile && code && code.length > 300) {
|
||||||
|
codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
|
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleMapNode(
|
||||||
|
pipelineId: string,
|
||||||
|
nodeTarget: string,
|
||||||
|
parsed: CliParsedArgs,
|
||||||
|
runtime: CliRuntime,
|
||||||
|
injectedMappingData?: any
|
||||||
|
): Promise<CliResult> {
|
||||||
|
if (!nodeTarget) {
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: [
|
||||||
|
"请提供目标节点标识 (name 或层级序号): hose-use workflow node map <pipelineId> <nodeNameOrIndex> --mapping-file=<path> [选项]",
|
||||||
|
"",
|
||||||
|
"常用选项:",
|
||||||
|
" --mapping-file=<路径> 包含字段映射的本地 JSON 文件 (可为字段数组或属性对象)",
|
||||||
|
" --dry-run 只预览变更",
|
||||||
|
" --yes 确认保存修改",
|
||||||
|
"",
|
||||||
|
"示例:",
|
||||||
|
" hose-use workflow node map 900682164608835609 action_datalink_create --mapping-file=./fields.json --yes",
|
||||||
|
].join("\n") + "\n",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let mappingData = injectedMappingData;
|
||||||
|
if (!mappingData) {
|
||||||
|
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||||
|
if (!mappingFile) {
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: "错误: 请通过 --mapping-file=<路径> 指定本地字段映射 JSON 文件\n",
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const fs = await import("fs/promises");
|
||||||
|
try {
|
||||||
|
const content = await fs.readFile(mappingFile, "utf-8");
|
||||||
|
mappingData = JSON.parse(content);
|
||||||
|
} catch (e: any) {
|
||||||
|
return {
|
||||||
|
stdout: "",
|
||||||
|
stderr: `错误: 读取或解析映射文件失败: ${e.message}\n`,
|
||||||
|
exitCode: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
requireMutationConfirmation(
|
||||||
|
parsed,
|
||||||
|
runtime,
|
||||||
|
"批量映射工作流节点配置",
|
||||||
|
`hose-use workflow node map ${pipelineId} ${nodeTarget} --yes`
|
||||||
|
);
|
||||||
|
|
||||||
|
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||||
|
const detail = await getWorkflowDetail(client, pipelineId);
|
||||||
|
|
||||||
|
const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData);
|
||||||
|
|
||||||
|
if (isDryRun(parsed, runtime)) {
|
||||||
|
return mutationPreview(parsed, runtime, "批量映射工作流节点配置", `${pipelineId}:${editedTask.name}`, {
|
||||||
|
pipelineId,
|
||||||
|
nodeName: editedTask.name,
|
||||||
|
label: editedTask.label,
|
||||||
|
nodeType: editedTask.type,
|
||||||
|
changedKeys,
|
||||||
|
mappingSummary: Array.isArray(mappingData)
|
||||||
|
? `数组格式更新 (${mappingData.length} 项)`
|
||||||
|
: `对象属性更新 (${Object.keys(mappingData).join(", ")})`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return {
|
||||||
|
stdout: printJson({ success: true, pipelineId, editedTask, changedKeys, workflow: saveResult }, runtime.outputOptions),
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n`,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
lintJavaScriptCode,
|
lintJavaScriptCode,
|
||||||
lintMvelCode,
|
lintMvelCode,
|
||||||
executeJavaScriptSandbox,
|
executeJavaScriptSandbox,
|
||||||
|
executeMvelSandbox,
|
||||||
} from "../../../domains/platform/services.js";
|
} from "../../../domains/platform/services.js";
|
||||||
import { stringOption, booleanOption } from "../../parser.js";
|
import { stringOption, booleanOption } from "../../parser.js";
|
||||||
import { printJson, printKeyValue } from "../../printer.js";
|
import { printJson, printKeyValue } from "../../printer.js";
|
||||||
@@ -196,6 +197,8 @@ export async function handleWorkflowEvalScript(
|
|||||||
const codeInline = stringOption(parsed.options, ["code"]);
|
const codeInline = stringOption(parsed.options, ["code"]);
|
||||||
const timeoutStr = stringOption(parsed.options, ["timeout"]);
|
const timeoutStr = stringOption(parsed.options, ["timeout"]);
|
||||||
const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000;
|
const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000;
|
||||||
|
const explicitType = (stringOption(parsed.options, ["type"]) || "").toLowerCase();
|
||||||
|
const isMvel = explicitType === "code" || explicitType === "mvel" || (filePath ? filePath.endsWith(".mvel") : false);
|
||||||
|
|
||||||
// 1. 获取输入参数 inputs
|
// 1. 获取输入参数 inputs
|
||||||
let inputs: Record<string, unknown> = {};
|
let inputs: Record<string, unknown> = {};
|
||||||
@@ -245,7 +248,9 @@ export async function handleWorkflowEvalScript(
|
|||||||
code = fs.readFileSync(filePath, "utf-8");
|
code = fs.readFileSync(filePath, "utf-8");
|
||||||
}
|
}
|
||||||
|
|
||||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
const evalResult = isMvel
|
||||||
|
? await executeMvelSandbox(code, inputs, { timeoutMs })
|
||||||
|
: await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||||
|
|
||||||
if (isJson) {
|
if (isJson) {
|
||||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||||
@@ -296,18 +301,7 @@ export async function handleWorkflowEvalScript(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const task = located.task;
|
const task = located.task;
|
||||||
if (task.type !== "code-js2") {
|
if (task.type !== "code-js2" && task.type !== "code") {
|
||||||
if (task.type === "code") {
|
|
||||||
return {
|
|
||||||
stdout: "",
|
|
||||||
stderr: [
|
|
||||||
`节点 [${task.name}] 是 MVEL (code) 节点。`,
|
|
||||||
"当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。",
|
|
||||||
"提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。",
|
|
||||||
].join("\n") + "\n",
|
|
||||||
exitCode: 1,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
|
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
|
||||||
@@ -316,6 +310,7 @@ export async function handleWorkflowEvalScript(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const code: string = (task as any).code || "";
|
const code: string = (task as any).code || "";
|
||||||
|
const isNodeMvel = task.type === "code";
|
||||||
|
|
||||||
// 如果没有显式传 input,尝试提取工作流样本数据
|
// 如果没有显式传 input,尝试提取工作流样本数据
|
||||||
if (Object.keys(inputs).length === 0) {
|
if (Object.keys(inputs).length === 0) {
|
||||||
@@ -352,7 +347,9 @@ export async function handleWorkflowEvalScript(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
const evalResult = isNodeMvel
|
||||||
|
? await executeMvelSandbox(code, inputs, { timeoutMs })
|
||||||
|
: await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||||
|
|
||||||
if (isJson) {
|
if (isJson) {
|
||||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { stringOption } from "../../parser.js";
|
|||||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||||
|
|
||||||
export const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"];
|
||||||
|
|
||||||
export async function createWorkflowDetailClient(
|
export async function createWorkflowDetailClient(
|
||||||
parsed: CliParsedArgs,
|
parsed: CliParsedArgs,
|
||||||
@@ -56,3 +56,105 @@ export async function createJobPiperClient(
|
|||||||
}
|
}
|
||||||
return clients.easoClient;
|
return clients.easoClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CodeNodeSummary {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
type: string;
|
||||||
|
status: string;
|
||||||
|
rawOutput: unknown;
|
||||||
|
summaryLines: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function extractCodeNodeSummaries(
|
||||||
|
nodes: Array<any>,
|
||||||
|
flattenExecutionTreeFn?: (nodes: any[]) => any[]
|
||||||
|
): CodeNodeSummary[] {
|
||||||
|
const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes;
|
||||||
|
const summaries: CodeNodeSummary[] = [];
|
||||||
|
|
||||||
|
for (const node of flattened) {
|
||||||
|
if (!node) continue;
|
||||||
|
const type = String(node.type || "");
|
||||||
|
if (type !== "code" && type !== "code-js2") continue;
|
||||||
|
|
||||||
|
const rawOutput = node.output ?? node.outputs ?? node.details;
|
||||||
|
const summaryLines: string[] = [];
|
||||||
|
|
||||||
|
if (rawOutput === undefined || rawOutput === null) {
|
||||||
|
summaryLines.push(" 出参: (无返回值或 null)");
|
||||||
|
} else if (Array.isArray(rawOutput)) {
|
||||||
|
summaryLines.push(` 出参类型: Array (${rawOutput.length} 项)`);
|
||||||
|
if (rawOutput.length > 0) {
|
||||||
|
const first = rawOutput[0];
|
||||||
|
if (first && typeof first === "object") {
|
||||||
|
const keys = ["planCode", "code", "id", "name", "title", "totalAmount", "amount"];
|
||||||
|
const matchedKey = keys.find((k) => (first as Record<string, unknown>)[k] !== undefined);
|
||||||
|
if (matchedKey) {
|
||||||
|
summaryLines.push(` 首项 ${matchedKey}: ${String((first as Record<string, unknown>)[matchedKey])}`);
|
||||||
|
}
|
||||||
|
if ((first as any).amount !== undefined && matchedKey !== "amount") {
|
||||||
|
summaryLines.push(` 首项金额: ${String((first as any).amount)}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
summaryLines.push(` 首项值: ${String(first)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (typeof rawOutput === "object") {
|
||||||
|
const obj = rawOutput as Record<string, unknown>;
|
||||||
|
summaryLines.push(" 出参类型: Object");
|
||||||
|
if (Array.isArray(obj.items)) {
|
||||||
|
summaryLines.push(` items.length: ${obj.items.length}`);
|
||||||
|
}
|
||||||
|
for (const k of ["planCode", "totalAmount", "count", "code", "total", "amount", "success"]) {
|
||||||
|
if (obj[k] !== undefined) {
|
||||||
|
summaryLines.push(` ${k}: ${String(obj[k])}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const allKeys = Object.keys(obj);
|
||||||
|
if (summaryLines.length === 1 && allKeys.length > 0) {
|
||||||
|
summaryLines.push(` 字段列表 (${allKeys.length} 个): ${allKeys.slice(0, 5).join(", ")}${allKeys.length > 5 ? "..." : ""}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
summaryLines.push(` 出参值: ${String(rawOutput)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
summaries.push({
|
||||||
|
id: node.id || "-",
|
||||||
|
name: node.name || "-",
|
||||||
|
label: node.label || node.displayName || (type === "code" ? "MVEL代码节点" : "JS代码节点"),
|
||||||
|
type,
|
||||||
|
status: node.status || "UNKNOWN",
|
||||||
|
rawOutput,
|
||||||
|
summaryLines,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return summaries;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCodeNodeSummariesCard(
|
||||||
|
summaries: CodeNodeSummary[],
|
||||||
|
jobId?: string
|
||||||
|
): string[] {
|
||||||
|
if (summaries.length === 0) return [];
|
||||||
|
|
||||||
|
const lines: string[] = [
|
||||||
|
"",
|
||||||
|
"── 🧮 核心代码节点出参即时摘要 (Code Return Values) ──",
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const s of summaries) {
|
||||||
|
const statusIcon = s.status === "COMPLETED" || s.status === "SUCCESS" ? "✅" : s.status === "FAILED" ? "❌" : "⏳";
|
||||||
|
lines.push(` ${statusIcon} [${s.name}] ${s.label} (${s.type}, 状态: ${s.status})`);
|
||||||
|
for (const l of s.summaryLines) {
|
||||||
|
lines.push(` ${l}`);
|
||||||
|
}
|
||||||
|
if (jobId) {
|
||||||
|
lines.push(` ↳ 完整出参查看: hose-use workflow job ${jobId} --node=${s.name} --full`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
||||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||||
import { createWorkflowDetailClient } from "./shared.js";
|
import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||||
|
|
||||||
export async function handleWorkflowTest(
|
export async function handleWorkflowTest(
|
||||||
@@ -58,9 +58,28 @@ export async function handleWorkflowTest(
|
|||||||
if (isProductionCorp) {
|
if (isProductionCorp) {
|
||||||
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
|
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
|
||||||
}
|
}
|
||||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
|
const nextActionCmd = isProductionCorp
|
||||||
|
? `hose-use workflow test ${pipelineId} --yes --force`
|
||||||
|
: `hose-use workflow test ${pipelineId} --yes`;
|
||||||
|
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
|
||||||
if (isDryRun(parsed, runtime)) {
|
if (isDryRun(parsed, runtime)) {
|
||||||
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||||
|
if (isProductionCorp) {
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
try {
|
||||||
|
const parsedJson = JSON.parse(previewResult.stdout);
|
||||||
|
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
|
||||||
|
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
|
||||||
|
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return previewResult;
|
||||||
}
|
}
|
||||||
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
||||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||||
@@ -88,9 +107,39 @@ export async function handleWorkflowTest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "WEBHOOK": {
|
case "WEBHOOK": {
|
||||||
// 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty
|
// 分支 B: Webhook / 外部事件触发器 ── 支持 flow/bill / sample / body / file / empty
|
||||||
targetId = "";
|
targetId = "";
|
||||||
if (rawBody) {
|
if (flowCodeOrId && !rawBody && !filePath) {
|
||||||
|
try {
|
||||||
|
const { getBillByCodeOrId } = await import("../../../domains/bill/tools.js");
|
||||||
|
const { createSessionClient } = await import("../../../core/http/index.js");
|
||||||
|
const sessionClient = await createSessionClient(runtime.selectedCorp!);
|
||||||
|
const corpId = runtime.selectedCorp?.corpId || runtime.selectedCorp?.id || "";
|
||||||
|
const bills = await getBillByCodeOrId(sessionClient, corpId, flowCodeOrId);
|
||||||
|
const bill = bills[0];
|
||||||
|
if (bill) {
|
||||||
|
customPayload = {
|
||||||
|
code: bill.billCode,
|
||||||
|
flowId: bill.billId,
|
||||||
|
title: bill.title,
|
||||||
|
data: bill,
|
||||||
|
corporationId: corpId,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
customPayload = {
|
||||||
|
code: flowCodeOrId,
|
||||||
|
flowId: flowCodeOrId,
|
||||||
|
corporationId: corpId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
customPayload = {
|
||||||
|
code: flowCodeOrId,
|
||||||
|
flowId: flowCodeOrId,
|
||||||
|
corporationId: runtime.selectedCorp?.corpId || runtime.selectedCorp?.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (rawBody) {
|
||||||
try {
|
try {
|
||||||
customPayload = JSON.parse(rawBody);
|
customPayload = JSON.parse(rawBody);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -435,6 +484,11 @@ export async function handleWorkflowTest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const codeSummaries = extractCodeNodeSummaries(report.executionTree);
|
||||||
|
if (codeSummaries.length > 0) {
|
||||||
|
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stdout: `${outLines.join("\n")}\n`,
|
stdout: `${outLines.join("\n")}\n`,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
|
|||||||
@@ -50,7 +50,9 @@ export const CorpSessionInfoSchema = z.object({
|
|||||||
roles: z.array(z.string()).nullable().optional().describe("员工角色清单"),
|
roles: z.array(z.string()).nullable().optional().describe("员工角色清单"),
|
||||||
roleTitles: z.string().nullable().optional().describe("高管/高级角色头衔"),
|
roleTitles: z.string().nullable().optional().describe("高管/高级角色头衔"),
|
||||||
isSeniorExecutive: z.boolean().nullable().optional().describe("是否包含高管/高级审批角色"),
|
isSeniorExecutive: z.boolean().nullable().optional().describe("是否包含高管/高级审批角色"),
|
||||||
riskLevel: z.string().nullable().optional().describe("身份风控等级 (HIGH/MEDIUM/NORMAL)"),
|
identityComplete: z.boolean().optional().describe("身份画像查询是否完整"),
|
||||||
|
identityUnavailableFields: z.array(z.string()).optional().describe("身份画像未能确认的信息"),
|
||||||
|
riskLevel: z.string().nullable().optional().describe("身份风控等级 (HIGH/MEDIUM/NORMAL/UNKNOWN)"),
|
||||||
permissions: z.array(z.string()).nullable().optional().describe("员工功能权限清单"),
|
permissions: z.array(z.string()).nullable().optional().describe("员工功能权限清单"),
|
||||||
});
|
});
|
||||||
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||||
|
|||||||
@@ -118,11 +118,17 @@ export async function getScriptEngineClient(
|
|||||||
const cachedHoseToken = mem.hoseToken;
|
const cachedHoseToken = mem.hoseToken;
|
||||||
return createAuthClient({
|
return createAuthClient({
|
||||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||||
getHeaders: () => ({
|
getHeaders: () => {
|
||||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
const headers: Record<string, string> = {
|
||||||
platformid: platformId,
|
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
|
||||||
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
|
platformid: platformId,
|
||||||
}),
|
};
|
||||||
|
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
||||||
|
if (currentHoseToken) {
|
||||||
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
@@ -144,11 +150,17 @@ export async function getScriptEngineClient(
|
|||||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||||
|
|
||||||
// 重新换取
|
// 重新换取
|
||||||
const hoseToken = await fetchHoseToken(
|
let hoseToken = "";
|
||||||
corp.credentials.accessToken,
|
try {
|
||||||
corpId,
|
hoseToken = await fetchHoseToken(
|
||||||
environment
|
corp.credentials.accessToken,
|
||||||
);
|
corpId,
|
||||||
|
environment
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
||||||
|
// 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建
|
||||||
|
}
|
||||||
const easoJwt = await fetchEasoJwt(
|
const easoJwt = await fetchEasoJwt(
|
||||||
corp.credentials.accessToken,
|
corp.credentials.accessToken,
|
||||||
corpId,
|
corpId,
|
||||||
@@ -179,11 +191,17 @@ export async function getScriptEngineClient(
|
|||||||
|
|
||||||
return createAuthClient({
|
return createAuthClient({
|
||||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||||
getHeaders: () => ({
|
getHeaders: () => {
|
||||||
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
const headers: Record<string, string> = {
|
||||||
platformid: platformId,
|
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
|
||||||
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
|
platformid: platformId,
|
||||||
}),
|
};
|
||||||
|
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
||||||
|
if (currentHoseToken) {
|
||||||
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
|
|||||||
@@ -107,15 +107,18 @@ export async function fetchUnityJwt(
|
|||||||
export async function fetchEasoRealmToken(
|
export async function fetchEasoRealmToken(
|
||||||
corpId: string,
|
corpId: string,
|
||||||
unityJwt: string,
|
unityJwt: string,
|
||||||
hoseToken: string
|
hoseToken?: string
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
Authorization: `Bearer ${unityJwt}`,
|
||||||
|
};
|
||||||
|
if (hoseToken) {
|
||||||
|
headers.hoseaccesstoken = hoseToken;
|
||||||
|
}
|
||||||
const response = await ky
|
const response = await ky
|
||||||
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
|
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
|
||||||
searchParams: { corpId },
|
searchParams: { corpId },
|
||||||
headers: {
|
headers,
|
||||||
Authorization: `Bearer ${unityJwt}`,
|
|
||||||
hoseaccesstoken: hoseToken,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
.json<{ value?: { accessToken?: string } }>();
|
.json<{ value?: { accessToken?: string } }>();
|
||||||
const token = response.value?.accessToken;
|
const token = response.value?.accessToken;
|
||||||
@@ -185,12 +188,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
|||||||
return {
|
return {
|
||||||
client: createAuthClient({
|
client: createAuthClient({
|
||||||
prefixUrl: EASO_BASE_URL,
|
prefixUrl: EASO_BASE_URL,
|
||||||
getHeaders: () => ({
|
getHeaders: () => {
|
||||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
|
const headers: Record<string, string> = {
|
||||||
accesstoken: corp.credentials.accessToken,
|
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
|
||||||
corporationid: corpId,
|
accesstoken: corp.credentials.accessToken,
|
||||||
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
|
corporationid: corpId,
|
||||||
}),
|
};
|
||||||
|
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
|
||||||
|
if (currentHoseToken) {
|
||||||
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateEasoCache(corp.id);
|
invalidateEasoCache(corp.id);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
@@ -212,11 +221,17 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
|||||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||||
|
|
||||||
// 重新换取
|
// 重新换取
|
||||||
const hoseToken = await fetchHoseToken(
|
let hoseToken = "";
|
||||||
corp.credentials.accessToken,
|
try {
|
||||||
corpId,
|
hoseToken = await fetchHoseToken(
|
||||||
environment
|
corp.credentials.accessToken,
|
||||||
);
|
corpId,
|
||||||
|
environment
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
|
||||||
|
// 但 EASO Realm 换票仅依赖 Unity JWT 即可完成鉴权,此处降级兼容以避免阻断
|
||||||
|
}
|
||||||
const unityJwt = await fetchUnityJwt(
|
const unityJwt = await fetchUnityJwt(
|
||||||
corp.credentials.accessToken,
|
corp.credentials.accessToken,
|
||||||
corpId,
|
corpId,
|
||||||
@@ -226,7 +241,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
|||||||
const easoToken = await fetchEasoRealmToken(
|
const easoToken = await fetchEasoRealmToken(
|
||||||
corpId,
|
corpId,
|
||||||
unityJwt,
|
unityJwt,
|
||||||
hoseToken
|
hoseToken || undefined
|
||||||
);
|
);
|
||||||
|
|
||||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||||
@@ -265,12 +280,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
|||||||
return {
|
return {
|
||||||
client: createAuthClient({
|
client: createAuthClient({
|
||||||
prefixUrl: EASO_BASE_URL,
|
prefixUrl: EASO_BASE_URL,
|
||||||
getHeaders: () => ({
|
getHeaders: () => {
|
||||||
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
|
const headers: Record<string, string> = {
|
||||||
accesstoken: corp.credentials.accessToken,
|
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
|
||||||
corporationid: corpId,
|
accesstoken: corp.credentials.accessToken,
|
||||||
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
|
corporationid: corpId,
|
||||||
}),
|
};
|
||||||
|
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
|
||||||
|
if (currentHoseToken) {
|
||||||
|
headers.hoseaccesstoken = currentHoseToken;
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
},
|
||||||
onUnauthorized: async () => {
|
onUnauthorized: async () => {
|
||||||
invalidateEasoCache(corp.id);
|
invalidateEasoCache(corp.id);
|
||||||
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
|
||||||
|
|||||||
@@ -24,3 +24,20 @@
|
|||||||
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
|
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
|
||||||
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
|
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
|
||||||
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
|
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
|
||||||
|
|
||||||
|
## 会话生成、导入与身份完整度
|
||||||
|
|
||||||
|
- `assist-platform enter <corpId> --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。
|
||||||
|
- `--save --yes` 导入后同步注册当前企业上下文;`--switch` 仅在实际切换成功后输出 `switched: true`。失败时说明配置已保存并提示重试切换。
|
||||||
|
- 生成成功的文本与 JSON 明确交付会话 Token 和可用免密链接,使用 CLI 受控凭证输出机制;捕获的诊断日志和错误继续统一脱敏。
|
||||||
|
- 导入默认沿用底层最佳努力 OpenAPI 密钥提取:无密钥、无读取权限或存在多个密钥均不阻止有效临时会话保存。SDK 显式 `elevate: true` 仍要求成功提取密钥,`elevate: false` 跳过提取。
|
||||||
|
- 身份画像输出可选的 `profileComplete` / `unavailableFields`,配置 `session` 对应保存可选的 `identityComplete` / `identityUnavailableFields`;旧配置仍可读取。员工、管理员标记、角色、权限或部门查询缺失时,完整度为 false;未知的 `isAdmin` / `isSeniorExecutive` 为 null,缺乏已知高风险证据时 `riskLevel` 为 `UNKNOWN`,不会假装 `NORMAL`。
|
||||||
|
- 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。
|
||||||
|
|
||||||
|
SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。
|
||||||
|
|
||||||
|
## 审批与转交目标解析
|
||||||
|
|
||||||
|
- `approve <工单ID> --corp <企业ID>`:显式 `--corp` 下,唯一位置参数始终为工单 ID;也支持 `approve <企业ID> <工单ID>`、`approve <企业ID> --ticket <工单ID>`,以及使用当前企业的 `approve <工单ID>` / `approve --ticket <工单ID>`。位置工单与 `--ticket` 不一致或位置参数多余时拒绝执行;只有完全未指定工单时才自动查询待授权工单。
|
||||||
|
- 转交收件人依次按账号 ID、工号、姓名精确匹配,再尝试模糊匹配。同一账号的多条角色记录按用户 ID 去重;同一匹配级别命中多个用户时拒绝选择,须改用唯一工号或账号。
|
||||||
|
- 转交的 dry-run 与执行使用相同的收件人解析规则。歧义、未找到人员或查询失败都会终止,不会将未解析的输入直接提交给转交接口。
|
||||||
@@ -6,6 +6,7 @@ import type {
|
|||||||
AssistPlatformTicket,
|
AssistPlatformTicket,
|
||||||
CorporationDetail,
|
CorporationDetail,
|
||||||
StaffRoleItem,
|
StaffRoleItem,
|
||||||
|
AssistIdentityUnavailableField,
|
||||||
TransferCandidate,
|
TransferCandidate,
|
||||||
TransferTicketParams,
|
TransferTicketParams,
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
@@ -392,9 +393,11 @@ export async function getStaffMeAndRolesApi(
|
|||||||
permissions: string[];
|
permissions: string[];
|
||||||
roles: StaffRoleItem[];
|
roles: StaffRoleItem[];
|
||||||
departmentName?: string;
|
departmentName?: string;
|
||||||
|
unavailableFields: AssistIdentityUnavailableField[];
|
||||||
}> {
|
}> {
|
||||||
let staff: Record<string, unknown> = {};
|
let staff: Record<string, unknown> = {};
|
||||||
let permissions: string[] = [];
|
let permissions: string[] = [];
|
||||||
|
const unavailableFields = new Set<AssistIdentityUnavailableField>(["staff", "admin", "permissions", "roles"]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const meRes = await client
|
const meRes = await client
|
||||||
@@ -409,9 +412,12 @@ export async function getStaffMeAndRolesApi(
|
|||||||
}>();
|
}>();
|
||||||
if (meRes.value?.staff) {
|
if (meRes.value?.staff) {
|
||||||
staff = meRes.value.staff;
|
staff = meRes.value.staff;
|
||||||
|
if (staff.id) unavailableFields.delete("staff");
|
||||||
|
if (typeof staff.admin === "boolean") unavailableFields.delete("admin");
|
||||||
}
|
}
|
||||||
if (Array.isArray(meRes.value?.permissions)) {
|
if (Array.isArray(meRes.value?.permissions) && meRes.value.permissions.every((permission) => typeof permission === "string")) {
|
||||||
permissions = meRes.value.permissions.map(String);
|
permissions = meRes.value.permissions.map(String);
|
||||||
|
unavailableFields.delete("permissions");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 允许容错降级
|
// 允许容错降级
|
||||||
@@ -436,8 +442,11 @@ export async function getStaffMeAndRolesApi(
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
if (Array.isArray(rolesRes.items)) {
|
if (Array.isArray(rolesRes.items)) {
|
||||||
|
if (rolesRes.items.every((item) => item && typeof item.roleDefName === "string")) {
|
||||||
|
unavailableFields.delete("roles");
|
||||||
|
}
|
||||||
for (const item of rolesRes.items) {
|
for (const item of rolesRes.items) {
|
||||||
if (item.roleDefName) {
|
if (item?.roleDefName) {
|
||||||
roles.push({
|
roles.push({
|
||||||
id: String(item.roleDefId || ""),
|
id: String(item.roleDefId || ""),
|
||||||
name: String(item.roleDefName),
|
name: String(item.roleDefName),
|
||||||
@@ -456,6 +465,7 @@ export async function getStaffMeAndRolesApi(
|
|||||||
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
|
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
|
||||||
);
|
);
|
||||||
if (deptId) {
|
if (deptId) {
|
||||||
|
unavailableFields.add("department");
|
||||||
try {
|
try {
|
||||||
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
|
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
|
||||||
const deptRes = await client
|
const deptRes = await client
|
||||||
@@ -465,6 +475,7 @@ export async function getStaffMeAndRolesApi(
|
|||||||
.json<{ value?: { name?: string } }>();
|
.json<{ value?: { name?: string } }>();
|
||||||
if (deptRes.value?.name) {
|
if (deptRes.value?.name) {
|
||||||
departmentName = deptRes.value.name;
|
departmentName = deptRes.value.name;
|
||||||
|
unavailableFields.delete("department");
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 允许容错降级
|
// 允许容错降级
|
||||||
@@ -476,6 +487,7 @@ export async function getStaffMeAndRolesApi(
|
|||||||
permissions,
|
permissions,
|
||||||
roles,
|
roles,
|
||||||
departmentName,
|
departmentName,
|
||||||
|
unavailableFields: [...unavailableFields],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, expect, it } from "bun:test";
|
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||||
import ky from "ky";
|
import ky from "ky";
|
||||||
import {
|
import {
|
||||||
analyzeStaffRoleRisk,
|
analyzeStaffRoleRisk,
|
||||||
@@ -26,6 +26,13 @@ function createMockClient(handler: (req: Request) => Response | Promise<Response
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("domains/assist-platform - 协助平台业务编排", () => {
|
describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||||
|
let originalFetch: typeof fetch;
|
||||||
|
beforeEach(() => {
|
||||||
|
originalFetch = globalThis.fetch;
|
||||||
|
// 身份穿透创建独立客户端;禁止这些 mock 编排测试访问真实企业接口。
|
||||||
|
globalThis.fetch = (async () => new Response("Mock identity unavailable", { status: 403 })) as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
afterEach(() => { globalThis.fetch = originalFetch; });
|
||||||
it("searchCorporations 能够正确分页并返回企业列表", async () => {
|
it("searchCorporations 能够正确分页并返回企业列表", async () => {
|
||||||
const client = createMockClient(async (req) => {
|
const client = createMockClient(async (req) => {
|
||||||
expect(req.url).toContain("corporation/search");
|
expect(req.url).toContain("corporation/search");
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import ky, { type KyInstance } from "ky";
|
import ky, { type KyInstance } from "ky";
|
||||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
import { loadCorpConfigs, saveCorpConfig } from "../../core/config/loader.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import {
|
import {
|
||||||
approveAssistTicketApi,
|
approveAssistTicketApi,
|
||||||
@@ -73,13 +73,14 @@ export const SENIOR_ROLE_KEYWORDS = [
|
|||||||
|
|
||||||
export function analyzeStaffRoleRisk(profile: {
|
export function analyzeStaffRoleRisk(profile: {
|
||||||
staffName: string;
|
staffName: string;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean | null;
|
||||||
|
profileComplete?: boolean;
|
||||||
roleNames: string[];
|
roleNames: string[];
|
||||||
permissions: string[];
|
permissions: string[];
|
||||||
}): {
|
}): {
|
||||||
isSeniorExecutive: boolean;
|
isSeniorExecutive: boolean | null;
|
||||||
seniorTitles: string[];
|
seniorTitles: string[];
|
||||||
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
|
riskLevel: "HIGH" | "MEDIUM" | "NORMAL" | "UNKNOWN";
|
||||||
riskWarning?: string;
|
riskWarning?: string;
|
||||||
} {
|
} {
|
||||||
const seniorTitles: string[] = [];
|
const seniorTitles: string[] = [];
|
||||||
@@ -100,17 +101,23 @@ export function analyzeStaffRoleRisk(profile: {
|
|||||||
["SYS_ADMIN", "ROLE_ADMIN", "CORP_PAYMENT_MANAGE", "FLOW_ADMIN"].includes(p)
|
["SYS_ADMIN", "ROLE_ADMIN", "CORP_PAYMENT_MANAGE", "FLOW_ADMIN"].includes(p)
|
||||||
);
|
);
|
||||||
|
|
||||||
const isSeniorExecutive = seniorTitles.length > 0 || hasHighRiskPerms;
|
const hasKnownRisk = seniorTitles.length > 0 || hasHighRiskPerms;
|
||||||
const riskLevel = seniorTitles.length > 0 ? "HIGH" : hasHighRiskPerms ? "MEDIUM" : "NORMAL";
|
const incomplete = profile.profileComplete === false;
|
||||||
|
const isSeniorExecutive = hasKnownRisk ? true : incomplete ? null : false;
|
||||||
|
const riskLevel = seniorTitles.length > 0 ? "HIGH" : hasHighRiskPerms ? "MEDIUM" : incomplete ? "UNKNOWN" : "NORMAL";
|
||||||
|
|
||||||
let riskWarning: string | undefined;
|
let riskWarning: string | undefined;
|
||||||
if (isSeniorExecutive) {
|
if (hasKnownRisk) {
|
||||||
const titleSummary = seniorTitles.length > 0 ? seniorTitles.join(" / ") : "高级系统管理员";
|
const titleSummary = seniorTitles.length > 0 ? seniorTitles.join(" / ") : "高级系统管理员";
|
||||||
riskWarning =
|
riskWarning =
|
||||||
`当前协助会话获取的是高阶管理人员身份 [${titleSummary}](${profile.staffName})。` +
|
`当前协助会话获取的是高阶管理人员身份 [${titleSummary}](${profile.staffName})。` +
|
||||||
`该身份拥有高级审批、财务权限或全系统管理权限。经理与实施人员严禁借用该身份发起或通过非授权审批,防范越权误操作!`;
|
`该身份拥有高级审批、财务权限或全系统管理权限。经理与实施人员严禁借用该身份发起或通过非授权审批,防范越权误操作!`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (incomplete) {
|
||||||
|
riskWarning = `${riskWarning || ""}身份或角色权限信息不完整,无法排除更高权限风险,请先核验当前身份。`;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isSeniorExecutive,
|
isSeniorExecutive,
|
||||||
seniorTitles,
|
seniorTitles,
|
||||||
@@ -145,7 +152,8 @@ export async function inspectAssistIdentity(
|
|||||||
const cellphone = staff.cellphone ? String(staff.cellphone) : undefined;
|
const cellphone = staff.cellphone ? String(staff.cellphone) : undefined;
|
||||||
const email = staff.email ? String(staff.email) : undefined;
|
const email = staff.email ? String(staff.email) : undefined;
|
||||||
const code = staff.code ? String(staff.code) : undefined;
|
const code = staff.code ? String(staff.code) : undefined;
|
||||||
const isAdmin = Boolean(staff.admin || false);
|
const isAdmin = typeof staff.admin === "boolean" ? staff.admin : null;
|
||||||
|
const profileComplete = res.unavailableFields.length === 0;
|
||||||
|
|
||||||
const roleNames = res.roles.map((r) => r.name);
|
const roleNames = res.roles.map((r) => r.name);
|
||||||
const readablePermissions = res.permissions.map(
|
const readablePermissions = res.permissions.map(
|
||||||
@@ -153,6 +161,7 @@ export async function inspectAssistIdentity(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const riskAnalysis = analyzeStaffRoleRisk({
|
const riskAnalysis = analyzeStaffRoleRisk({
|
||||||
|
profileComplete,
|
||||||
staffName,
|
staffName,
|
||||||
isAdmin,
|
isAdmin,
|
||||||
roleNames,
|
roleNames,
|
||||||
@@ -160,6 +169,8 @@ export async function inspectAssistIdentity(
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
profileComplete,
|
||||||
|
unavailableFields: res.unavailableFields,
|
||||||
staffId,
|
staffId,
|
||||||
staffName,
|
staffName,
|
||||||
cellphone,
|
cellphone,
|
||||||
@@ -338,20 +349,52 @@ export async function importAssistSessionToLocal(
|
|||||||
overwrite: params.overwrite ?? true,
|
overwrite: params.overwrite ?? true,
|
||||||
enterprisesDir: params.enterprisesDir,
|
enterprisesDir: params.enterprisesDir,
|
||||||
ttl: params.ttl,
|
ttl: params.ttl,
|
||||||
elevate: params.elevate ?? true,
|
elevate: params.elevate,
|
||||||
};
|
};
|
||||||
|
|
||||||
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
|
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
|
||||||
? sessionResult.loginUrl
|
? sessionResult.loginUrl
|
||||||
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||||
|
|
||||||
|
const previousCorp = loadCorpConfigs(params.enterprisesDir ? [params.enterprisesDir] : undefined)
|
||||||
|
.find((corp) => corp.id === sessionResult.corporationId);
|
||||||
const corpConfig = await importFromLink(linkToImport, importOptions);
|
const corpConfig = await importFromLink(linkToImport, importOptions);
|
||||||
|
|
||||||
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
||||||
if (sessionResult.identity) {
|
if (sessionResult.identity) {
|
||||||
const ident = sessionResult.identity;
|
const ident = sessionResult.identity;
|
||||||
|
// 画像接口失败时保留 JWT 已确认的身份,不能将未知值降为非管理员或低风险
|
||||||
|
const previousSession = previousCorp?.credentials.staffId === corpConfig.credentials.staffId
|
||||||
|
? previousCorp.session
|
||||||
|
: undefined;
|
||||||
|
ident.isAdmin ??= corpConfig.session?.isAdmin ?? previousSession?.isAdmin ?? null;
|
||||||
|
const unavailable = ident.unavailableFields || [];
|
||||||
|
if (unavailable.includes("roles") && previousSession?.roles) {
|
||||||
|
ident.roleNames = [...new Set([...ident.roleNames, ...previousSession.roles])];
|
||||||
|
}
|
||||||
|
if (unavailable.includes("permissions") && previousSession?.permissions) {
|
||||||
|
ident.permissions = [...new Set([...ident.permissions, ...previousSession.permissions])];
|
||||||
|
ident.readablePermissions = ident.permissions.map((p) => `${PERMISSION_LABEL_MAP[p] || p} (${p})`);
|
||||||
|
}
|
||||||
|
if (unavailable.includes("staff")) {
|
||||||
|
ident.staffId = corpConfig.credentials.staffId || ident.staffId;
|
||||||
|
ident.staffName = corpConfig.session?.staffName || ident.staffName;
|
||||||
|
}
|
||||||
|
Object.assign(ident, analyzeStaffRoleRisk(ident));
|
||||||
|
// 同一员工的历史高风险证据不能因本次探测不完整而被降级。
|
||||||
|
if (ident.profileComplete === false && previousSession?.riskLevel) {
|
||||||
|
const riskRank: Record<string, number> = { UNKNOWN: 0, NORMAL: 0, MEDIUM: 1, HIGH: 2 };
|
||||||
|
if ((riskRank[previousSession.riskLevel] || 0) > riskRank[ident.riskLevel]!) {
|
||||||
|
ident.riskLevel = previousSession.riskLevel as "HIGH" | "MEDIUM";
|
||||||
|
ident.isSeniorExecutive = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sessionResult.staffId = ident.staffId || sessionResult.staffId;
|
||||||
|
sessionResult.staffName = ident.staffName || sessionResult.staffName;
|
||||||
corpConfig.session = {
|
corpConfig.session = {
|
||||||
...corpConfig.session,
|
...corpConfig.session,
|
||||||
|
identityComplete: ident.profileComplete,
|
||||||
|
identityUnavailableFields: ident.unavailableFields,
|
||||||
staffName: ident.staffName || corpConfig.session?.staffName,
|
staffName: ident.staffName || corpConfig.session?.staffName,
|
||||||
cellphone: ident.cellphone || corpConfig.session?.cellphone,
|
cellphone: ident.cellphone || corpConfig.session?.cellphone,
|
||||||
isAdmin: ident.isAdmin ?? corpConfig.session?.isAdmin,
|
isAdmin: ident.isAdmin ?? corpConfig.session?.isAdmin,
|
||||||
@@ -388,31 +431,39 @@ export async function resolveTransferRecipient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const candidates = await listTransferCandidates(client);
|
const candidates = await listTransferCandidates(client);
|
||||||
const exactMatches = candidates.filter(
|
// 一个用户可能有多条角色记录;先匹配,再按稳定账号 ID 去重。
|
||||||
(c) => c.name === cleanTarget || c.code === cleanTarget || c.id === cleanTarget
|
const uniqueUsers = (matches: TransferCandidate[]) =>
|
||||||
);
|
[...new Map(matches.map((candidate) => [candidate.id, candidate])).values()];
|
||||||
if (exactMatches.length === 1) {
|
const rejectAmbiguous = (matches: TransferCandidate[]): never => {
|
||||||
return exactMatches[0];
|
const names = matches
|
||||||
}
|
.slice(0, 5)
|
||||||
if (exactMatches.length > 1) {
|
.map((m) => `${m.name}(${m.id}${m.code ? `, 工号: ${m.code}` : ""})`)
|
||||||
return exactMatches[0];
|
.join("、");
|
||||||
|
throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定唯一工号或账号`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 账号 ID 优先于工号、姓名,避免一个人的姓名覆盖另一个人的明确账号。
|
||||||
|
for (const matches of [
|
||||||
|
candidates.filter((c) => c.id === cleanTarget),
|
||||||
|
candidates.filter((c) => c.code === cleanTarget),
|
||||||
|
candidates.filter((c) => c.name === cleanTarget),
|
||||||
|
]) {
|
||||||
|
const users = uniqueUsers(matches);
|
||||||
|
if (users.length === 1) return users[0];
|
||||||
|
if (users.length > 1) rejectAmbiguous(users);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fuzzyMatches = candidates.filter(
|
const fuzzyMatches = uniqueUsers(candidates.filter(
|
||||||
(c) =>
|
(c) =>
|
||||||
c.name.includes(cleanTarget) ||
|
c.name.includes(cleanTarget) ||
|
||||||
(c.code && c.code.includes(cleanTarget)) ||
|
(c.code && c.code.includes(cleanTarget)) ||
|
||||||
c.id.includes(cleanTarget)
|
c.id.includes(cleanTarget)
|
||||||
);
|
));
|
||||||
if (fuzzyMatches.length === 1) {
|
if (fuzzyMatches.length === 1) {
|
||||||
return fuzzyMatches[0];
|
return fuzzyMatches[0];
|
||||||
}
|
}
|
||||||
if (fuzzyMatches.length > 1) {
|
if (fuzzyMatches.length > 1) {
|
||||||
const names = fuzzyMatches
|
rejectAmbiguous(fuzzyMatches);
|
||||||
.slice(0, 5)
|
|
||||||
.map((m) => `${m.name}(${m.code || m.id})`)
|
|
||||||
.join("、");
|
|
||||||
throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定具体工号或全名`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`);
|
throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`);
|
||||||
@@ -426,16 +477,9 @@ export async function transferAssistTicket(
|
|||||||
remarks?: string;
|
remarks?: string;
|
||||||
}
|
}
|
||||||
): Promise<TransferTicketResult> {
|
): Promise<TransferTicketResult> {
|
||||||
let resolvedRecipientId = params.recipient;
|
const candidate = await resolveTransferRecipient(client, params.recipient);
|
||||||
let recipientName: string | undefined;
|
const resolvedRecipientId = candidate.id;
|
||||||
|
const recipientName = candidate.name;
|
||||||
try {
|
|
||||||
const candidate = await resolveTransferRecipient(client, params.recipient);
|
|
||||||
resolvedRecipientId = candidate.id;
|
|
||||||
recipientName = candidate.name;
|
|
||||||
} catch {
|
|
||||||
// 若解析不到,仍尝试直接以原值请求
|
|
||||||
}
|
|
||||||
|
|
||||||
await transferAssistTicketApi(client, {
|
await transferAssistTicketApi(client, {
|
||||||
ticketId: params.ticketId,
|
ticketId: params.ticketId,
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import ky from "ky";
|
||||||
|
import { BusinessError, EkbApiError, NotFoundError } from "../../core/errors.js";
|
||||||
|
import { resolveTransferRecipient, transferAssistTicket } from "./services.js";
|
||||||
|
|
||||||
|
type User = { id: string; name: string; code?: string };
|
||||||
|
const first: User = { id: "zhang3016", name: "张三", code: "3016" };
|
||||||
|
const second: User = { id: "zhang3020", name: "张三", code: "3020" };
|
||||||
|
|
||||||
|
function mockClient(users: User[], failSearch = false) {
|
||||||
|
const writes: unknown[] = [];
|
||||||
|
const client = ky.create({
|
||||||
|
prefix: "https://assist.invalid/api",
|
||||||
|
retry: 0,
|
||||||
|
fetch: async (input, init) => {
|
||||||
|
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||||
|
if (request.url.endsWith("userRole/search")) {
|
||||||
|
if (failSearch) return new Response("unavailable", { status: 503 });
|
||||||
|
return Response.json({ items: users.map((userId, i) => ({
|
||||||
|
id: `role-row-${i}`,
|
||||||
|
userId,
|
||||||
|
roleIds: [{ id: `role-${i}`, name: `角色${i}` }],
|
||||||
|
})) });
|
||||||
|
}
|
||||||
|
if (request.url.endsWith("assistPlatform/transfer")) {
|
||||||
|
writes.push(await request.json());
|
||||||
|
return Response.json({ value: true });
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected request: ${request.url}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { client, writes };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("assist-platform 转交目标解析", () => {
|
||||||
|
it("同名不同账号拒绝精确匹配,错误提示唯一工号或账号", async () => {
|
||||||
|
const { client } = mockClient([first, second]);
|
||||||
|
await expect(resolveTransferRecipient(client, "张三")).rejects.toBeInstanceOf(BusinessError);
|
||||||
|
await expect(resolveTransferRecipient(client, "张三")).rejects.toThrow("唯一工号或账号");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("相同工号的不同用户也拒绝选择第一人", async () => {
|
||||||
|
const { client } = mockClient([first, { ...second, code: first.code }]);
|
||||||
|
await expect(resolveTransferRecipient(client, "3016")).rejects.toThrow("多个可转交人员");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("账号精确匹配优先于其他人的工号和姓名", async () => {
|
||||||
|
const { client } = mockClient([
|
||||||
|
{ ...second, code: first.id },
|
||||||
|
{ id: "other", name: first.id },
|
||||||
|
first,
|
||||||
|
]);
|
||||||
|
expect((await resolveTransferRecipient(client, first.id)).id).toBe(first.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("工号精确匹配优先于其他人的姓名", async () => {
|
||||||
|
const { client } = mockClient([{ ...second, name: "3016" }, first]);
|
||||||
|
expect((await resolveTransferRecipient(client, "3016")).id).toBe(first.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["张三", "3016", "zhang3016", "zhang", " 3016 "])(
|
||||||
|
"同一稳定账号的多条角色记录不会令 %s 产生歧义",
|
||||||
|
async (target) => {
|
||||||
|
const { client } = mockClient([first, first]);
|
||||||
|
expect((await resolveTransferRecipient(client, target)).id).toBe(first.id);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
it("模糊匹配存在多个用户时拒绝", async () => {
|
||||||
|
const { client } = mockClient([first, second]);
|
||||||
|
await expect(resolveTransferRecipient(client, "zhang")).rejects.toThrow("多个可转交人员");
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["张三", "不存在的账号"])("执行转交时 %s 解析失败不提交原始值", async (recipient) => {
|
||||||
|
const { client, writes } = mockClient([first, second]);
|
||||||
|
const ErrorClass = recipient === "张三" ? BusinessError : NotFoundError;
|
||||||
|
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient }))
|
||||||
|
.rejects.toBeInstanceOf(ErrorClass);
|
||||||
|
expect(writes).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("查询候选人失败时不以原始账号继续写入", async () => {
|
||||||
|
const { client, writes } = mockClient([], true);
|
||||||
|
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient: first.id }))
|
||||||
|
.rejects.toBeInstanceOf(EkbApiError);
|
||||||
|
expect(writes).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("使用唯一工号时写入稳定账号 ID", async () => {
|
||||||
|
const { client, writes } = mockClient([first, first, second]);
|
||||||
|
const result = await transferAssistTicket(client, {
|
||||||
|
ticketId: "TICKET", recipient: "3016", remarks: "交接",
|
||||||
|
});
|
||||||
|
expect(result.recipient).toBe(first.id);
|
||||||
|
expect(result.recipientName).toBe(first.name);
|
||||||
|
expect(writes).toEqual([{ assistId: "TICKET", recipient: first.id, remarks: "交接" }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -54,22 +54,26 @@ export interface StaffRoleItem {
|
|||||||
code?: string;
|
code?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type AssistIdentityUnavailableField = "staff" | "admin" | "permissions" | "roles" | "department";
|
||||||
|
|
||||||
export interface AssistIdentityProfile {
|
export interface AssistIdentityProfile {
|
||||||
|
profileComplete?: boolean;
|
||||||
|
unavailableFields?: AssistIdentityUnavailableField[];
|
||||||
staffId: string;
|
staffId: string;
|
||||||
staffName: string;
|
staffName: string;
|
||||||
cellphone?: string;
|
cellphone?: string;
|
||||||
email?: string;
|
email?: string;
|
||||||
code?: string;
|
code?: string;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean | null;
|
||||||
departmentId?: string;
|
departmentId?: string;
|
||||||
departmentName?: string;
|
departmentName?: string;
|
||||||
roles: StaffRoleItem[];
|
roles: StaffRoleItem[];
|
||||||
roleNames: string[];
|
roleNames: string[];
|
||||||
permissions: string[];
|
permissions: string[];
|
||||||
readablePermissions: string[];
|
readablePermissions: string[];
|
||||||
isSeniorExecutive: boolean;
|
isSeniorExecutive: boolean | null;
|
||||||
seniorTitles: string[];
|
seniorTitles: string[];
|
||||||
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
|
riskLevel: "HIGH" | "MEDIUM" | "NORMAL" | "UNKNOWN";
|
||||||
riskWarning?: string;
|
riskWarning?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+47
-20
@@ -830,23 +830,39 @@ export async function getBillByCodeOrId(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
|
// 1.1 如果是典型单据编号特征(如 B26010730、R2023...),优先走审批流通道检索,避免 invoice/search 接口慢超时
|
||||||
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
|
if (/^[A-Za-z][A-Za-z0-9_-]+$/.test(cleanQuery)) {
|
||||||
const matched = searchRes.items.filter((item) => {
|
try {
|
||||||
if (item.id === cleanQuery) return true;
|
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
|
||||||
if (item.code === cleanQuery) return true;
|
if (rawFlow) {
|
||||||
for (const [k, v] of Object.entries(item.form || {})) {
|
return [formatFlowAsBill(rawFlow, dictionary)];
|
||||||
if (typeof v === "string" && v.trim() === cleanQuery) {
|
}
|
||||||
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
|
} catch {
|
||||||
return true;
|
// 容错并继续回退到传统单据检索
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId(带 5s 超时与容错降级)
|
||||||
|
try {
|
||||||
|
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50, timeout: 5000 });
|
||||||
|
const matched = searchRes.items.filter((item) => {
|
||||||
|
if (item.id === cleanQuery) return true;
|
||||||
|
if (item.code === cleanQuery) return true;
|
||||||
|
for (const [k, v] of Object.entries(item.form || {})) {
|
||||||
|
if (typeof v === "string" && v.trim() === cleanQuery) {
|
||||||
|
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
return false;
|
||||||
return false;
|
});
|
||||||
});
|
|
||||||
|
|
||||||
if (matched.length > 0) {
|
if (matched.length > 0) {
|
||||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略 invoice/search 超时或错误,平滑回退
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
|
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
|
||||||
@@ -1049,7 +1065,8 @@ function buildDiagnosticReport(
|
|||||||
export async function traceBillFlowDetail(
|
export async function traceBillFlowDetail(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
corpId: string,
|
corpId: string,
|
||||||
targetQuery: string
|
targetQuery: string,
|
||||||
|
options?: { skipInvoices?: boolean }
|
||||||
): Promise<BillFlowTraceDiagnostic> {
|
): Promise<BillFlowTraceDiagnostic> {
|
||||||
const cleanTarget = targetQuery.trim();
|
const cleanTarget = targetQuery.trim();
|
||||||
if (!cleanTarget) {
|
if (!cleanTarget) {
|
||||||
@@ -1616,7 +1633,8 @@ export async function searchAndFormatBills(
|
|||||||
export async function getTranslatorContext(
|
export async function getTranslatorContext(
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
corpId: string,
|
corpId: string,
|
||||||
rawFlow?: Record<string, unknown>
|
rawFlow?: Record<string, unknown>,
|
||||||
|
options?: { skipInvoices?: boolean }
|
||||||
): Promise<TranslatorOptions> {
|
): Promise<TranslatorOptions> {
|
||||||
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
|
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
|
||||||
getFeeTypeTree(client, corpId),
|
getFeeTypeTree(client, corpId),
|
||||||
@@ -1667,10 +1685,19 @@ export async function getTranslatorContext(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const invoiceFetches = Array.from(invoiceIds).map(async (id) => {
|
const invoiceFetches = options?.skipInvoices
|
||||||
const detail = await getInvoiceValidationDetail(client, corpId, id);
|
? []
|
||||||
if (detail) invoiceDetailMap.set(id, detail);
|
: Array.from(invoiceIds).map(async (id) => {
|
||||||
});
|
try {
|
||||||
|
const detail = await Promise.race([
|
||||||
|
getInvoiceValidationDetail(client, corpId, id),
|
||||||
|
new Promise<null>((_, reject) => setTimeout(() => reject(new Error("Invoice timeout")), 3000)),
|
||||||
|
]);
|
||||||
|
if (detail) invoiceDetailMap.set(id, detail);
|
||||||
|
} catch {
|
||||||
|
// 单张发票详情超时或获取失败不阻断整体流程解析
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
|
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
|
||||||
const cardCandidateIds = new Set<string>();
|
const cardCandidateIds = new Set<string>();
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ hose-use platform list
|
|||||||
hose-use platform get <应用 ID|名称>
|
hose-use platform get <应用 ID|名称>
|
||||||
hose-use platform entities <应用 ID|名称>
|
hose-use platform entities <应用 ID|名称>
|
||||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--search-fields <字段列表>] [--filter <表达式>] [--where <条件>] [--sum <字段1,字段2>] [--group-by <字段>] [--fields <字段列表>] [--flat] [--ndjson] [--stats]
|
||||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||||
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
hose-use platform record edit <应用> <业务对象> <记录ID> [--set="字段=值" | --data='{"field": "val"}'] [--raw] [--dry-run|--yes]
|
||||||
@@ -50,7 +50,10 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
|||||||
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
- `records --stats`(或 `records stats <应用> <对象>` / `records profile`):宏观结构与特征聚类画像。输出总记录数、启用/停用分布及占比、唯一标题数与重名分布、编码生成规则聚类(自动提取 `${groupIndex}-${formCode}-month-${idx}` 等动态模板分布)、最早与最新维护时间,毫秒级洞察数据特征。
|
||||||
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
- `records --flat`:自动剥离底层动态物理前缀(如 `E_<entityId>_`),提取关联引用对象的名称/编码,将复杂元数据规整为 `{ id, code, name, active, createTime, updateTime, fields }` 干净对象。
|
||||||
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
- `records --sum="字段1,字段2" [--group-by="分组字段"]`:台账数学聚合核算,自动解析纯数值、金额对象(`{ standard: 100 }`)与货币符号字符串(`¥12,500.00`),输出样本数、总合计(SUM)、均值(AVG)、最小值(MIN)、最大值(MAX)以及指定字段的分组小计。
|
||||||
|
- `records --keyword="关键词" [--search-fields="字段1,字段2"]`:服务端原生索引检索。缺省检索 `name` 与 `code`;指定 `--search-fields` 时,自动解析业务字段(无论标签更名还是底层代码),自动附加 `form.E_...` 命名空间及货币复合对象(`standard`)过滤,服务端秒级精准返回,杜绝客户端无边界全表扫描。
|
||||||
|
- `records --filter="表达式"`:服务端原生 `filterBy` 过滤。支持原生 DSL 语法,同时支持简写形式(如 `--filter="客户名称~猫子"`、`--filter="不含税金额=191700"`、`--filter="状态!=停用"`),自动结合业务对象元数据映射底层物理字段与数据类型。
|
||||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||||
|
- **客户端谓词早退机制(Early-Exit)**:未显式指定 `--all` 时,检索采用流式迭代,匹配满 `count`(默认 20 条)即刻终止拉取,杜绝无脑拉取全量台账导致的大流量开销与终端假死。
|
||||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
|
|||||||
import {
|
import {
|
||||||
DatalinkEntitySchema,
|
DatalinkEntitySchema,
|
||||||
DatalinkPlatformDetailSchema,
|
DatalinkPlatformDetailSchema,
|
||||||
|
enrichDatalinkField,
|
||||||
type DatalinkEntity,
|
type DatalinkEntity,
|
||||||
type DatalinkField,
|
type DatalinkField,
|
||||||
type DatalinkImportJob,
|
type DatalinkImportJob,
|
||||||
@@ -26,7 +27,11 @@ function numberOr(value: unknown, fallback: number): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseEntity(value: unknown): DatalinkEntity {
|
function parseEntity(value: unknown): DatalinkEntity {
|
||||||
return DatalinkEntitySchema.parse(asRecord(value));
|
const entity = DatalinkEntitySchema.parse(asRecord(value));
|
||||||
|
return {
|
||||||
|
...entity,
|
||||||
|
fields: entity.fields.map(enrichDatalinkField),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
|
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
|
||||||
|
|||||||
@@ -16,10 +16,12 @@ import {
|
|||||||
auditLedgerContinuityAndBaseline,
|
auditLedgerContinuityAndBaseline,
|
||||||
batchSafeEditRecords,
|
batchSafeEditRecords,
|
||||||
buildKeywordFilter,
|
buildKeywordFilter,
|
||||||
|
buildServerFieldFilter,
|
||||||
calculateEntityRecordStats,
|
calculateEntityRecordStats,
|
||||||
compileRecordPredicate,
|
compileRecordPredicate,
|
||||||
fetchAllEntityRecords,
|
fetchAllEntityRecords,
|
||||||
filterRecordsByPredicate,
|
filterRecordsByPredicate,
|
||||||
|
formatServerFieldExpr,
|
||||||
iterateAllEntityRecords,
|
iterateAllEntityRecords,
|
||||||
normalizeDatalinkRecord,
|
normalizeDatalinkRecord,
|
||||||
parseExpectClause,
|
parseExpectClause,
|
||||||
@@ -670,4 +672,59 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("DataLink native server filter and keyword expression builder", () => {
|
||||||
|
const entity = {
|
||||||
|
id: "c214f3d2d4bc7e8adfc0",
|
||||||
|
name: "待摊台账",
|
||||||
|
fields: [
|
||||||
|
{ name: "E_c214f3d2d4bc7e8adfc0_客户名称", label: "客户名称", type: "text" },
|
||||||
|
{ name: "E_c214f3d2d4bc7e8adfc0_不含税金额", label: "不含税金额", type: "money" },
|
||||||
|
{ name: "E_c214f3d2d4bc7e8adfc0_合同月数", label: "月数", type: "number" },
|
||||||
|
{ name: "E_c214f3d2d4bc7e8adfc0_单号", label: "单号", type: "text" },
|
||||||
|
],
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
test("buildKeywordFilter 缺省模式保持向后兼容并仅查询 name 与 code", () => {
|
||||||
|
const filter = buildKeywordFilter("测试");
|
||||||
|
expect(filter).toBe('(name.containsIgnoreCase("测试")||code.containsIgnoreCase("测试"))&&(active.in(true,false))');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildKeywordFilter 支持指定业务字段并自动附加 form. 命名空间", () => {
|
||||||
|
const filter = buildKeywordFilter("猫子", {
|
||||||
|
entity,
|
||||||
|
searchFields: ["客户名称"],
|
||||||
|
});
|
||||||
|
expect(filter).toBe(
|
||||||
|
'(name.containsIgnoreCase("猫子")||code.containsIgnoreCase("猫子")||form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("formatServerFieldExpr 针对 money 字段生成标准 .standard 精确表达式", () => {
|
||||||
|
const expr = formatServerFieldExpr("不含税金额", "=", "191700", entity);
|
||||||
|
expect(expr).toBe(
|
||||||
|
'(form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700"||form.E_c214f3d2d4bc7e8adfc0_不含税金额.standard=="191700.00")'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildServerFieldFilter 支持 key~val 模糊检索并附加 active 白名单", () => {
|
||||||
|
const filter = buildServerFieldFilter("客户名称~猫子", entity);
|
||||||
|
expect(filter).toBe('(form.E_c214f3d2d4bc7e8adfc0_客户名称.containsIgnoreCase("猫子"))&&(active.in(true,false))');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildServerFieldFilter 支持已更名标签或底层物理 Code 映射", () => {
|
||||||
|
// 字段名为 "合同月数",标签修改为 "月数"
|
||||||
|
const filterByLabel = buildServerFieldFilter("月数=1", entity);
|
||||||
|
expect(filterByLabel).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||||
|
|
||||||
|
const filterByCode = buildServerFieldFilter("E_c214f3d2d4bc7e8adfc0_合同月数=1", entity);
|
||||||
|
expect(filterByCode).toBe('(form.E_c214f3d2d4bc7e8adfc0_合同月数==1)&&(active.in(true,false))');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildServerFieldFilter 透传原生复杂的 DataLink DSL 表达式", () => {
|
||||||
|
const rawDsl = '(active == true && INSTR(form.code, "ABC") > 0)';
|
||||||
|
expect(buildServerFieldFilter(rawDsl, entity)).toBe(rawDsl);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -103,9 +103,119 @@ export async function resolveEntity(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildKeywordFilter(keyword: string): string {
|
export interface BuildKeywordFilterOptions {
|
||||||
|
entity?: DatalinkEntity;
|
||||||
|
searchFields?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化服务端 filterBy 字段表达式。
|
||||||
|
* 针对 DataLink 特性:
|
||||||
|
* - 动态业务字段(E_ 前缀)自动附加 form. 命名空间
|
||||||
|
* - money 货币复合对象自动下钻到 .standard 标准字符串
|
||||||
|
* - number 数值字段支持比较运算符
|
||||||
|
*/
|
||||||
|
export function formatServerFieldExpr(
|
||||||
|
fieldKey: string,
|
||||||
|
op: string,
|
||||||
|
rawVal: string,
|
||||||
|
entity?: DatalinkEntity
|
||||||
|
): string {
|
||||||
|
const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined;
|
||||||
|
const targetKey = resolved?.name || fieldKey;
|
||||||
|
const isCustom = targetKey.startsWith("E_");
|
||||||
|
const serverPath = isCustom ? `form.${targetKey}` : targetKey;
|
||||||
|
const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
|
const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== "";
|
||||||
|
|
||||||
|
// Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... })
|
||||||
|
if (resolved?.type === "money") {
|
||||||
|
const moneyPath = `${serverPath}.standard`;
|
||||||
|
const num = Number(rawVal);
|
||||||
|
const withDec = !Number.isNaN(num) && !rawVal.includes(".") ? `${rawVal}.00` : rawVal;
|
||||||
|
if (op === "=" || op === "==") {
|
||||||
|
if (withDec !== rawVal) {
|
||||||
|
return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`;
|
||||||
|
}
|
||||||
|
return `${moneyPath}=="${escaped}"`;
|
||||||
|
}
|
||||||
|
if (op === "!=") {
|
||||||
|
return `${moneyPath}!="${escaped}"`;
|
||||||
|
}
|
||||||
|
return `${moneyPath}.containsIgnoreCase("${escaped}")`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Number 字段
|
||||||
|
if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) {
|
||||||
|
if (op === "~" || op === "=~" || op === ":") {
|
||||||
|
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
||||||
|
}
|
||||||
|
const cmp = op === "=" ? "==" : op;
|
||||||
|
return `${serverPath}${cmp}${rawVal}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text / Ref / Other 字段
|
||||||
|
if (op === "~" || op === "=~" || op === ":") {
|
||||||
|
return `${serverPath}.containsIgnoreCase("${escaped}")`;
|
||||||
|
}
|
||||||
|
if (op === "!=") {
|
||||||
|
return `${serverPath}!="${escaped}"`;
|
||||||
|
}
|
||||||
|
return `${serverPath}=="${escaped}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildKeywordFilter(
|
||||||
|
keyword: string,
|
||||||
|
options?: BuildKeywordFilterOptions
|
||||||
|
): string {
|
||||||
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
const conds: string[] = [
|
||||||
|
`name.containsIgnoreCase("${escaped}")`,
|
||||||
|
`code.containsIgnoreCase("${escaped}")`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (options?.entity && options.searchFields && options.searchFields.length > 0) {
|
||||||
|
for (const searchField of options.searchFields) {
|
||||||
|
const resolved = resolveEntityField(options.entity, searchField);
|
||||||
|
const targetName = resolved?.name || searchField;
|
||||||
|
if (targetName && targetName !== "name" && targetName !== "code") {
|
||||||
|
const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity);
|
||||||
|
conds.push(expr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `(${conds.join("||")})&&(active.in(true,false))`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。
|
||||||
|
* 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。
|
||||||
|
*/
|
||||||
|
export function buildServerFieldFilter(
|
||||||
|
filterInput: string,
|
||||||
|
entity?: DatalinkEntity
|
||||||
|
): string {
|
||||||
|
const trimmed = filterInput.trim();
|
||||||
|
if (
|
||||||
|
trimmed.startsWith("(") ||
|
||||||
|
trimmed.includes(".containsIgnoreCase(") ||
|
||||||
|
trimmed.includes(".in(") ||
|
||||||
|
trimmed.includes("==")
|
||||||
|
) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用"
|
||||||
|
const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/);
|
||||||
|
if (!match) return trimmed;
|
||||||
|
|
||||||
|
const rawKey = match[1].trim();
|
||||||
|
const op = match[2];
|
||||||
|
const rawVal = match[3].trim().replace(/^["']|["']$/g, "");
|
||||||
|
|
||||||
|
const expr = formatServerFieldExpr(rawKey, op, rawVal, entity);
|
||||||
|
return expr ? `(${expr})&&(active.in(true,false))` : trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function selectRecordFields(
|
export function selectRecordFields(
|
||||||
|
|||||||
@@ -20,9 +20,37 @@ export const DatalinkFieldSchema = z
|
|||||||
unit: z.string().nullable().optional(),
|
unit: z.string().nullable().optional(),
|
||||||
index: z.boolean().nullable().optional(),
|
index: z.boolean().nullable().optional(),
|
||||||
systemField: z.boolean().nullable().optional(),
|
systemField: z.boolean().nullable().optional(),
|
||||||
|
fieldKey: z.string().optional(),
|
||||||
|
displayName: z.string().optional(),
|
||||||
|
role: z.enum(["title", "code", "system", "custom"]).optional(),
|
||||||
|
description: z.string().optional(),
|
||||||
})
|
})
|
||||||
.passthrough();
|
.passthrough();
|
||||||
|
|
||||||
|
export function enrichDatalinkField<T extends DatalinkField>(field: T): T {
|
||||||
|
const name = field.name;
|
||||||
|
const label = field.label;
|
||||||
|
let role: "title" | "code" | "system" | "custom" = "custom";
|
||||||
|
let description = `业务自定义字段 (界面显示为「${label}」),API与工作流配置时使用此物理键`;
|
||||||
|
if (name.endsWith("_name")) {
|
||||||
|
role = "title";
|
||||||
|
description = `实体主名称/标题 (界面显示为「${label}」),系统基础字段`;
|
||||||
|
} else if (name.endsWith("_code")) {
|
||||||
|
role = "code";
|
||||||
|
description = `业务单号/流水号 (界面显示为「${label}」),通常由自动编号规则生成`;
|
||||||
|
} else if (field.systemField) {
|
||||||
|
role = "system";
|
||||||
|
description = `系统预置字段 (界面显示为「${label}」)`;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...field,
|
||||||
|
fieldKey: field.fieldKey ?? name,
|
||||||
|
displayName: field.displayName ?? label,
|
||||||
|
role: field.role ?? role,
|
||||||
|
description: field.description ?? description,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export const DatalinkEntitySchema = z
|
export const DatalinkEntitySchema = z
|
||||||
.object({
|
.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from "bun:test";
|
import { describe, it, expect } from "bun:test";
|
||||||
import { flattenFeeTypeTree } from "./tools.js";
|
import { flattenFeeTypeTree, collectSubtreeNodes } from "./tools.js";
|
||||||
import { FeeTypeNode } from "./types.js";
|
import { FeeTypeNode } from "./types.js";
|
||||||
|
|
||||||
describe("domains/feetype > tools & helpers", () => {
|
describe("domains/feetype > tools & helpers", () => {
|
||||||
@@ -71,4 +71,15 @@ describe("domains/feetype > tools & helpers", () => {
|
|||||||
expect(flat[3].parentName).toBe("");
|
expect(flat[3].parentName).toBe("");
|
||||||
expect(flat[3].active).toBe(false);
|
expect(flat[3].active).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("collectSubtreeNodes 正确收集指定子树及其全部后代", () => {
|
||||||
|
const subtree = collectSubtreeNodes(sampleTree, "node_1");
|
||||||
|
expect(subtree.map((s) => s.id)).toEqual(["node_1", "node_1_1", "node_1_1_1"]);
|
||||||
|
|
||||||
|
const leafSubtree = collectSubtreeNodes(sampleTree, "node_1_1_1");
|
||||||
|
expect(leafSubtree.map((s) => s.id)).toEqual(["node_1_1_1"]);
|
||||||
|
|
||||||
|
const missingSubtree = collectSubtreeNodes(sampleTree, "not_exist");
|
||||||
|
expect(missingSubtree).toEqual([]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -60,6 +60,41 @@ export function flattenFeeTypeTree(
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归收集 parentId 节点及其所有子孙节点的 FlatFeeTypeItem
|
||||||
|
*/
|
||||||
|
export function collectSubtreeNodes(
|
||||||
|
nodes: FeeTypeNode[],
|
||||||
|
parentId: string,
|
||||||
|
parentPath = "",
|
||||||
|
parentName = ""
|
||||||
|
): FlatFeeTypeItem[] {
|
||||||
|
for (const node of nodes) {
|
||||||
|
const item = node.feeType;
|
||||||
|
if (!item || !item.id) continue;
|
||||||
|
const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name;
|
||||||
|
const children = Array.isArray(node.children) ? node.children : [];
|
||||||
|
if (item.id === parentId || item.name === parentId || item.code.toLowerCase() === parentId.toLowerCase()) {
|
||||||
|
const result: FlatFeeTypeItem[] = [];
|
||||||
|
result.push({
|
||||||
|
...item,
|
||||||
|
path: currentPath,
|
||||||
|
parentName,
|
||||||
|
childrenCount: children.length,
|
||||||
|
});
|
||||||
|
if (children.length > 0) {
|
||||||
|
result.push(...flattenFeeTypeTree(children, currentPath, item.name));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (children.length > 0) {
|
||||||
|
const found = collectSubtreeNodes(children, parentId, currentPath, item.name);
|
||||||
|
if (found.length > 0) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用)
|
* 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用)
|
||||||
*/
|
*/
|
||||||
@@ -127,12 +162,15 @@ export async function listFeeTypes(
|
|||||||
total: number;
|
total: number;
|
||||||
items: FlatFeeTypeItem[] | FeeTypeNode[];
|
items: FlatFeeTypeItem[] | FeeTypeNode[];
|
||||||
rawTree: FeeTypeNode[];
|
rawTree: FeeTypeNode[];
|
||||||
|
ids: string[];
|
||||||
}> {
|
}> {
|
||||||
const rawTree = options.all
|
const rawTree = options.all
|
||||||
? await getFullFeeTypeTree(client, corpId)
|
? await getFullFeeTypeTree(client, corpId)
|
||||||
: await getActiveFeeTypeTree(client, corpId);
|
: await getActiveFeeTypeTree(client, corpId);
|
||||||
|
|
||||||
let flat = flattenFeeTypeTree(rawTree);
|
let flat = options.subtreeParentId
|
||||||
|
? collectSubtreeNodes(rawTree, options.subtreeParentId)
|
||||||
|
: flattenFeeTypeTree(rawTree);
|
||||||
|
|
||||||
if (options.keyword?.trim()) {
|
if (options.keyword?.trim()) {
|
||||||
const kw = options.keyword.trim().toLowerCase();
|
const kw = options.keyword.trim().toLowerCase();
|
||||||
@@ -145,10 +183,14 @@ export async function listFeeTypes(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ids = flat.map((item) => item.id);
|
||||||
|
const useFlat = options.flat || Boolean(options.subtreeParentId) || Boolean(options.idsOnly);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
total: flat.length,
|
total: flat.length,
|
||||||
items: options.flat ? flat : (options.keyword ? flat : rawTree),
|
items: useFlat ? flat : (options.keyword ? flat : rawTree),
|
||||||
rawTree,
|
rawTree,
|
||||||
|
ids,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -151,6 +151,8 @@ export interface FeeTypeQueryOptions {
|
|||||||
all?: boolean;
|
all?: boolean;
|
||||||
keyword?: string;
|
keyword?: string;
|
||||||
flat?: boolean;
|
flat?: boolean;
|
||||||
|
subtreeParentId?: string;
|
||||||
|
idsOnly?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FeeTypeView {
|
export interface FeeTypeView {
|
||||||
|
|||||||
@@ -240,7 +240,16 @@ export async function listRunningJobs(
|
|||||||
const response = await client.get("api/easo/jobs/running", {
|
const response = await client.get("api/easo/jobs/running", {
|
||||||
searchParams: { pipelineId, runType },
|
searchParams: { pipelineId, runType },
|
||||||
});
|
});
|
||||||
return unwrap(response, z.array(WorkflowJobSchema));
|
const json = (await response.json()) as { code?: number; data?: unknown };
|
||||||
|
const rawData = json?.data;
|
||||||
|
if (!rawData) return [];
|
||||||
|
if (Array.isArray(rawData)) {
|
||||||
|
return z.array(WorkflowJobSchema).parse(rawData);
|
||||||
|
}
|
||||||
|
if (typeof rawData === "object") {
|
||||||
|
return [WorkflowJobSchema.parse(rawData)];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getJob(
|
export async function getJob(
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { FieldMappingSchema, EkuaibaoDatalinkCreateTaskSchema } from "./types.js";
|
||||||
|
|
||||||
|
describe("FieldMappingSchema 字段映射验证与序列化", () => {
|
||||||
|
it("正确解析仅含 key 的映射项", () => {
|
||||||
|
const raw = { key: "E_field_1" };
|
||||||
|
const parsed = FieldMappingSchema.parse(raw);
|
||||||
|
expect(parsed.key).toBe("E_field_1");
|
||||||
|
expect(parsed.value).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("正确保留 value 表达式,不被剥离丢失 (防止 Piper 报错金额/必填字段为空)", () => {
|
||||||
|
const raw = {
|
||||||
|
key: "E_e716b9f4b67179b1fbc0_费用金额",
|
||||||
|
value: "control_stssrn.item.amortizationAmount",
|
||||||
|
};
|
||||||
|
const parsed = FieldMappingSchema.parse(raw);
|
||||||
|
expect(parsed.key).toBe("E_e716b9f4b67179b1fbc0_费用金额");
|
||||||
|
expect(parsed.value).toBe("control_stssrn.item.amortizationAmount");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("正确保留复杂对象/数组或数字类型的 value 与扩展属性", () => {
|
||||||
|
const raw = {
|
||||||
|
key: "E_nested_field",
|
||||||
|
value: { subKey: "action_1.output", defaultVal: 100 },
|
||||||
|
type: "relateEntity",
|
||||||
|
required: true,
|
||||||
|
};
|
||||||
|
const parsed = FieldMappingSchema.parse(raw);
|
||||||
|
expect(parsed.key).toBe("E_nested_field");
|
||||||
|
expect(parsed.value).toEqual({ subKey: "action_1.output", defaultVal: 100 });
|
||||||
|
expect((parsed as any).type).toBe("relateEntity");
|
||||||
|
expect((parsed as any).required).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("在 EkuaibaoDatalinkCreateTaskSchema 节点中完整保留所有字段映射的 key 与 value", () => {
|
||||||
|
const node = {
|
||||||
|
name: "action_create_test",
|
||||||
|
label: "创建摊销台账",
|
||||||
|
type: "ekuaibao-datalink-create",
|
||||||
|
groupName: "DEFAULT",
|
||||||
|
orderIndex: 1,
|
||||||
|
levelIndex: [1],
|
||||||
|
status: "NORMAL",
|
||||||
|
mode: "NORMAL",
|
||||||
|
entityId: "e716b9f4b67179b1fbc0",
|
||||||
|
combineFilters: { condition: "AND", filters: [] },
|
||||||
|
filters: [],
|
||||||
|
fields: [
|
||||||
|
{ key: "E_e716b9f4b67179b1fbc0_name", value: "control_stssrn.item.title" },
|
||||||
|
{ key: "E_e716b9f4b67179b1fbc0_费用金额", value: "control_stssrn.item.amortizationAmount" },
|
||||||
|
{ key: "E_e716b9f4b67179b1fbc0_摊销月份", value: "control_stssrn.item.amortizationMonth" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const parsed = EkuaibaoDatalinkCreateTaskSchema.parse(node);
|
||||||
|
expect(parsed.fields).toHaveLength(3);
|
||||||
|
expect(parsed.fields[0].value).toBe("control_stssrn.item.title");
|
||||||
|
expect(parsed.fields[1].value).toBe("control_stssrn.item.amortizationAmount");
|
||||||
|
expect(parsed.fields[2].value).toBe("control_stssrn.item.amortizationMonth");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -64,11 +64,11 @@ export const FilterGroupSchema: z.ZodType<any> = z.lazy(() =>
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// 字段映射条目的两种形态:只读 key 或 key-value 映射
|
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
|
||||||
export const FieldMappingSchema = z.union([
|
export const FieldMappingSchema = z.object({
|
||||||
z.object({ key: z.string() }),
|
key: z.string(),
|
||||||
z.object({ key: z.string(), value: z.string() }),
|
value: z.any().optional(),
|
||||||
]);
|
}).passthrough();
|
||||||
|
|
||||||
// 错误处理配置
|
// 错误处理配置
|
||||||
export const OnErrorSchema = z.object({
|
export const OnErrorSchema = z.object({
|
||||||
@@ -188,6 +188,11 @@ export const FlowCreateTaskSchema = BaseTaskSchema.extend({
|
|||||||
onError: OnErrorSchema.optional(),
|
onError: OnErrorSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const DynamicDelayTaskSchema = BaseTaskSchema.extend({
|
||||||
|
type: z.literal("task-dynamic-delay"),
|
||||||
|
sleepTime: z.union([z.number(), z.string()]).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
// 兜底节点:遇到未收录类型时仍保留全部字段
|
// 兜底节点:遇到未收录类型时仍保留全部字段
|
||||||
export const UnknownTaskSchema = z
|
export const UnknownTaskSchema = z
|
||||||
.object({
|
.object({
|
||||||
@@ -217,6 +222,7 @@ export const WorkflowTaskSchema: z.ZodType<WorkflowTask> = z.union([
|
|||||||
EkuaibaoDatalinkCreateTaskSchema,
|
EkuaibaoDatalinkCreateTaskSchema,
|
||||||
DataConvertTaskSchema,
|
DataConvertTaskSchema,
|
||||||
FlowCreateTaskSchema,
|
FlowCreateTaskSchema,
|
||||||
|
DynamicDelayTaskSchema,
|
||||||
UnknownTaskSchema,
|
UnknownTaskSchema,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -351,14 +357,33 @@ export const WorkflowChargeSchema = z.object({
|
|||||||
|
|
||||||
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
||||||
|
|
||||||
export const WorkflowJobSchema = z.object({
|
export const WorkflowJobSchema = z
|
||||||
id: z.string(),
|
.object({
|
||||||
pipelineId: z.string(),
|
id: z.string().optional(),
|
||||||
status: z.string().default(""),
|
jobId: z.string().optional(),
|
||||||
startTime: z.union([z.string(), z.number()]).optional(),
|
pipelineId: z.string().nullish().default(""),
|
||||||
endTime: z.union([z.string(), z.number()]).optional(),
|
jobName: z.string().nullish(),
|
||||||
triggerType: z.string().default(""),
|
status: z.string().default(""),
|
||||||
});
|
runType: z.string().default(""),
|
||||||
|
executeTime: z.union([z.string(), z.number()]).nullish(),
|
||||||
|
startTime: z.union([z.string(), z.number()]).nullish(),
|
||||||
|
endTime: z.union([z.string(), z.number()]).nullish(),
|
||||||
|
triggerType: z.string().default(""),
|
||||||
|
successTaskCount: z.number().nullish().default(0),
|
||||||
|
errorTaskCount: z.number().nullish().default(0),
|
||||||
|
hasError: z.union([z.string(), z.boolean()]).nullish(),
|
||||||
|
state: z.union([z.number(), z.string()]).nullish(),
|
||||||
|
autoPublish: z.boolean().nullish(),
|
||||||
|
version: z.string().nullish(),
|
||||||
|
snapshotId: z.string().nullish(),
|
||||||
|
})
|
||||||
|
.passthrough()
|
||||||
|
.transform((val) => ({
|
||||||
|
...val,
|
||||||
|
id: val.id || val.jobId || "",
|
||||||
|
jobId: val.jobId || val.id || "",
|
||||||
|
pipelineId: val.pipelineId || "",
|
||||||
|
}));
|
||||||
|
|
||||||
export const WorkflowJobDetailSchema = z
|
export const WorkflowJobDetailSchema = z
|
||||||
.object({
|
.object({
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
|
|||||||
## CLI 常用命令
|
## CLI 常用命令
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
hose-use workflow list [--platform-id=<id>|--app-id=<id>] [-q|--keyword=<关键词>] [--full]
|
||||||
hose-use workflow get <pipelineId>
|
hose-use workflow get <pipelineId>
|
||||||
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
|
||||||
hose-use workflow analyze <pipelineId> [--json]
|
hose-use workflow analyze <pipelineId> [--json]
|
||||||
@@ -33,6 +33,8 @@ hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--s
|
|||||||
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||||
|
|
||||||
## 触发器分类与调测路径分支 (Path Branching)
|
## 触发器分类与调测路径分支 (Path Branching)
|
||||||
|
|
||||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||||
@@ -156,6 +158,6 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
|||||||
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
|
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
|
||||||
|
|
||||||
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
||||||
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断,防止运行时直接返回 403 Forbidden;
|
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
|
||||||
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
|
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
|
||||||
4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。
|
4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。
|
||||||
@@ -50,6 +50,7 @@ const KNOWN_TYPES = new Set([
|
|||||||
"ekuaibao-datalink-delete-trigger",
|
"ekuaibao-datalink-delete-trigger",
|
||||||
"data-convert",
|
"data-convert",
|
||||||
"flow-create-task",
|
"flow-create-task",
|
||||||
|
"task-dynamic-delay",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function referencesFromTask(task: WorkflowTask): string[] {
|
function referencesFromTask(task: WorkflowTask): string[] {
|
||||||
@@ -617,28 +618,42 @@ export function analyzeWorkflow(
|
|||||||
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
|
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
|
||||||
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
|
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
|
||||||
if (powerCodeMatch) {
|
if (powerCodeMatch) {
|
||||||
const powerCode = decodeURIComponent(powerCodeMatch[1]);
|
let powerCode: string | undefined;
|
||||||
const powerCodeKey = powerCode.trim().toLowerCase();
|
try {
|
||||||
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
|
powerCode = decodeURIComponent(powerCodeMatch[1]);
|
||||||
|
} catch {
|
||||||
|
addDiagnostic(diagnostics, {
|
||||||
|
severity: "error",
|
||||||
|
category: "hard_block",
|
||||||
|
code: "INVALID_POWER_CODE_ENCODING",
|
||||||
|
path,
|
||||||
|
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 中 powerCode 参数包含无效的百分号转义 [${powerCodeMatch[1]}],无法校验功能权限。请修正为有效的 URL 编码。`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (openedPowerCodeSet !== undefined) {
|
if (powerCode !== undefined) {
|
||||||
if (!openedPowerCodeSet.has(powerCodeKey)) {
|
const powerCodeKey = powerCode.trim().toLowerCase();
|
||||||
|
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
|
||||||
|
|
||||||
|
if (openedPowerCodeSet !== undefined) {
|
||||||
|
if (!openedPowerCodeSet.has(powerCodeKey)) {
|
||||||
|
addDiagnostic(diagnostics, {
|
||||||
|
severity: "error",
|
||||||
|
category: "hard_block",
|
||||||
|
code: "UNLICENSED_POWER_CODE",
|
||||||
|
path,
|
||||||
|
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
addDiagnostic(diagnostics, {
|
addDiagnostic(diagnostics, {
|
||||||
severity: "error",
|
severity: "warning",
|
||||||
category: "hard_block",
|
category: "soft_advice",
|
||||||
code: "UNLICENSED_POWER_CODE",
|
code: "POWER_CODE_DEPENDENCY",
|
||||||
path,
|
path,
|
||||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
|
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
addDiagnostic(diagnostics, {
|
|
||||||
severity: "warning",
|
|
||||||
category: "soft_advice",
|
|
||||||
code: "POWER_CODE_DEPENDENCY",
|
|
||||||
path,
|
|
||||||
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -361,5 +361,41 @@ describe("Workflow static analysis", () => {
|
|||||||
expect(diag?.category).toBe("soft_advice");
|
expect(diag?.category).toBe("soft_advice");
|
||||||
expect(diag?.severity).toBe("warning");
|
expect(diag?.severity).toBe("warning");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("diagnoses malformed powerCode encoding and continues checking later nodes", () => {
|
||||||
|
const wf = {
|
||||||
|
id: "wf-invalid-power-code-encoding",
|
||||||
|
label: "权限代码编码异常",
|
||||||
|
state: 1,
|
||||||
|
version: "1",
|
||||||
|
tasks: [
|
||||||
|
{
|
||||||
|
name: "action_invalid",
|
||||||
|
type: "http",
|
||||||
|
label: "无效权限代码",
|
||||||
|
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=bad%value",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "action_encoded",
|
||||||
|
type: "http",
|
||||||
|
label: "编码权限代码",
|
||||||
|
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=custom%20power",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = analyzeWorkflow(wf as any);
|
||||||
|
const invalidEncoding = result.diagnostics.find((d) => d.code === "INVALID_POWER_CODE_ENCODING");
|
||||||
|
const dependency = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
|
||||||
|
|
||||||
|
expect(invalidEncoding?.severity).toBe("error");
|
||||||
|
expect(invalidEncoding?.category).toBe("hard_block");
|
||||||
|
expect(invalidEncoding?.path).toBe("0");
|
||||||
|
expect(invalidEncoding?.message).toContain("无效的百分号转义");
|
||||||
|
expect(dependency?.path).toBe("1");
|
||||||
|
expect(dependency?.message).toContain("custom power");
|
||||||
|
expect(result.summary.hardBlocks).toBe(1);
|
||||||
|
expect(result.summary.softAdvices).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -175,6 +175,21 @@ export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions>
|
|||||||
...options.extra,
|
...options.extra,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
case "task-dynamic-delay":
|
||||||
|
case "delay":
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
type: "task-dynamic-delay",
|
||||||
|
label: options.label || "延迟执行节点",
|
||||||
|
desc: options.desc || "在工作流中暂停等待指定秒数",
|
||||||
|
groupName: "action",
|
||||||
|
orderIndex: 0,
|
||||||
|
levelIndex: [0],
|
||||||
|
status: "active",
|
||||||
|
sleepTime: options.extra?.sleepTime ?? 60,
|
||||||
|
...options.extra,
|
||||||
|
};
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return {
|
return {
|
||||||
name,
|
name,
|
||||||
@@ -295,3 +310,45 @@ export function removeWorkflowTask(
|
|||||||
reindexTasks(cloned.tasks);
|
reindexTasks(cloned.tasks);
|
||||||
return { workflow: cloned, removedTask };
|
return { workflow: cloned, removedTask };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type MappingContent = Array<Record<string, any>> | Record<string, any>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量映射节点字段配置 (支持数组格式替换 fields,或对象格式深度设置属性)
|
||||||
|
*/
|
||||||
|
export function applyNodeMapping(
|
||||||
|
workflow: WorkflowDetail,
|
||||||
|
targetKey: string | number,
|
||||||
|
mapping: MappingContent
|
||||||
|
): { workflow: WorkflowDetail; editedTask: WorkflowTask; changedKeys: string[] } {
|
||||||
|
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
|
||||||
|
if (!cloned.tasks) cloned.tasks = [];
|
||||||
|
|
||||||
|
const target = findWorkflowTask(cloned.tasks, targetKey);
|
||||||
|
if (!target) {
|
||||||
|
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { task } = target;
|
||||||
|
const changedKeys: string[] = [];
|
||||||
|
|
||||||
|
if (Array.isArray(mapping)) {
|
||||||
|
// 数组格式直接更新/替换 fields 数组
|
||||||
|
(task as any).fields = mapping;
|
||||||
|
changedKeys.push(`fields (${mapping.length} 项)`);
|
||||||
|
} else if (mapping && typeof mapping === "object") {
|
||||||
|
// 对象格式:合并/设置每个顶层键
|
||||||
|
for (const [key, value] of Object.entries(mapping)) {
|
||||||
|
(task as any)[key] = value;
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
changedKeys.push(`${key} (${value.length} 项)`);
|
||||||
|
} else {
|
||||||
|
changedKeys.push(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new ValidationError("映射内容必须为 JSON 数组或 JSON 对象");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { workflow: cloned, editedTask: task, changedKeys };
|
||||||
|
}
|
||||||
@@ -30,6 +30,10 @@ export function summarizeTask(task: WorkflowTask): string {
|
|||||||
if (task.type === "stop") {
|
if (task.type === "stop") {
|
||||||
return "阻断终止流程";
|
return "阻断终止流程";
|
||||||
}
|
}
|
||||||
|
if (task.type === "task-dynamic-delay") {
|
||||||
|
const sleep = (task as any).sleepTime;
|
||||||
|
return sleep !== undefined && sleep !== null ? `延迟等待: ${sleep} 秒` : "延迟等待节点";
|
||||||
|
}
|
||||||
if (task.type === "ekuaibao-datalink-create-trigger") {
|
if (task.type === "ekuaibao-datalink-create-trigger") {
|
||||||
return "业务对象台账新增触发";
|
return "业务对象台账新增触发";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
lintMvelCode,
|
lintMvelCode,
|
||||||
lintWorkflowScripts,
|
lintWorkflowScripts,
|
||||||
executeJavaScriptSandbox,
|
executeJavaScriptSandbox,
|
||||||
|
executeMvelSandbox,
|
||||||
} from "./index.js";
|
} from "./index.js";
|
||||||
import type { WorkflowDetail } from "../../types.js";
|
import type { WorkflowDetail } from "../../types.js";
|
||||||
|
|
||||||
@@ -164,6 +165,27 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
|
|||||||
expect(res.durationMs).toBeGreaterThanOrEqual(0);
|
expect(res.durationMs).toBeGreaterThanOrEqual(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("supports accessing variables through inputs namespace as well as top-level globals", async () => {
|
||||||
|
const code = `
|
||||||
|
return {
|
||||||
|
direct: foo,
|
||||||
|
viaNamespace: inputs.foo,
|
||||||
|
nested: inputs.nested.value
|
||||||
|
};
|
||||||
|
`;
|
||||||
|
const inputs = {
|
||||||
|
foo: "bar",
|
||||||
|
nested: { value: 42 }
|
||||||
|
};
|
||||||
|
const res = await executeJavaScriptSandbox(code, inputs);
|
||||||
|
expect(res.success).toBe(true);
|
||||||
|
expect(res.returnValue).toEqual({
|
||||||
|
direct: "bar",
|
||||||
|
viaNamespace: "bar",
|
||||||
|
nested: 42
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("catches runtime errors and reports line number", async () => {
|
it("catches runtime errors and reports line number", async () => {
|
||||||
const code = `
|
const code = `
|
||||||
const a = 10;
|
const a = 10;
|
||||||
@@ -254,4 +276,30 @@ describe("isolated script runtime boundaries", () => {
|
|||||||
expect((await executeJavaScriptSandbox('return Promise.resolve(1);')).success).toBe(false);
|
expect((await executeJavaScriptSandbox('return Promise.resolve(1);')).success).toBe(false);
|
||||||
expect((await executeJavaScriptSandbox('return 1;')).returnValue).toBe(1);
|
expect((await executeJavaScriptSandbox('return 1;')).returnValue).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("executeMvelSandbox", () => {
|
||||||
|
it("executes basic MVEL variable assignments, collections and return statements", async () => {
|
||||||
|
const mvel = [
|
||||||
|
'String planCode = "AMORT-001";',
|
||||||
|
'int periods = 3;',
|
||||||
|
'Map row = new HashMap();',
|
||||||
|
'row.put("code", planCode);',
|
||||||
|
'row.put("periods", periods);',
|
||||||
|
'return row;',
|
||||||
|
].join("\n");
|
||||||
|
const result = await executeMvelSandbox(mvel);
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.returnValue).toEqual({ code: "AMORT-001", periods: 3 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accesses inputs in MVEL code", async () => {
|
||||||
|
const mvel = [
|
||||||
|
'int total = amount * 2;',
|
||||||
|
'return total;',
|
||||||
|
].join("\n");
|
||||||
|
const result = await executeMvelSandbox(mvel, { amount: 50 });
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.returnValue).toBe(100);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -51,6 +51,11 @@ export async function executeJavaScriptSandbox(
|
|||||||
const value = vm.getProp(parsed.value, key);
|
const value = vm.getProp(parsed.value, key);
|
||||||
try { vm.setProp(vm.global, key, value); } finally { value.dispose(); }
|
try { vm.setProp(vm.global, key, value); } finally { value.dispose(); }
|
||||||
}
|
}
|
||||||
|
// 同时挂载 inputs 命名空间,支持脚本直接通过 inputs.xxx 访问输入对象
|
||||||
|
if (!Object.hasOwn(inputs, "inputs")) {
|
||||||
|
const dup = parsed.value.dup();
|
||||||
|
try { vm.setProp(vm.global, "inputs", dup); } finally { dup.dispose(); }
|
||||||
|
}
|
||||||
} finally { parsed.value.dispose(); }
|
} finally { parsed.value.dispose(); }
|
||||||
|
|
||||||
const recordLog = (args: Parameters<typeof vm.dump>) => {
|
const recordLog = (args: Parameters<typeof vm.dump>) => {
|
||||||
@@ -117,3 +122,54 @@ export async function executeJavaScriptSandbox(
|
|||||||
runtime?.dispose();
|
runtime?.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真
|
||||||
|
*/
|
||||||
|
export function transpileMvelToJs(mvelCode: string): string {
|
||||||
|
let js = mvelCode;
|
||||||
|
|
||||||
|
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
|
||||||
|
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
|
||||||
|
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
|
||||||
|
|
||||||
|
// 2. 转换 new HashMap() / new ArrayList()
|
||||||
|
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
|
||||||
|
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
|
||||||
|
|
||||||
|
// 3. 常见 Map/List 方法调用模拟:
|
||||||
|
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
|
||||||
|
// 注入轻量 helper
|
||||||
|
const preamble = [
|
||||||
|
"function _mvel_put(obj, key, val) { if (obj && typeof obj === 'object') { obj[key] = val; } return val; }",
|
||||||
|
"function _mvel_get(obj, key) { return obj ? obj[key] : undefined; }",
|
||||||
|
"function _mvel_size(obj) { if (!obj) return 0; if (Array.isArray(obj)) return obj.length; if (typeof obj === 'object') return Object.keys(obj).length; return 0; }",
|
||||||
|
"function _mvel_add(arr, item) { if (Array.isArray(arr)) arr.push(item); return arr; }",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, ""); // 避免直接正则冲突,使用下面逐行或更精确替换
|
||||||
|
// 恢复并使用 helper
|
||||||
|
js = mvelCode;
|
||||||
|
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
|
||||||
|
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
|
||||||
|
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
|
||||||
|
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
|
||||||
|
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, "[$1] = $2");
|
||||||
|
js = js.replace(/\.size\s*\(\s*\)/g, ".length");
|
||||||
|
|
||||||
|
return `${preamble}${js}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轻量仿真执行 MVEL 节点
|
||||||
|
*/
|
||||||
|
export async function executeMvelSandbox(
|
||||||
|
code: string,
|
||||||
|
inputs: Record<string, unknown> = {},
|
||||||
|
options: { timeoutMs?: number } = {}
|
||||||
|
): Promise<ScriptEvalResult> {
|
||||||
|
const transpiled = transpileMvelToJs(code);
|
||||||
|
const result = await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -7,11 +7,13 @@ export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<str
|
|||||||
const rawStatus = (job as any).status;
|
const rawStatus = (job as any).status;
|
||||||
const rawState = (job as any).state;
|
const rawState = (job as any).state;
|
||||||
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
if (typeof rawStatus === "string" && rawStatus.trim()) {
|
||||||
return rawStatus.trim().toUpperCase();
|
const s = rawStatus.trim().toUpperCase();
|
||||||
|
if (s === "STARTED") return "RUNNING";
|
||||||
|
return s;
|
||||||
}
|
}
|
||||||
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
|
||||||
if (rawState === 1 || rawState === "1") return "RUNNING";
|
if (rawState === 1 || rawState === "1") return "RUNNING";
|
||||||
if (rawState === 2 || rawState === "2") return "FAILED";
|
if (rawState === 2 || rawState === "2") return "FAILED";
|
||||||
|
if (rawState === 0 || rawState === "0") return "COMPLETED";
|
||||||
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
|
||||||
return "UNKNOWN";
|
return "UNKNOWN";
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user