Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8571390f15 | ||
|
|
e98463ab23 | ||
|
|
7ac52e7981 | ||
|
|
a7974abb08 | ||
|
|
0f164b6de5 | ||
|
|
a6e4836d2a | ||
|
|
39a5a7e669 | ||
|
|
ebcebbfffc | ||
|
|
af7362a346 | ||
|
|
a797196caa | ||
|
|
dda9b2c7a0 | ||
|
|
3c00a0c0a6 | ||
|
|
1de9e3f552 | ||
|
|
258b347d4d | ||
|
|
782466ad80 | ||
|
|
9d7df10994 | ||
|
|
5d1e3e5d8e | ||
|
|
6628a546c5 | ||
|
|
4d921c09b3 | ||
|
|
3fee9a2a6f | ||
|
|
32a509aa0e | ||
|
|
ad771e92e0 | ||
|
|
1739daacf2 | ||
|
|
1c2e97486b | ||
|
|
a5f685045e | ||
|
|
fbdb38bfb2 | ||
|
|
f834822f36 | ||
|
|
37f5e5c74b | ||
|
|
fa55e45acd | ||
|
|
975f76af74 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.18",
|
||||
"version": "0.8.21",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.18)
|
||||
# hose-use (v0.8.21)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+742
-623
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
||||
Bundled 356 modules in 32ms
|
||||
|
||||
server.js 3.1 MB (entry point)
|
||||
|
||||
✓ Successfully bundled MCP server: /Users/yingqing/.codex/worktrees/f55d/hose-use/dist/mcp/server.js
|
||||
$ node scripts/build-plugin.mjs
|
||||
Whitespace-only changes.
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"corpId": "ID01ofWoOC1wiX",
|
||||
"corpName": "沈玥妍测试企业",
|
||||
"readOnly": true,
|
||||
"checks": [
|
||||
{
|
||||
"name": "workflow-list",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"count": 14
|
||||
},
|
||||
{
|
||||
"name": "workflow-detail",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"taskCount": 4
|
||||
},
|
||||
{
|
||||
"name": "workflow-analyze",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"summary": {
|
||||
"total": 1,
|
||||
"hardBlocks": 0,
|
||||
"softAdvices": 1,
|
||||
"passed": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "workflow-has-error",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"count": 0
|
||||
},
|
||||
{
|
||||
"name": "platform-schema",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"entityCount": 2,
|
||||
"fieldCount": 6
|
||||
},
|
||||
{
|
||||
"name": "bill-trace-legacy-option",
|
||||
"exitCode": 0,
|
||||
"jsonParsed": true,
|
||||
"found": true,
|
||||
"billCode": "B26000022",
|
||||
"compatibilityNotice": true,
|
||||
"sameResultAsWithoutFlag": true,
|
||||
"baselineExitCode": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
$ tsc --noEmit
|
||||
@@ -0,0 +1,70 @@
|
||||
# 2026-10-25 Codex GitHub 审查意见修复完成报告
|
||||
|
||||
日期:2026-10-25(Asia/Shanghai)。分支:`fix/codex-review-findings`。修复基线:`main@0f164b6`。
|
||||
|
||||
## 交付结果
|
||||
|
||||
最近 10 个 PR 中的 16 条已核实意见均已落实对应修复或明确的兼容处置。通过 3 个子智能体分别实现工作流、接口身份、CLI,并由主控整合和最终复核;独立交叉审查额外发现并修正了 JWT 非法管理员值的归一化问题,真实测试企业回归又发现并修正了 JSON 脱敏破坏布尔标记的问题。
|
||||
|
||||
最终 `bun test` 为 **842 pass / 0 fail,108 个测试文件,3986 次断言**;`bun run check` 通过;插件构建成功;源码与重建插件的离线执行契约测试通过。真实接口只在**沈玥妍测试企业**读取既有数据,未创建、提交、审批、修改或删除真实业务数据。
|
||||
|
||||
本次从主分支选择性复用旧 `fix/review-20261023` 的集合转换和引用扫描思路,没有合并旧提交中单据创建、复制、校验等其他修改。旧分支保持原状;以后合入时应单独审查重叠文件。
|
||||
|
||||
## 逐项实际修改及行为差异
|
||||
|
||||
| 编号 / 原评论 | 实际修改与原因 | 修复前 → 修复后 |
|
||||
|---|---|---|
|
||||
| R01 [#142 file 别名](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311509) | [node.ts](../../src/cli/commands/workflow/node.ts):edit 的映射别名移除 file,保留 mapping-file/mapping/json-file,恢复原有代码别名 | edit --file=script.js 被 JSON.parse 拒绝 → 按代码文件读取;独立 node map --file 继续读映射 |
|
||||
| R02 [#142 完整构造器名](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311517) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts)、[sandbox.ts](../../src/domains/platform/workflow/script/sandbox.ts):按 token 精确识别零参 java.util.HashMap/ArrayList,避免全文替换影响字面量 | java 未定义 → 与已有短名得到一致 Map/List 结果;其他构造器明确不支持 |
|
||||
| R03 [#142 末尾表达式](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311526) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts)、[lint-mvel.ts](../../src/domains/platform/workflow/script/lint-mvel.ts):识别可确定的最后顶层表达式,单次 return 求值,lint 接受此语义 | result; 成功但 undefined → 返回真实结果;复杂末项完成值明确报 UnsupportedMvelSyntax |
|
||||
| R04 [#142 Map.size](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311532) | [mvel-subset.ts](../../src/domains/platform/workflow/script/mvel-subset.ts):Map/List helper 区分自身键数和元素数,处理嵌套调用及方法返回值 | 一个键的 Map 得 undefined → 得 1;覆盖同键不增加计数,length/原型名称键也正确 |
|
||||
| R05 [#142 嵌套摘要](https://github.com/yunyingk/hose-use/pull/142#discussion_r4356311540) | [shared.ts](../../src/cli/commands/workflow/shared.ts):默认复用现有 flattenExecutionTree,保持 test/job 相同容器语义 | 条件/循环内代码节点摘要缺失 → 展开并保留每次执行,不按名称去重 |
|
||||
| R06 [#139 发票超时](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394125) | [bill/api.ts](../../src/domains/bill/api.ts)、[tools.ts](../../src/domains/bill/tools.ts):可选 signal、retry:0、逐票 3 秒整体 deadline、abort 与 finally 清理 | 提前返回后请求/计时器仍存活 → 请求和响应体可被取消,计时器必清;迟到结果不污染返回字典 |
|
||||
| R07 [#139 无效发票参数](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394145) | [search.ts](../../src/cli/commands/bill/search.ts)、[metadata](../../src/cli/command-metadata.ts)、[flow.ts](../../src/cli/commands/flow.ts):旧参数保留接受、明确兼容空操作并给 stderr 提示;SDK 兼容签名保留 | 假装参数控制详情加载 → 说明 trace 本身不补充发票详情;结果 JSON/退出码保持一致,不增加网络补全 |
|
||||
| R08 [#139 物理字段键](https://github.com/yunyingk/hose-use/pull/139#discussion_r4347394152) | [app-info.ts](../../src/cli/commands/platform/app-info.ts):文本物理列改为 fieldKey ?? name | name 与 fieldKey 不同时误导复制 → 显示真实物理键;JSON 原字段保持原样 |
|
||||
| R09 [#145 表单容器](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575334) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):覆盖 inputs/fields/mapping/form 及对象/数组组合,明确字段条目只扫 value | 直接 form、inputs.form 漏检 → 与普通 fields 得到一致诊断;脚本、条目 label/type 元信息不扫描 |
|
||||
| R10 [#145 choose 表示](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575344) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):解析 JSON、单双引号/裸路径、多标签、转义;按明确节点/上下文/未知来源分类 | 非 JSON 形式静默跳过 → 缺失明确节点硬阻断,body 等非 descriptor 上下文保留;未知根/畸形表达式软提示 |
|
||||
| R11 [#145 trigger_1](https://github.com/yunyingk/hose-use/pull/145#discussion_r4358575352) | [analyzer.ts](../../src/domains/platform/workflow/analysis/analyzer.ts):删除固定豁免,统一依赖真实节点索引 | 缺失 trigger_1 仍 passed → 缺失阻断、实际存在通过;不自动替换成其他触发器 |
|
||||
| R12 [#136 业务错误](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138930) | [platform/api.ts](../../src/domains/platform/api.ts)、[pipeline-watcher.ts](../../src/domains/platform/workflow/watch/pipeline-watcher.ts):共用业务错误检查先于列表归一化,watcher 两处 running 鉴权异常重抛 | code:401/data:null 被当[] → AuthenticationError;成功空值/单对象/数组兼容不变,CLI 不再把该鉴权错误当零任务成功 |
|
||||
| R13 [#136 在途错误](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138939) | [history.ts](../../src/cli/commands/workflow/history.ts):拆开含错与终态谓词,错误列优先显示明确错误 | RUNNING+errorTaskCount>0 被 --has-error 排除 → 保留;state 过滤和计数维持既有兼容行为 |
|
||||
| R14 [#136 未知状态](https://github.com/yunyingk/hose-use/pull/136#discussion_r4335138947) | [job.ts](../../src/cli/commands/workflow/job.ts):四处状态展示共用已知/未知判断 | detail 不可读显示已停用 → 显示未知,保留可用 job/tree;JSON 不捏造 workflow |
|
||||
| R15 [#135 保存 key 回填](https://github.com/yunyingk/hose-use/pull/135#discussion_r4334533782) | [assist services.ts](../../src/domains/assist-platform/services.ts):只回填实际保存目录、同 id/物理企业中完整保留的 key 对 | 磁盘有 keys、运行态没有 → 返回配置/CLI hasOpenApi 与磁盘一致;不恢复旧员工/token/session,不读取其他目录 keys |
|
||||
| R16 [#135 画像完整度](https://github.com/yunyingk/hose-use/pull/135#discussion_r4334533792) | [assist services.ts](../../src/domains/assist-platform/services.ts)、[link-import.ts](../../src/core/auth/link-import.ts):本次确认 boolean admin 后重算缺项与风险,源头严格解析 JWT | 已确认 false 仍不完整 → 清除仅 admin 缺项;null/unknown 等不再被伪装成 false;历史高风险及员工隔离保留 |
|
||||
|
||||
对应的模块 README、内嵌 skill、CLI 帮助均已更新;[插件产物](../../dist/mcp/server.js)从构建生成,包含最终源码和内嵌说明,没有手工修改 bundle。
|
||||
|
||||
## 关键兼容取舍与方案偏差
|
||||
|
||||
1. `node edit --file=<mapping.json>` 的近期调用需要改为 --mapping-file 或 node map --file;恢复的是更早已存在的代码文件别名,不根据扩展名猜用途。
|
||||
2. trace 的旧发票参数被明确为兼容空操作;没有为制造开关效果而新增发票加载。回退单据检索仍可能查 invoice/search,不宣传完全无发票相关请求。
|
||||
3. MVEL 保留原有除法、三元、classic for 等兼容运算。Map.put/get/add 由同组 helper 明确返回语义;不支持的语法从可能静默错算改为明确失败。仍是 QuickJS 子集,不是原生 MVEL/JVM。
|
||||
4. 未知裸 choose 根保持软提示,明确 descriptor 节点键及标准前缀缺失才硬阻断;不会为提高“检出数量”而把所有路径当节点。此处不是完整上游可访问作用域和字段类型分析。
|
||||
5. 两项必要关联修正比初始文件清单增加了范围:独立复核发现 JWT null/unknown 被旧 link-import 转成 false,故收紧其归一化;真实 B26000022 回归发现旧文本脱敏把 keepItSecret:false 改为裸 <redacted> 导致非法 JSON,故在 [printer.ts](../../src/cli/printer.ts) 对完整 JSON 按类型脱敏。凭据字符串、数字及 URL/Bearer 继续遮蔽,业务 boolean/null 和 NDJSON 单行得到保留;普通文本原规则保持。两项均由复现驱动,没有扩大成认证结构或输出协议重构。
|
||||
6. 共享 HTTP 工厂、保存 API 返回类型、state 筛选兼容语义与业务写流程没有重构;原有注释随迁移保留,旧审查证据未覆盖改写。
|
||||
|
||||
## 实际验证
|
||||
|
||||
| 验证 | 实际结果与证据 |
|
||||
|---|---|
|
||||
| 完整测试 | **842 pass / 0 fail,108 文件,3986 断言,9.57 秒**;[完整日志](./2026-10-25-codex-review-evidence/tests.log) |
|
||||
| 类型检查 | `bun run check` exit 0;[日志](./2026-10-25-codex-review-evidence/typecheck.log) |
|
||||
| 插件构建 | `bun run build:plugin` 成功,356 模块,3.1MB;[日志](./2026-10-25-codex-review-evidence/build.log) |
|
||||
| 分发物执行 | [plugin-review-smoke.test.ts](../../scripts/plugin-review-smoke.test.ts)在隔离假企业配置中实际运行源码 CLI 和重建 bundle,验证全限定名集合、Map.size、末尾对象返回、JS 保持及 UnsupportedMvelSyntax 非零退出码;包含在全量测试中 |
|
||||
| 架构边界 | 仓库 architecture-boundaries 测试包含在全量测试中,通过 |
|
||||
| Diff 检查 | `git diff --check` exit 0;[日志](./2026-10-25-codex-review-evidence/diff-check.log) |
|
||||
| 真实只读回归 | 仅沈玥妍测试企业,显式 --corp/--stateless:工作流列表14项、既有4节点流程详情/静态分析、--has-error日志、schema 2对象6字段、既有单据B26000022 trace;全部exit0且JSON可解析。带/不带--basic的trace结果完全一致;[汇总](./2026-10-25-codex-review-evidence/live-readonly.json) |
|
||||
|
||||
新增回归覆盖真实入口、超时后资源生命周期、body读取、401重放、跨目录keys、非法JWT、角色缺项、dry-run无保存、mock保存、状态筛选、嵌套执行和源码/插件一致性。CLI子组还把新回归放回原始HEAD临时副本验证:原实现出现9项失败,修复后通过,避免测试只重复实现。
|
||||
|
||||
首轮全量测试在受限环境出现回环端口、默认SQLite和企业目录写权限失败,不能算通过。最终执行将所有测试配置/账号/企业文件/SQLite隔离到临时目录,并允许本地回环测试后取得以上全绿结果;没有为测试放开真实企业写权限,也未修改你的日常企业配置。
|
||||
|
||||
## 未覆盖及复查重点
|
||||
|
||||
- 真实回归没有发起 Job、创建或提交单据、修改协助身份、发布工作流。401/403、挂起、旧key、字段缺失和非法JWT都用离线mock制造。
|
||||
- 真实 --has-error 样本返回空列表,故在途含错筛选、不可读工作流详情等负面场景由mock证明;未借此宣称所有真实Job状态已覆盖。
|
||||
- 本地 MVEL 不模拟任意 Java 方法、Map字面量、精确JVM数值或末项复合语句完成值;运行错误位置仍来自转换后代码,未实现源位置映射。合思原生引擎特殊语义未在本轮执行验证。
|
||||
- 单票取消信号不撤销已开始的独立认证续期,也不能强制停止忽略AbortSignal的自定义fetch;整体等待及迟到结果隔离有测试覆盖。
|
||||
- 其他 watcher catch、严格FAILED字面语义、schema底层state默认值、gen-props物理键契约、旧分支其他单据修复不在本次扩大。
|
||||
- 重点复查MVEL支持边界、choose未知根软提示、keys来源目录限制,以及JSON脱敏对业务标记与凭据的区分。未把“没有发现问题”当作完整可靠性证明。
|
||||
|
||||
本次未推送、创建PR、合并main、打tag、发布或更新全局安装,也没有发送GitHub评论、关闭旧审查线程。修复应经后续正常PR流程进入主分支;旧机器人线程状态仍需在代码合入并核对后处理。
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.18",
|
||||
"version": "0.8.21",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
test("source and committed plugin preserve offline review execution contracts", () => {
|
||||
const root = resolve(import.meta.dir, "..");
|
||||
const temp = mkdtempSync(join(tmpdir(), "hose-review-plugin-"));
|
||||
try {
|
||||
const enterprises = join(temp, "enterprises");
|
||||
mkdirSync(enterprises);
|
||||
writeFileSync(join(enterprises, "smoke.json"), JSON.stringify({
|
||||
id: "smoke", name: "离线测试企业", env: "test",
|
||||
credentials: { accessToken: "synthetic-offline-token", corpId: "smoke", staffId: "staff" },
|
||||
}));
|
||||
const env = {
|
||||
...process.env,
|
||||
HOSE_ENTERPRISES_DIR: enterprises,
|
||||
HOSE_CONFIG_FILE: join(temp, "config.json"),
|
||||
HOSE_ACCOUNTS_FILE: join(temp, "accounts.json"),
|
||||
HOSE_APPROVAL_DB: ":memory:",
|
||||
};
|
||||
const fixtures = [
|
||||
{ name: "collections", type: "code", code: 'Map m = new java.util.HashMap(); m.put("x", 7); m.size();', value: 1 },
|
||||
{ name: "final-expression", type: "code", code: 'Map m = new HashMap(); m.put("x", 7); m;', value: { x: 7 } },
|
||||
{ name: "javascript", type: "code-js2", code: "return 7;", value: 7 },
|
||||
{ name: "unsupported", type: "code", code: "new java.util.Date();", error: "UnsupportedMvelSyntax" },
|
||||
];
|
||||
for (const fixture of fixtures) {
|
||||
const file = join(temp, `${fixture.name}.script`);
|
||||
writeFileSync(file, fixture.code);
|
||||
for (const entry of [["src/cli.ts"], ["dist/mcp/server.js", "--hose-use-cli"]]) {
|
||||
const result = Bun.spawnSync([
|
||||
process.execPath, ...entry, "workflow", "eval-script", "--file", file,
|
||||
"--type", fixture.type, "--corp", "smoke", "--stateless", "--json",
|
||||
], { cwd: root, env, timeout: 10000 });
|
||||
expect(result.exitCode).toBe(fixture.error ? 1 : 0);
|
||||
const report = JSON.parse(result.stdout.toString());
|
||||
expect(report.success).toBe(!fixture.error);
|
||||
if (fixture.error) expect(report.error.name).toBe(fixture.error);
|
||||
else expect(report.returnValue).toEqual(fixture.value);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rmSync(temp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.18
|
||||
version: 0.8.21
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.18)
|
||||
# hose-use (v0.8.21)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -66,6 +66,20 @@ metadata:
|
||||
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
||||
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
|
||||
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
14. **工作流代码节点文件映射与 Token 防膨胀守则 (Workflow Code Node File Mapping & Zero-Token-Waste Rule)**:
|
||||
- **严禁终端内联大段代码**:在新建或修改工作流代码节点(`code-js2` / `code`)时,**严禁使用 `--code="..."` 或在终端命令(如 `bun -e '...'`)中内联几十上百行的长代码**。内联大段代码会导致命令行参数急剧膨胀,在 Tool Calls 中产生严重的输入输出 Token 浪费,且极易因 Shell 引号转义损坏脚本语法;
|
||||
- **必须走本地文件映射与 `--code-file`**:
|
||||
1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get <pipelineId> <nodeName> > ./scripts/xxx.mvel`;
|
||||
2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token);
|
||||
3. **一键同步**:使用 `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。
|
||||
15. **附件命名与用户协商(Attachment Naming is a Human Decision)**:
|
||||
- 附件文件名属于企业业务习惯,**CLI 不设默认命名规则、不强制格式**;
|
||||
- 上传或重命名附件前,Agent 必须先与用户确认文件名——可以直接沿用原文件名,也可以由用户指定(如"类型-金额/期间-日期");
|
||||
- **不要自行套用历史单据的命名格式**,也不要因为命名与旧单不同而判定错误。
|
||||
16. **业务输入必须来自用户(Never Invent Business Inputs)**:
|
||||
- 驳回原因、转交/加签审批人、提交/撤回/删除、金额与期间等关键业务内容,**必须由用户明确提供或确认**;
|
||||
- **严禁自行编造**驳回意见、审批人、金额、期间等业务输入,也不要用"测试环境驳回(CLI 验证)"之类的占位文案代替;
|
||||
- 用户没有给出时,先停下来询问;宁可多问一句,也不要替客户写业务内容。
|
||||
|
||||
---
|
||||
|
||||
@@ -100,6 +114,12 @@ metadata:
|
||||
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
|
||||
| 草稿字段一致性校验(金额/币种/发票总额/明细草稿状态) | `hose-use bill validate <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据模板列表(默认仅启用,与页面快速新建同源) | `hose-use bill templates [--all] [--keyword=...]` | [references/bill.md](references/bill.md) |
|
||||
| 按模板创建单据草稿(不提交) | `hose-use bill create --template <模板ID> [--title] [--amount] [--reason] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 提交单据送审 | `hose-use bill submit <单号|ID> [--approver=<员工>] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 复制单据为新草稿(清空发票绑定,不提交) | `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 删除草稿单据(仅 draft 状态) | `hose-use bill delete <单号|ID> --yes` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
@@ -161,6 +181,14 @@ hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明
|
||||
hose-use bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
|
||||
hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
|
||||
hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
|
||||
hose-use bill templates # 查看当前可见的启用模板(按分组)
|
||||
hose-use bill templates --all --keyword=报销 # 含停用 + 关键字过滤
|
||||
hose-use bill create --template ID01ok2mM0IroP --amount 0.01 --yes # 按模板建草稿
|
||||
hose-use bill submit B26000019 --approver 沈玥妍 --yes # 提交送审
|
||||
hose-use bill validate B26015505 # 校验草稿派生字段(金额/币种/发票总额)
|
||||
hose-use bill copy B26015505 --title "副本" --dry-run # 预览复制(默认保留附件)
|
||||
hose-use bill copy B26015505 --title "副本" --yes # 复制为新草稿(不提交)
|
||||
hose-use bill delete B26015505 --yes # 删除 draft 草稿(已提交单据会被拒绝)
|
||||
hose-use bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
|
||||
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
@@ -227,8 +255,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 node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
|
||||
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code="return items;" --yes # 声明式追加节点 (--after/--parent 插入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --label="新标题" --yes # 定向修改节点配置
|
||||
hose-use workflow node add wf_01k83y... --type=code-js2 --label="清洗" --code-file=./clean.js --yes # 声明式追加节点 (支持 --code-file 导入)
|
||||
hose-use workflow node edit wf_01k83y... <节点name或#序号> --code-file=./clean.js --yes # 从本地文件同步最新脚本 (推荐,零 Token 浪费)
|
||||
hose-use workflow node rm wf_01k83y... <节点name或#序号> --yes # 安全移除任务节点 (首节点触发器安全防御)
|
||||
hose-use workflow tail wf_01k83y... # 类似 tail -f 实时监听新任务派发与节点执行日志流 (别名 watch, follow)
|
||||
hose-use workflow tail wf_01k83y... --job=<jobId> # 针对单个执行中的 Job 实时跟踪直至终态
|
||||
|
||||
@@ -17,6 +17,12 @@ Generate code for Ekuaibao's modified MVEL 2.x runtime, not JavaScript, Groovy,
|
||||
- For Chinese or dynamic field names, prefer `map.get("字段名")` instead of dot access.
|
||||
- Every `if`, `&&`, and `||` operand must be a strict boolean expression. Never write `if (data)`.
|
||||
|
||||
## Local Evaluation Boundary
|
||||
|
||||
`workflow eval-script` runs a limited MVEL-to-JavaScript subset in isolated QuickJS, not the tenant's JVM engine. It supports zero-argument `HashMap`/`ArrayList` constructors, including `java.util.HashMap`/`java.util.ArrayList`, basic collection methods, explicit return, and a determinable final top-level expression evaluated once. Map size counts own keys; list size counts elements.
|
||||
|
||||
Unsupported constructors, generics, or final compound-statement completion values must be reported as unsupported rather than accepted with an incorrect result. Tenant-proven Map literals, Java methods, and precise JVM numeric behavior may exceed the local subset. Do not rewrite working tenant code merely to satisfy the local evaluator; report the limitation and validate native behavior in an authorized test tenant when needed.
|
||||
|
||||
## Code Node Template
|
||||
|
||||
Use this style when the user has shown bare assignments and final-expression return work:
|
||||
@@ -144,3 +150,11 @@ result;
|
||||
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
|
||||
|
||||
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
|
||||
|
||||
## Deployment & CLI Integration (Zero-Token-Waste Rule)
|
||||
|
||||
- **Always maintain MVEL scripts in local dedicated files** (e.g. `./scripts/node_calc.mvel`), never pass long scripts inline in `--code="..."` or in terminal `bun -e '...'` expressions.
|
||||
- **Local syntax check**: `hose-use workflow lint-script --file=./scripts/node_calc.mvel --type=code`
|
||||
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
|
||||
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
|
||||
|
||||
@@ -54,6 +54,8 @@ hose-use bill get CL20260903001 --json
|
||||
hose-use bill flow CL20260903001
|
||||
```
|
||||
|
||||
`bill trace` / `flow get` 的穿透诊断不补充加载发票详情。旧参数 `--no-invoice` / `--noInvoice` / `--basic` 仍可传入,但不改变结果,CLI 会通过 stderr 说明;未命中流程时的回退检索仍可能查询发票索引。
|
||||
|
||||
在详情中附加风控与合规快照时加 `--risk`。该选项会沿用审批详情页的风控、预算和发票风险接口,并在 JSON 的每个单据项中增加 `risk` 字段:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -247,6 +247,8 @@ hose-use workflow logs <pipelineId> --has-error
|
||||
hose-use workflow logs <pipelineId> --state=FAILED --json
|
||||
```
|
||||
|
||||
`--has-error` 也包含 `RUNNING` / `STARTED` 且已出现错误的任务;`--state` 保留既有终态筛选兼容语义,不替代包含错误筛选,客户端筛选范围为当前返回页。`job` 读取不到工作流详情时显示状态未知;`tail` 的在途任务鉴权失败会返回认证错误,不把它当成没有任务。
|
||||
|
||||
扫描企业内工作流列表中的 `errorCount`,并把已提醒的错误计数保存在本地状态文件;同一错误计数不会重复提醒,错误计数增加时才产生新提醒:
|
||||
|
||||
```bash
|
||||
@@ -321,15 +323,18 @@ hose-use workflow node get <pipelineId> 2 --json
|
||||
|
||||
# 3. 声明式向工作流追加或定向插入新节点 (别名: append, insert)
|
||||
# 默认追加至流程末尾;支持通过 --parent=<容器节点> 插入循环/分支内,或 --after=<节点> 插入指定节点后
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --dry-run
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code="return items.filter(x => x.amount > 0);" --yes
|
||||
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地脚本文件导入代码
|
||||
hose-use workflow node add <pipelineId> --type=code-js2 --label="数据过滤" --code-file=./scripts/filter.js --yes
|
||||
hose-use workflow node add <pipelineId> --type=stop --label="超额阻断" --after=action_dx9cci --yes
|
||||
hose-use workflow node add <pipelineId> --type=http --label="外部通知" --parent=control_every_1 --yes
|
||||
|
||||
# 4. 定向修改指定节点配置 (别名: update, set)
|
||||
# 支持修改 --label, --desc, --code, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --code="return items;" --yes
|
||||
# 支持修改 --label, --desc, --code, --code-file, 或通过 --set="key=value" 定向覆盖任意属性
|
||||
# edit 的 --file 是代码文件别名;JSON 映射使用 --mapping-file,独立 node map 的 --file 仍表示映射文件
|
||||
# 推荐做法(零 Token 浪费 & 避开命令行转义):从本地文件导入脚本
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --dry-run
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --code-file=./scripts/clean.js --yes
|
||||
hose-use workflow node edit <pipelineId> action_dx9cci --label="清洗增强版" --yes
|
||||
hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
|
||||
|
||||
# 5. 安全移除指定任务节点 (别名: remove, delete, del)
|
||||
@@ -371,6 +376,8 @@ hose-use workflow tail <pipelineId> --timeout=60
|
||||
|
||||
合思工作流支持自定义 JavaScript (`code-js2`) 与 MVEL (`code`) 脚本节点。以往只能在生产派发调试 Job 才能验证脚本,不仅污染发布版本快照,还容易因死循环、语法报错或悬空上游节点引发流程中断。`hose-use` 提供了纯本地 AST 语法检查与安全隔离沙箱运行能力:
|
||||
|
||||
MVEL 离线仿真为 QuickJS 转译子集,支持零参 `java.util.HashMap` / `java.util.ArrayList` 和短名、基本集合方法与可确定的末尾表达式;不支持的构造器或完成值会明确报错。原生 MVEL 的其他 Java 方法、集合字面量和 JVM 数值语义仍应以授权测试企业的真实引擎为准,不能把本地成功当作完整兼容保证。工作流调试的代码摘要覆盖嵌套执行实例。
|
||||
|
||||
```bash
|
||||
# 1. 静态扫描整条工作流中所有代码节点的语法、return 语句与上游依赖引用
|
||||
hose-use workflow lint-script <pipelineId>
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.18",
|
||||
"version": "0.8.21",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.18
|
||||
version: 0.8.21
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
|
||||
|
||||
@@ -166,7 +166,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal"
|
||||
},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify offline cached", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"config": {
|
||||
"summary": "全局运行模式与路径配置",
|
||||
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose 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 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 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": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -295,12 +295,19 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"relations": "查看关联单据",
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接"
|
||||
"link": "生成单据详情链接",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
|
||||
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
|
||||
"delete": "删除草稿单据(仅 draft,需 --yes)",
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)",
|
||||
"create": "按模板创建单据草稿(不提交)",
|
||||
"submit": "提交单据送审(会进入审批流)"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
"--yes/--confirm 确认执行审批动作",
|
||||
"--comment=<原因> 驳回或评论内容"
|
||||
"--comment=<原因> 驳回或评论内容",
|
||||
"trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"aliases": [
|
||||
"bills",
|
||||
@@ -339,11 +346,14 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target template title to amount reason fee-type feeType", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
"usage": "hose-use flow <子命令> [单号|ID]",
|
||||
"options": [
|
||||
"get/trace 的 --no-invoice/--noInvoice/--basic 为兼容空操作;穿透诊断本身不补充加载发票详情"
|
||||
],
|
||||
"commands": {
|
||||
"get": "穿透诊断单据流转",
|
||||
"history": "查看审批流转时间线",
|
||||
@@ -368,7 +378,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"show": "get",
|
||||
"find": "get"
|
||||
},
|
||||
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
},
|
||||
"contact": {
|
||||
"summary": "企业通讯录与人员检索",
|
||||
@@ -445,7 +455,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"costtype"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { ...flagList("a all fields flat flatten include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query target title to", "value") }
|
||||
flags: { ...flagList("a all fields flat flatten ids ids-only include-disabled r recursive spec specs table", "boolean"), ...flagList("code color desc description en-name enName icon id keyword name parent parent-id parentId q query subtree subtree-id target title to", "value") }
|
||||
},
|
||||
"role": {
|
||||
"summary": "企业角色定义与成员",
|
||||
@@ -541,6 +551,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"records": "查询记录(支持 --all / --ndjson 流式 / --stats 画像)",
|
||||
"record": "查看或安全修改单条/批量记录 (get/create/edit/batch-edit)",
|
||||
"audit": "业务对象健康度巡检(必填缺失/禁用引用/跨表同步差异)",
|
||||
"gen-props": "生成业务对象字段常量与代码模板 (支持 MVEL / JS)",
|
||||
"permissions": "查看权限",
|
||||
"imports": "查看导入任务",
|
||||
"get": "查看应用详情"
|
||||
@@ -580,11 +591,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"update": "record",
|
||||
"batch-update": "record",
|
||||
"record-recompute": "record",
|
||||
"gen-mvel-props": "gen-props",
|
||||
"props": "gen-props",
|
||||
"permission": "permissions",
|
||||
"auth": "permissions",
|
||||
"import-jobs": "imports"
|
||||
},
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword limit name offset page-size pageSize q query select seq sequence set start sum where", "value") }
|
||||
flags: { ...flagList("a active active-only activeOnly all flat ndjson normalize normalized profile raw state stats stream w workbench", "boolean"), ...flagList("aggregate baseline c check-continuous check-fields checkContinuous checkFields concurrency continuous count d data expect expect-value expectValue f field fields file filter filter-by filterBy form group-by groupBy id ids keyword lang language limit name offset page-size pageSize q query search-field searchField search-fields searchFields select seq sequence set start sum where", "value") }
|
||||
},
|
||||
"app": {
|
||||
"summary": "桌面端工作台应用管理",
|
||||
@@ -819,7 +832,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
@@ -9,6 +9,7 @@ export async function handleTickets(
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const client = resolveAssistClient(parsed, runtime);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const corpId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
|
||||
@@ -17,7 +18,7 @@ export async function handleTickets(
|
||||
if (!corpId) {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -26,7 +27,7 @@ export async function handleTickets(
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ corporationId: corpId, count: tickets.length, tickets }, runtime.outputOptions),
|
||||
stdout: printJson({ corporationId: corpId, count: tickets.length, all: isAll, tickets }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import { buildBillCopyForm, copyBillAsDraft } from "../../../domains/bill/copy.js";
|
||||
import type { BillDraftForm } from "../../../domains/bill/draft-validation.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
|
||||
* 只创建草稿,不提交。
|
||||
*/
|
||||
export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] --yes");
|
||||
}
|
||||
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
|
||||
const client = await ctx.getClient();
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
|
||||
if (!form) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据,无法复制\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const copy = buildBillCopyForm(form, { title, keepAttachments });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
dryRun: true,
|
||||
source: target,
|
||||
sourceTitle: form.title,
|
||||
title: copy.title,
|
||||
detailCount: copy.details?.length ?? 0,
|
||||
expenseMoney: copy.expenseMoney?.standard,
|
||||
keepAttachments,
|
||||
invoicesCleared: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 复制单据(dry-run,未创建) ======\n` +
|
||||
` 源单 : ${target}(${form.title ?? "-"})\n` +
|
||||
` 新标题 : ${copy.title ?? "-"}\n` +
|
||||
` 明细 : ${copy.details?.length ?? 0} 条\n` +
|
||||
` 金额 : ${copy.expenseMoney?.standard ?? "0"} CNY\n` +
|
||||
` 附件 : ${keepAttachments ? "保留" : "清空"}\n` +
|
||||
` 发票 : 清空绑定,发票总额归零\n` +
|
||||
`\n提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
source: target,
|
||||
flowId: result.flowId,
|
||||
code: result.code,
|
||||
title: result.title,
|
||||
detailCount: result.detailCount,
|
||||
expenseMoney: result.expenseMoney,
|
||||
submitted: false,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`复制成功(已创建草稿,未提交)\n` +
|
||||
` 新单号 : ${result.code}\n` +
|
||||
` 单据 ID : ${result.flowId}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { createBillDraft } from "../../../domains/bill/create.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill create --template <模板ID> [--title=...] [--amount=0.01] [--reason=...] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口创建草稿:最小表头 + 一条费用明细,创建后不提交。
|
||||
*/
|
||||
export async function handleCreate(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const templateId = stringOption(parsed.options, ["template", "spec", "specification"]);
|
||||
if (!templateId) {
|
||||
throw new Error("请通过 --template 指定单据模板 ID: hose-use bill create --template <ID> --yes");
|
||||
}
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const amount = stringOption(parsed.options, ["amount"]) ?? "0.01";
|
||||
const reason = stringOption(parsed.options, ["reason"]);
|
||||
const feeTypeName = stringOption(parsed.options, ["fee-type", "feeType"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const preview = { template: templateId, title: title ?? "(模板名称)", amount, reason: reason ?? "", feeType: feeTypeName ?? "简单费用" };
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ dryRun: true, ...preview }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 创建单据(dry-run,未创建) ======\n` +
|
||||
` 模板 : ${preview.template}\n` +
|
||||
` 标题 : ${preview.title}\n` +
|
||||
` 金额 : ${preview.amount} CNY\n` +
|
||||
` 费用类型: ${preview.feeType}\n` +
|
||||
` 事由 : ${preview.reason || "-"}\n` +
|
||||
`\n提示: 追加 --yes 执行创建(仍为草稿,不会提交)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await createBillDraft(await ctx.getClient(), corpId, {
|
||||
templateId,
|
||||
title,
|
||||
amount,
|
||||
reason,
|
||||
feeTypeName,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ ...result, submitted: false }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`创建成功(草稿,未提交)\n` +
|
||||
` 单号 : ${result.code}\n` +
|
||||
` 流程 ID : ${result.flowId}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 金额 : ${result.amount} CNY(${result.feeType})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import { deleteBillDraft } from "../../../domains/bill/write.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill delete <单号|ID> [--dry-run] --yes`
|
||||
*
|
||||
* 仅允许删除 `draft` 状态单据(`freeflow.delete`)。
|
||||
* 已提交/审批中/已支付的单据会被拒绝,避免误删真实业务单据。
|
||||
*/
|
||||
export async function handleDelete(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要删除的单号或 ID: hose-use bill delete <单号|ID> --yes");
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : undefined;
|
||||
|
||||
if (!flow || !form) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const flowId = String(flow.id ?? "");
|
||||
const code = String(form.code ?? target);
|
||||
const state = String(flow.state ?? "");
|
||||
if (state !== "draft") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[拒绝删除] 单据 ${code} 当前状态为 ${state || "unknown"},仅允许删除 draft 草稿。\n` +
|
||||
`已提交单据请走撤回/作废流程,避免误删真实业务数据。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ dryRun: true, code, flowId, state }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 删除单据(dry-run,未执行) ======\n` +
|
||||
` 单号 : ${code}\n` +
|
||||
` 流程 ID : ${flowId}\n` +
|
||||
` 状态 : ${state}\n` +
|
||||
`\n提示: 确认无误后追加 --yes 执行删除\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
await deleteBillDraft(client, corpId, flowId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ deleted: true, code, flowId }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return { stdout: `删除成功\n 单号: ${code}\n 流程 ID: ${flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -5,6 +5,12 @@ import { handleList, handleGet, handleTrace } from "./search.js";
|
||||
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
|
||||
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
|
||||
import { handleSchema, handleLink, handleSpec } from "./meta.js";
|
||||
import { handleValidate } from "./validate.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleTemplates } from "./templates.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { handleSubmit } from "./submit.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -104,7 +110,36 @@ export async function handleBillCommand(
|
||||
case "specification":
|
||||
return handleSpec(ctx);
|
||||
|
||||
case "validate":
|
||||
case "check":
|
||||
case "lint":
|
||||
return handleValidate(ctx);
|
||||
|
||||
case "copy":
|
||||
case "duplicate":
|
||||
case "clone":
|
||||
return handleCopy(ctx);
|
||||
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "remove":
|
||||
return handleDelete(ctx);
|
||||
|
||||
case "templates":
|
||||
case "template":
|
||||
case "specs":
|
||||
case "spec-list":
|
||||
return handleTemplates(ctx);
|
||||
|
||||
case "create":
|
||||
case "new":
|
||||
return handleCreate(ctx);
|
||||
|
||||
case "submit":
|
||||
case "send":
|
||||
return handleSubmit(ctx);
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
|
||||
}
|
||||
}
|
||||
@@ -207,19 +207,23 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const legacyInvoiceOption = ["no-invoice", "noInvoice", "basic"].some((key) => Object.hasOwn(parsed.options, key));
|
||||
const compatibilityNotice = legacyInvoiceOption
|
||||
? "提示: --no-invoice/--noInvoice/--basic 仅为旧版兼容参数;穿透诊断不补充加载发票详情,传入这些参数不会改变结果。\n"
|
||||
: "";
|
||||
const report = await traceBillFlowDetail(client, corpId, target);
|
||||
|
||||
if (!report.found) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(report, runtime.outputOptions),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
stderr: `${compatibilityNotice}[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -234,7 +238,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -293,7 +297,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
stderr: compatibilityNotice,
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||
import { submitBillDraft } from "../../../domains/bill/submit.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill submit <单号|ID> [--approver=<员工>] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口提交:计算审批计划 → 补齐未指派审批人 → freeflow.submit。
|
||||
*/
|
||||
export async function handleSubmit(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要提交的单号或 ID: hose-use bill submit <单号|ID> [--approver=<员工>] --yes");
|
||||
}
|
||||
const approverRaw = stringOption(parsed.options, ["approver", "approver-id", "staff"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ dryRun: true, target, approver: approverRaw ?? null }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 提交单据(dry-run,未提交) ======\n` +
|
||||
` 目标 : ${target}\n` +
|
||||
` 审批人 : ${approverRaw ?? "(使用计划中已指派的人)"}\n` +
|
||||
`\n提示: 追加 --yes 执行提交(会真实进入审批流)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const client = await ctx.getClient();
|
||||
let approverId: string | undefined;
|
||||
if (approverRaw) {
|
||||
const ids = await resolveBillStaffIds(client, corpId, [approverRaw]);
|
||||
approverId = ids[0];
|
||||
}
|
||||
const result = await submitBillDraft(client, corpId, target, { approverId });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`提交成功(已进入审批流)\n` +
|
||||
` 单号 : ${result.code}\n` +
|
||||
` 流程 ID : ${result.flowId}\n` +
|
||||
` 节点数 : ${result.nodeCount}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { listBillTemplates } from "../../../domains/bill/templates.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill templates [--all] [--keyword=...]`
|
||||
*
|
||||
* 默认返回当前身份可见且启用中的模板(与页面「快速新建单据」同源、同分组);
|
||||
* `--all` 才会带出停用模板。
|
||||
*/
|
||||
export async function handleTemplates(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const includeInactive = booleanOption(parsed.options, ["all"]);
|
||||
const keyword = (stringOption(parsed.options, ["keyword", "k", "q", "query"]) ?? "").trim();
|
||||
|
||||
const result = await listBillTemplates(await ctx.getClient(), corpId, { includeInactive });
|
||||
let groups = result.groups;
|
||||
if (keyword) {
|
||||
groups = groups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
specifications: group.specifications.filter((spec) => spec.name.includes(keyword)),
|
||||
}))
|
||||
.filter((group) => group.specifications.length > 0);
|
||||
}
|
||||
const total = groups.reduce((sum, group) => sum + group.specifications.length, 0);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
includeInactive,
|
||||
total,
|
||||
inactive: result.inactive,
|
||||
groups,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [
|
||||
`====== 单据模板(${corp.name} | ${groups.length} 组 / ${total} 个${includeInactive ? ",含停用" : ""})======`,
|
||||
"",
|
||||
];
|
||||
for (const group of groups) {
|
||||
lines.push(`${group.name || "未分组"}`);
|
||||
for (const spec of group.specifications) {
|
||||
const inactiveMark = spec.active ? "" : "(已停用)";
|
||||
lines.push(` - ${spec.name}${inactiveMark} [${spec.type}] ID: ${spec.id}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
if (!includeInactive) {
|
||||
lines.push("提示: 追加 --all 可查看包含停用模板的全量列表");
|
||||
}
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import {
|
||||
formatValidationIssues,
|
||||
validateBillDraft,
|
||||
type BillDraftForm,
|
||||
} from "../../../domains/bill/draft-validation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill validate <单号|ID>`
|
||||
*
|
||||
* 读取单据的原始表单,校验派生字段(金额/币种/发票总额/明细草稿状态)是否自洽。
|
||||
* 这是写入前的最后一道闸门:合思服务端只做弱校验,币种混加、发票总额不同步都能存进去。
|
||||
*/
|
||||
export async function handleValidate(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要校验的单号或 ID: hose-use bill validate <单号|ID>");
|
||||
}
|
||||
|
||||
const raw = await getRawBillFlow(await ctx.getClient(), corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
|
||||
|
||||
if (!flow || !form) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const issues = validateBillDraft(form);
|
||||
const errors = issues.filter((item) => item.severity === "error");
|
||||
const warnings = issues.filter((item) => item.severity === "warning");
|
||||
const billCode = typeof form.title === "string" ? form.title : target;
|
||||
const code = typeof (form as Record<string, unknown>).code === "string"
|
||||
? String((form as Record<string, unknown>).code)
|
||||
: target;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
found: true,
|
||||
corpId,
|
||||
code,
|
||||
title: billCode,
|
||||
ok: errors.length === 0,
|
||||
errorCount: errors.length,
|
||||
warningCount: warnings.length,
|
||||
issues,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: errors.length === 0 ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
const header =
|
||||
`====== 单据校验 (${code}) ======\n` +
|
||||
` 企业 : ${corp.name}\n` +
|
||||
` 标题 : ${billCode}\n` +
|
||||
` 结论 : ${errors.length === 0 ? "✅ 通过" : "❌ 未通过"}(错误 ${errors.length} / 警告 ${warnings.length})\n`;
|
||||
const body = issues.length > 0 ? formatValidationIssues(issues) : " ✅ 派生字段与必填项一致";
|
||||
return {
|
||||
stdout: `${header}\n${body}\n`,
|
||||
stderr: "",
|
||||
exitCode: errors.length === 0 ? 0 : 1,
|
||||
};
|
||||
}
|
||||
@@ -48,7 +48,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
expect(data.runtime.configFile).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use status 与 whoami 别名成功解析至 context", async () => {
|
||||
test("hose-use status 解析至 context,whoami 输出逐企业执行身份", async () => {
|
||||
const resStatus = await runCli(["status", "--json"]);
|
||||
expect(resStatus.exitCode).toBe(0);
|
||||
const dataStatus = JSON.parse(resStatus.stdout);
|
||||
@@ -57,7 +57,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
const resWhoami = await runCli(["whoami", "--json"]);
|
||||
expect(resWhoami.exitCode).toBe(0);
|
||||
const dataWhoami = JSON.parse(resWhoami.stdout);
|
||||
expect(dataWhoami.tool).toBe("hose-use");
|
||||
expect(Array.isArray(dataWhoami.corporations)).toBe(true);
|
||||
});
|
||||
|
||||
test("hose-aipro status 输出 AI PRO 专属上下文", async () => {
|
||||
|
||||
@@ -10,11 +10,17 @@ import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleWhoami } from "./corps/whoami.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
// `whoami` 输出按企业逐一列出当前执行身份;`context/status` 保留全局诊断。
|
||||
const invoked = (parsed.raw ?? []).find((arg) => !arg.startsWith("-"));
|
||||
if (invoked?.toLowerCase() === "whoami") {
|
||||
return handleWhoami(parsed, runtime);
|
||||
}
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
const activeAccount = getActiveAccount();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
it("successfully parses standard thirdparty.html assistance links", () => {
|
||||
@@ -418,4 +419,86 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
|
||||
it("supports corps hose-staffs with auto-resolved corp credentials", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as { url: string }).url;
|
||||
if (urlStr.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
accessToken: "mock-open-token",
|
||||
corporationId: "corpKeyed",
|
||||
corporation: { id: "corpKeyed", name: "已配密钥企业" },
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roleDefGroups")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: "g1",
|
||||
name: "默认组",
|
||||
roleDefs: [
|
||||
{ id: "corpKeyed:admin", name: "主管理员" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/roledefs/")) {
|
||||
return new Response(JSON.stringify({
|
||||
value: {
|
||||
id: "corpKeyed:admin",
|
||||
name: "主管理员",
|
||||
count: 1,
|
||||
contents: [{ staffs: ["corpKeyed:staff1"] }],
|
||||
},
|
||||
}), { status: 200 });
|
||||
}
|
||||
if (urlStr.includes("/api/openapi/v1/staffs/getStaffIds")) {
|
||||
return new Response(JSON.stringify({
|
||||
items: [
|
||||
{ id: "corpKeyed:staff1", name: "测试管理员", code: "001", active: true },
|
||||
],
|
||||
}), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify({}), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
const corpWithKeys: CorpConfig = {
|
||||
id: "corpKeyed",
|
||||
name: "已配密钥企业",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "token-x",
|
||||
corpId: "corpKeyed",
|
||||
staffId: "corpKeyed:STAFF",
|
||||
appKey: "my-key-123",
|
||||
appSecurity: "my-sec-456",
|
||||
},
|
||||
};
|
||||
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "hose-staffs",
|
||||
args: [],
|
||||
options: { role: "admin", json: true },
|
||||
raw: ["corps", "hose-staffs", "--role=admin", "--json"],
|
||||
},
|
||||
{ ...searchRuntime, selectedCorp: corpWithKeys, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.roleName).toBe("主管理员");
|
||||
expect(data.staffs).toHaveLength(1);
|
||||
expect(data.staffs[0].name).toBe("测试管理员");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { stringOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleSearch } from "./query.js";
|
||||
import { handleSwitch, handleCurrent } from "./context.js";
|
||||
import { handleWhoami } from "./whoami.js";
|
||||
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
|
||||
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
|
||||
@@ -36,8 +37,11 @@ export async function handleCorpsCommand(
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "identities":
|
||||
case "identity":
|
||||
return handleWhoami(parsed, runtime);
|
||||
case "current":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
|
||||
@@ -43,15 +43,21 @@ export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime
|
||||
}
|
||||
|
||||
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
let appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
let appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
let domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if ((!appKey || !appSecurity) && runtime.selectedCorp?.credentials?.appKey && runtime.selectedCorp?.credentials?.appSecurity) {
|
||||
appKey = runtime.selectedCorp.credentials.appKey;
|
||||
appSecurity = runtime.selectedCorp.credentials.appSecurity;
|
||||
domain = domain || runtime.selectedCorp.baseUrl;
|
||||
}
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
stderr: "用法: hose-use corps hose-staffs [--corp=<id>] [--app-key=<key> --app-security=<secret>] [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -233,6 +233,7 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
formatCorpEnvLabel(c.env),
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffName || "-",
|
||||
c.staffId,
|
||||
formatSourceLabel(c.source, c.hasOpenApi),
|
||||
formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
|
||||
@@ -240,7 +241,7 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
["#", "环境", "企业 ID", "企业名称", "员工姓名", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
rows
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { loadCorpConfigs } from "../../../core/config/loader.js";
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { booleanOption } from "../../parser.js";
|
||||
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
/**
|
||||
* `hose-use whoami` — 按企业逐行显示当前执行身份。
|
||||
*
|
||||
* 名称以在线 `staffs/me` 为准(配置里只存工号即可);
|
||||
* `--offline` 时退回本地缓存的 staffName(没有则显示 -)。
|
||||
*/
|
||||
|
||||
async function resolveStaffName(config: any): Promise<string | undefined> {
|
||||
try {
|
||||
const client = await Promise.race([
|
||||
createSessionClient(config),
|
||||
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), 8000)),
|
||||
]);
|
||||
const corpId = config.corpId || config.id;
|
||||
const response = await (client as any).get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
timeout: 8000,
|
||||
});
|
||||
const json = (await response.json()) as Record<string, any>;
|
||||
const staff = json.value?.staff ?? json;
|
||||
const name = typeof staff?.name === "string" ? staff.name.trim() : "";
|
||||
return name || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const results: R[] = new Array(items.length);
|
||||
let cursor = 0;
|
||||
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor++;
|
||||
results[index] = await fn(items[index]);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function handleWhoami(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const offline = booleanOption(parsed.options, ["offline", "cached"]);
|
||||
const corps = runtime.corpContext.listCorps();
|
||||
const configs = new Map<string, any>();
|
||||
for (const config of loadCorpConfigs()) {
|
||||
configs.set(config.id, config);
|
||||
}
|
||||
|
||||
const resolved: Array<{ name?: string; online: boolean }> = offline
|
||||
? corps.map((corp: any) => ({ name: corp.staffName || undefined, online: false }))
|
||||
: await mapLimit(corps, 5, async (corp: any) => {
|
||||
const config = configs.get(corp.id);
|
||||
if (!config) return { name: corp.staffName || undefined, online: false };
|
||||
const name = await resolveStaffName(config);
|
||||
return { name: name ?? corp.staffName ?? undefined, online: Boolean(name) };
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
resolvedOnline: !offline,
|
||||
corporations: corps.map((corp: any, index: number) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
env: corp.env,
|
||||
staffId: corp.staffId,
|
||||
staffName: resolved[index]?.name ?? null,
|
||||
staffNameResolved: resolved[index]?.online ?? false,
|
||||
source: corp.source,
|
||||
current: Boolean(corp.current),
|
||||
})),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (corps.length === 0) {
|
||||
return { stdout: "未配置任何企业,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = corps.map((corp: any, index: number) => [
|
||||
corp.current ? `* ${index + 1}` : ` ${index + 1}`,
|
||||
corp.name,
|
||||
corp.id,
|
||||
resolved[index]?.name || "-",
|
||||
corp.staffId || "-",
|
||||
formatSourceLabel(corp.source, corp.hasOpenApi),
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业名称", "企业 ID", "执行身份", "员工工号", "来源"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`====== 当前执行身份(共 ${corps.length} 家企业${offline ? ",离线缓存" : ",在线核验"})======\n${table}\n` +
|
||||
`\n提示: 标记 * 为当前激活企业;追加 --offline 可只看本地缓存、不发起网络请求。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -106,6 +106,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
total: 3,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
ids: ["COST01", "COST02", "COST19"],
|
||||
});
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
@@ -134,6 +135,7 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
total: 2,
|
||||
items: mockTree,
|
||||
rawTree: mockTree,
|
||||
ids: ["COST01", "COST02"],
|
||||
});
|
||||
|
||||
const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true };
|
||||
|
||||
@@ -84,11 +84,15 @@ export async function handleFeeTypeCommand(
|
||||
booleanOption(parsed.options, ["flat", "flatten", "table"]) || false;
|
||||
const keyword =
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const subtree = stringOption(parsed.options, ["subtree", "subtree-id", "parent-id"]);
|
||||
const idsOnly = booleanOption(parsed.options, ["ids-only", "ids"]) || false;
|
||||
|
||||
const result = await listFeeTypes(await getClient(), corpId, {
|
||||
all: includeAll,
|
||||
flat: isFlat,
|
||||
flat: isFlat || Boolean(subtree) || idsOnly,
|
||||
keyword,
|
||||
subtreeParentId: subtree || undefined,
|
||||
idsOnly,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -100,7 +104,7 @@ export async function handleFeeTypeCommand(
|
||||
total: result.total,
|
||||
includeDisabled: includeAll,
|
||||
keyword: keyword || null,
|
||||
items: result.items,
|
||||
...(idsOnly ? { ids: result.ids } : { items: result.items }),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
@@ -109,8 +113,16 @@ export async function handleFeeTypeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
if (idsOnly) {
|
||||
return {
|
||||
stdout: JSON.stringify(result.ids) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let rows: (string | number)[][] = [];
|
||||
if (!isFlat && !keyword) {
|
||||
if (!isFlat && !keyword && !subtree) {
|
||||
rows = renderTreeRows(result.rawTree);
|
||||
} else {
|
||||
const flatItems = (result.items as FlatFeeTypeItem[]) || [];
|
||||
@@ -126,7 +138,7 @@ export async function handleFeeTypeCommand(
|
||||
|
||||
const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${
|
||||
includeAll ? ",含停用" : ""
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}) ======`;
|
||||
}${keyword ? `,过滤: "${keyword}"` : ""}${subtree ? `,子树: "${subtree}"` : ""}) ======`;
|
||||
const tableStr = rows.length
|
||||
? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows)
|
||||
: "暂无匹配的费用类型";
|
||||
|
||||
@@ -22,6 +22,7 @@ function printFlowHelp(): string {
|
||||
" --corp=<id> 指定操作企业 (默认激活企业)",
|
||||
" --json 以 JSON 结构化格式输出诊断数据",
|
||||
" --verbose 显示完整调试信息",
|
||||
" --no-invoice/--noInvoice/--basic 旧版兼容空操作;穿透诊断本身不补充加载发票详情",
|
||||
" -h, --help 显示帮助信息",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
@@ -525,5 +525,38 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("platform gen-props 生成 MVEL 和 JS 格式的字段模板", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(services, "resolvePlatform").mockResolvedValue(mockPlatform as any));
|
||||
spies.push(spyOn(services, "resolveEntity").mockResolvedValue({
|
||||
id: "E_contract",
|
||||
name: "合同",
|
||||
code: "CONTRACT",
|
||||
fields: [
|
||||
{ name: "E_contract_name", label: "合同名称", type: "text", optional: false },
|
||||
{ name: "E_contract_amount", label: "合同金额", type: "money", optional: true },
|
||||
],
|
||||
} as any));
|
||||
|
||||
// MVEL 模板 (默认)
|
||||
const mvelRes = await handlePlatformCommand(
|
||||
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
expect(mvelRes.exitCode).toBe(0);
|
||||
expect(mvelRes.stdout).toContain('String TARGET_ENTITY_ID = "E_contract";');
|
||||
expect(mvelRes.stdout).toContain('String FIELD_合同名称 = FIELD_PREFIX + "name";');
|
||||
expect(mvelRes.stdout).toContain('row.put(FIELD_合同名称, "");');
|
||||
|
||||
// JS 模板
|
||||
const jsRes = await handlePlatformCommand(
|
||||
{ area: "platform", action: "gen-props", args: ["platform-1", "contract"], options: { lang: "js" }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
expect(jsRes.exitCode).toBe(0);
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,10 +50,55 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
const output = entities.map((entity) => ({
|
||||
...entity,
|
||||
fields: fieldKeyword
|
||||
? entity.fields.filter((field) =>
|
||||
[field.name, field.label, field.type, field.fieldKey, field.displayName].some(
|
||||
(value) => typeof value === "string" && value.toLowerCase().includes(fieldKeyword)
|
||||
)
|
||||
)
|
||||
: entity.fields,
|
||||
}));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) =>
|
||||
entity.fields.map((field): Array<string | number | boolean | null | undefined> => {
|
||||
const roleTag =
|
||||
field.role === "title"
|
||||
? "⭐ 主标题 (_name)"
|
||||
: field.role === "code"
|
||||
? "🔢 业务编码 (_code)"
|
||||
: field.role === "system"
|
||||
? "⚙️ 系统字段"
|
||||
: "📝 业务字段";
|
||||
return [
|
||||
entity.name,
|
||||
field.fieldKey ?? field.name,
|
||||
field.label,
|
||||
field.type,
|
||||
roleTag,
|
||||
field.optional === false ? "必填" : "可选",
|
||||
cell(field.entity),
|
||||
];
|
||||
})
|
||||
);
|
||||
const table = printTable(
|
||||
["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"],
|
||||
rows
|
||||
);
|
||||
const tips = [
|
||||
"",
|
||||
"💡 字段命名与工作流配置避坑提示:",
|
||||
" 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。",
|
||||
" 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);",
|
||||
" 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。",
|
||||
"",
|
||||
].join("\n");
|
||||
return {
|
||||
stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -77,3 +122,90 @@ export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleGenProps(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform gen-props <应用> <业务对象> [--lang=mvel|js]");
|
||||
}
|
||||
|
||||
const lang = (stringOption(parsed.options, ["lang", "language"]) || "mvel").toLowerCase();
|
||||
const entity = resolved.entity;
|
||||
const entityId = entity.id;
|
||||
const entityName = entity.name;
|
||||
const prefix = entityId ? `${entityId}_` : "";
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
platform: resolved.platform,
|
||||
entity: {
|
||||
id: entity.id,
|
||||
name: entity.name,
|
||||
code: entity.code,
|
||||
prefix,
|
||||
fields: entity.fields.map((f) => ({
|
||||
fieldKey: f.name,
|
||||
label: f.label,
|
||||
type: f.type,
|
||||
suffix: f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name,
|
||||
})),
|
||||
},
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
if (lang === "js" || lang === "javascript") {
|
||||
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (JS / QuickJS) ======`);
|
||||
lines.push(`const ENTITY_ID = "${entityId}";`);
|
||||
lines.push(`const FIELD_PREFIX = "${prefix}";`);
|
||||
lines.push("");
|
||||
lines.push("// ── 字段物理键定义 ──");
|
||||
lines.push("const FIELDS = {");
|
||||
for (const f of entity.fields) {
|
||||
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||
lines.push(` "${safeLabel}": FIELD_PREFIX + "${suffix}", // ${f.type || "text"}${f.optional === false ? " [必填]" : ""}`);
|
||||
}
|
||||
lines.push("};");
|
||||
lines.push("");
|
||||
lines.push("// ── 写入数据对象示例 ──");
|
||||
lines.push("const recordData = {");
|
||||
for (const f of entity.fields) {
|
||||
const safeLabel = f.label.replace(/"/g, '\\"');
|
||||
lines.push(` [FIELDS["${safeLabel}"]]: "", // ${f.label}`);
|
||||
}
|
||||
lines.push("};");
|
||||
} else {
|
||||
// 默认 MVEL 模板
|
||||
lines.push(`// ====== 自建应用实体代码模板 [${entityName}] (MVEL) ======`);
|
||||
lines.push(`String TARGET_ENTITY_ID = "${entityId}";`);
|
||||
lines.push(`String FIELD_PREFIX = "${prefix}";`);
|
||||
lines.push("");
|
||||
lines.push("// ── 物理字段键常量 ──");
|
||||
for (const f of entity.fields) {
|
||||
const suffix = f.name.startsWith(prefix) ? f.name.slice(prefix.length) : f.name;
|
||||
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||
lines.push(`String ${constName} = FIELD_PREFIX + "${suffix}"; // ${f.label} (${f.type || "text"})${f.optional === false ? " [必填]" : ""}`);
|
||||
}
|
||||
lines.push("");
|
||||
lines.push("// ── DataLink 行构建模板 (row.put) ──");
|
||||
lines.push("Map row = new HashMap();");
|
||||
for (const f of entity.fields) {
|
||||
const constName = `FIELD_${f.label.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "_")}`;
|
||||
lines.push(`row.put(${constName}, ""); // ${f.label}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { booleanOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js";
|
||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports, handleGenProps } from "./app-info.js";
|
||||
import { handleRecords, handleAudit } from "./records.js";
|
||||
import { handleRecordAction } from "./record-actions.js";
|
||||
|
||||
@@ -47,9 +47,12 @@ export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliR
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "gen-props":
|
||||
case "gen-mvel-props":
|
||||
case "props": return handleGenProps(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, gen-props, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
auditEntityRecords,
|
||||
auditLedgerContinuityAndBaseline,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
fetchAllEntityRecords,
|
||||
compileRecordPredicate,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import type { DatalinkRecord } from "../../../domains/datalink/types.js";
|
||||
import type { LedgerContinuityReport } from "../../../domains/datalink/types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue, redactSensitiveText } from "../../printer.js";
|
||||
@@ -32,7 +34,17 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const searchFields = splitFields(
|
||||
stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "searchField"])
|
||||
);
|
||||
const rawFilter = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]);
|
||||
let filterBy: string | undefined;
|
||||
if (rawFilter) {
|
||||
filterBy = buildServerFieldFilter(rawFilter, resolved.entity);
|
||||
} else if (keyword) {
|
||||
filterBy = buildKeywordFilter(keyword, { entity: resolved.entity, searchFields });
|
||||
}
|
||||
|
||||
const whereClause = stringOption(parsed.options, ["where"]);
|
||||
const predicate = whereClause ? compileRecordPredicate(whereClause, resolved.entity) : undefined;
|
||||
const sumOption = stringOption(parsed.options, ["sum", "aggregate"]);
|
||||
@@ -41,7 +53,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const isFlat = booleanOption(parsed.options, ["flat", "normalize", "normalized"], false);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const groupBy = stringOption(parsed.options, ["group-by", "groupBy"]);
|
||||
const fetchAll = isAll || Boolean(whereClause || sumOption || isProfileStats);
|
||||
const fetchAll = isAll || Boolean(sumOption || isProfileStats);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
@@ -125,12 +137,36 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
let data: DatalinkRecord[] = [];
|
||||
let total = 0;
|
||||
|
||||
let data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
if (fetchAll) {
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
if (predicate) data = data.filter(predicate);
|
||||
} else if (predicate) {
|
||||
// 客户端谓词早退机制:一旦匹配到 count 条记录,立即停止拉取后续页面,杜绝无限制全量扫描
|
||||
let matched = 0;
|
||||
const targetLimit = count ?? 20;
|
||||
for await (const record of iterateAllEntityRecords(
|
||||
resolved.clients.ekbClient,
|
||||
resolved.corpId,
|
||||
resolved.entity.id,
|
||||
{ filterBy, pageSize }
|
||||
)) {
|
||||
total++;
|
||||
if (predicate(record)) {
|
||||
data.push(record);
|
||||
matched++;
|
||||
if (matched >= targetLimit) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const page = await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
total = page.total;
|
||||
data = page.data;
|
||||
}
|
||||
|
||||
// 3. 数学聚合核算模式 (--sum="租赁费用,日折旧费")
|
||||
if (sumOption) {
|
||||
@@ -191,7 +227,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, where: whereClause, fields, flat: isFlat },
|
||||
total: page.total,
|
||||
total: total || data.length,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
@@ -209,7 +245,7 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${total || data.length}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import * as services from "../../domains/platform/services.js";
|
||||
import * as billApi from "../../domains/bill/api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as session from "../../core/http/session-client.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as workflowShared from "./workflow/shared.js";
|
||||
import * as platformShared from "./platform/shared.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { runCli } from "../runner.js";
|
||||
import { commandFlags } from "../command-metadata.js";
|
||||
import { renderScopedHelp } from "../help.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import { handleNodeCommand } from "./workflow/node.js";
|
||||
import { handleLogs } from "./workflow/history.js";
|
||||
import { handleJob } from "./workflow/job.js";
|
||||
import { handleSchema } from "./platform/app-info.js";
|
||||
import { handleBillCommand } from "./bill/index.js";
|
||||
import { handleFlowCommand } from "./flow.js";
|
||||
|
||||
const runtime = {
|
||||
selectedCorp: { id: "fixture-corp", name: "离线测试企业", credentials: { corpId: "fixture-corp" } },
|
||||
jsonMode: true,
|
||||
} as CliRuntime;
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
const directories: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const spy of spies.splice(0).reverse()) spy.mockRestore();
|
||||
await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("review CLI compatibility regressions", () => {
|
||||
it("keeps real trace-shaped boolean flags valid through runner redaction", async () => {
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: "B-FIXTURE", keepItSecret: false, appSecurity: "fixture-credential" }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(helpers, "initCorpRuntime").mockReturnValue(runtime as any));
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(raw));
|
||||
const result = await runCli(["bill", "trace", "B-FIXTURE", "--basic", "--json"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.raw.flowId.form.keepItSecret).toBe(false);
|
||||
expect(data.raw.flowId.form.appSecurity).toBe("<redacted>");
|
||||
expect(result.stdout).not.toContain("fixture-credential");
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
});
|
||||
|
||||
it("documents legacy trace flags without dropping them from the parser vocabulary", () => {
|
||||
for (const [area, action] of [["bill", "trace"], ["flow", "get"], ["trace", "get"]]) {
|
||||
const help = renderScopedHelp([area!, action!]);
|
||||
expect(help).toContain("兼容空操作");
|
||||
expect(help).toContain("不补充加载发票详情");
|
||||
const documented = help.split("支持选项:\n")[1]!.split("\n\n提示:")[0]!.trim().split("\n").map((line) => line.trim().match(/^--([^=[\s]+)/)?.[1]);
|
||||
expect(documented).toEqual(Object.keys(commandFlags(area, action)));
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
expect(commandFlags(area, action)[flag]).toBe("boolean");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("restores edit --file as code while explicit mapping and map --file still work", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "hose-node-options-"));
|
||||
directories.push(dir);
|
||||
const codeFile = join(dir, "script.js");
|
||||
const mappingFile = join(dir, "mapping.json");
|
||||
const code = "// Keep exact bytes.\nreturn 7;\n";
|
||||
await writeFile(codeFile, code);
|
||||
await writeFile(mappingFile, JSON.stringify({ label: "mapped" }));
|
||||
const detail = { id: "wf", state: 0, tasks: [{ name: "action_js", type: "code-js2", label: "original", code: "return 0;" }] };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
spies.push(spyOn(services, "getWorkflowDetail").mockResolvedValue(detail as any));
|
||||
const save = spyOn(services, "updateWorkflow").mockImplementation(async (_client, workflow) => workflow);
|
||||
spies.push(save);
|
||||
for (const flag of ["file", "code-file"]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--${flag}=${codeFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.updatedFields.code).toContain(`${code.length} 字符`);
|
||||
}
|
||||
for (const [action, flag] of [["edit", "mapping-file"], ["edit", "mapping"], ["edit", "json-file"], ["map", "file"]]) {
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", action!, "wf", "action_js", `--${flag}=${mappingFile}`, "--dry-run"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).changes.changedKeys).toContain("label");
|
||||
}
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--file=${codeFile}`, "--yes"]), runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse(result.stdout).editedTask.code).toBe(code);
|
||||
expect((save.mock.calls[0]?.[1]?.tasks?.[0] as any).code).toBe(code);
|
||||
});
|
||||
|
||||
for (const fallback of [false, true]) {
|
||||
it(`keeps legacy trace invoice flags as explicit no-ops (${fallback ? "search fallback" : "direct flow"})`, async () => {
|
||||
const target = fallback ? "流水中文" : "B-FIXTURE";
|
||||
const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: target, details: [{ feeTypeForm: { invoices: [{ invoiceId: "invoice" }] } }] }, plan: { nodes: [] } } };
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockImplementation(async (_client, _corp, query) => fallback && query !== "bill" ? undefined : raw));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
const search = spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [{ id: "bill", code: target, form: {} }], total: 1 } as any);
|
||||
spies.push(search);
|
||||
const invoice = spyOn(billApi, "getInvoiceValidationDetail").mockRejectedValue(new Error("must not supplement invoices"));
|
||||
spies.push(invoice);
|
||||
const baseline = await handleBillCommand(parseArgs(["bill", "trace", target]), runtime);
|
||||
expect(baseline.stderr).toBe("");
|
||||
expect(baseline.exitCode).toBe(0);
|
||||
for (const [area, action] of [["bill", "trace"], ["bill", "inspect"], ["flow", "get"], ["flow", "trace"], ["flow", "diagnose"]]) {
|
||||
for (const flag of ["no-invoice", "noInvoice", "basic"]) {
|
||||
for (const value of ["true", "false"]) {
|
||||
const parsed = parseArgs([area!, action!, target, `--${flag}=${value}`]);
|
||||
expect(parsed.options[flag]).toBe(value === "true");
|
||||
const result = await (area === "bill" ? handleBillCommand : handleFlowCommand)(parsed, runtime);
|
||||
expect(result.exitCode).toBe(baseline.exitCode);
|
||||
expect(JSON.parse(result.stdout)).toEqual(JSON.parse(baseline.stdout));
|
||||
expect(result.stderr).toContain("仅为旧版兼容参数");
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = await handleBillCommand(parseArgs(["bill", "trace", target, "--basic"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("单据全域穿透诊断");
|
||||
expect(text.stderr).toContain("不会改变结果");
|
||||
expect(invoice).not.toHaveBeenCalled();
|
||||
if (fallback) expect(search).toHaveBeenCalled();
|
||||
else expect(search).not.toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves not-found trace output and status with compatibility notices", async () => {
|
||||
spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise<unknown>) => loader() } as any));
|
||||
spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([]));
|
||||
spies.push(spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [], total: 0 } as any));
|
||||
for (const jsonMode of [false, true]) {
|
||||
const result = await handleBillCommand(parseArgs(["bill", "trace", "missing", "--basic=false"]), { ...runtime, jsonMode });
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("旧版兼容参数");
|
||||
if (jsonMode) expect(JSON.parse(result.stdout).found).toBe(false);
|
||||
else expect(result.stderr).toContain("[NOT FOUND]");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows actual physical schema keys, preserves JSON and falls back to name", async () => {
|
||||
const fields = [{ name: "alias_name", fieldKey: "E_REAL_KEY", label: "字段", type: "text" }, { name: "fallback_key", label: "旧字段", type: "text" }];
|
||||
spies.push(spyOn(platformShared, "resolveAppAndEntity").mockResolvedValue({ clients: {}, corpId: "corp", platform: { id: "app", name: "应用" }, entity: { id: "entity", name: "对象", fields } } as any));
|
||||
const args = ["platform", "schema", "app", "entity"];
|
||||
const text = await handleSchema(parseArgs(args), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout).toContain("E_REAL_KEY");
|
||||
expect(text.stdout).toContain("fallback_key");
|
||||
expect(text.stdout).not.toContain("alias_name");
|
||||
const json = JSON.parse((await handleSchema(parseArgs(args), runtime)).stdout);
|
||||
expect(json.entities[0].fields).toEqual(fields);
|
||||
const filtered = JSON.parse((await handleSchema(parseArgs([...args, "--keyword=E_REAL_KEY"]), runtime)).stdout);
|
||||
expect(filtered.entities[0].fields).toEqual([fields[0]]);
|
||||
});
|
||||
|
||||
it("finds in-flight errors without expanding the existing terminal state filters", async () => {
|
||||
const jobs = [
|
||||
{ id: "running-boolean", status: "RUNNING", hasError: true },
|
||||
{ id: "started-string", status: "STARTED", hasError: "true" },
|
||||
{ id: "running-localized", status: "RUNNING", hasError: "存在" },
|
||||
{ id: "started-count", status: "STARTED", errorTaskCount: 1 },
|
||||
{ id: "running-normal", status: "RUNNING", hasError: false, errorTaskCount: 0 },
|
||||
{ id: "started-normal", status: "STARTED", hasError: "不存在" },
|
||||
{ id: "completed-normal", status: "COMPLETED", hasError: "false" },
|
||||
{ id: "completed-skip", status: "COMPLETED", errorTaskCount: 1 },
|
||||
{ id: "failed", status: "FAILED" },
|
||||
];
|
||||
const page = { executeCount: 9, successCount: 2, errorCount: 1, totalItems: 9, jobList: jobs };
|
||||
spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any));
|
||||
const logs = spyOn(services, "listWorkflowLogs").mockResolvedValue(page as any);
|
||||
spies.push(logs, spyOn(services, "getWorkflowDetail").mockRejectedValue(new Error("offline unavailable")));
|
||||
const read = async (flags: string[]) => JSON.parse((await handleLogs(parseArgs(["workflow", "logs", "wf", ...flags]), runtime)).stdout);
|
||||
const errors = await read(["--has-error"]);
|
||||
const expected = ["running-boolean", "started-string", "running-localized", "started-count", "completed-skip", "failed"];
|
||||
expect(errors.jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(errors.totalItems).toBe(9);
|
||||
expect(errors.inProgressCount).toBe(6);
|
||||
expect((await read([])).jobList).toEqual(jobs);
|
||||
expect((await read(["--state=FAILED"])).jobList.map((j: any) => j.id)).toEqual(["completed-skip", "failed"]);
|
||||
expect((await read(["--state=COMPLETED"])).jobList.map((j: any) => j.id)).toEqual(["completed-normal"]);
|
||||
expect((await read(["--state=RUNNING"])).jobList).toEqual(jobs.slice(0, 6));
|
||||
expect((await read(["--state=RUNNING", "--has-error"])).jobList.map((j: any) => j.id)).toEqual(expected);
|
||||
expect(logs.mock.calls.at(-1)?.[2]?.state).toBe("RUNNING");
|
||||
const text = await handleLogs(parseArgs(["workflow", "logs", "wf"]), { ...runtime, jsonMode: false });
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-boolean"))).toContain("⚠️ 包含错误");
|
||||
expect(text.stdout.split("\n").find((line) => line.includes("running-normal"))).toContain("⏳ 执行中");
|
||||
});
|
||||
|
||||
for (const state of [undefined, 0, 1, 2]) {
|
||||
it(`reports workflow state truthfully when detail state is ${state ?? "unavailable"}`, async () => {
|
||||
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any));
|
||||
spies.push(spyOn(services, "getJob").mockResolvedValue({ id: "job", pipelineId: "wf", status: "RUNNING" } as any));
|
||||
spies.push(spyOn(services, "getJobExecutionTree").mockResolvedValue([]));
|
||||
spies.push(spyOn(services, "getJobFailedExecutions").mockResolvedValue({ items: [] } as any));
|
||||
const detail = spyOn(services, "getWorkflowDetail");
|
||||
spies.push(detail);
|
||||
if (state === undefined) detail.mockRejectedValue(new Error("offline detail unavailable"));
|
||||
else detail.mockResolvedValue({ id: "wf", state, tasks: [{ name: "trigger", type: "clock" }] } as any);
|
||||
const expected = state === undefined ? "未知(无法读取工作流详情)" : state === 0 ? "⚪ 已停用" : state === 1 ? "🟢 启用中" : "未知";
|
||||
for (const mode of [[], ["--timeline"]]) {
|
||||
const parsed = parseArgs(["workflow", "job", "job", "--platform=p", ...mode]);
|
||||
const text = await handleJob(parsed, { ...runtime, jsonMode: false });
|
||||
expect(text.exitCode).toBe(0);
|
||||
expect(text.stdout).toContain(expected);
|
||||
if (state !== 0) expect(text.stdout).not.toContain("已停用");
|
||||
const json = JSON.parse((await handleJob(parsed, runtime)).stdout);
|
||||
if (state === undefined) {
|
||||
expect(json.workflow).toBeUndefined();
|
||||
expect(json.job.id).toBe("job");
|
||||
} else if (mode.length) expect(json.workflowState).toBe(expected);
|
||||
else expect(json.workflow.stateLabel).toBe(expected);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWorkflowCommand } from "./workflow/index.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
import * as platformServices from "../../domains/platform/services.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
|
||||
@@ -1655,6 +1656,42 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
expect(editRes.exitCode).toBe(0);
|
||||
expect(editRes.stdout).toContain("修改已保存至工作流");
|
||||
|
||||
// 5.1 node map
|
||||
const mapRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["map", "pipe_node_test", "action_js_1"],
|
||||
options: { yes: true },
|
||||
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(mapRes.exitCode).toBe(1);
|
||||
expect(mapRes.stderr).toContain("请通过 --mapping-file=<路径> 指定");
|
||||
|
||||
const tmpMappingFile = (await import("os")).tmpdir() + "/test-fields-" + Date.now() + ".json";
|
||||
await (await import("fs/promises")).writeFile(
|
||||
tmpMappingFile,
|
||||
JSON.stringify([{ name: "test_field", label: "测试字段", value: "test_val" }]),
|
||||
"utf-8"
|
||||
);
|
||||
|
||||
const mapSuccessRes = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "node",
|
||||
args: ["map", "pipe_node_test", "action_js_1"],
|
||||
options: { "mapping-file": tmpMappingFile, yes: true },
|
||||
raw: ["workflow", "node", "map", "pipe_node_test", "action_js_1", `--mapping-file=${tmpMappingFile}`, "--yes"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
expect(mapSuccessRes.exitCode).toBe(0);
|
||||
expect(mapSuccessRes.stdout).toContain("已批量应用映射");
|
||||
|
||||
await (await import("fs/promises")).unlink(tmpMappingFile).catch(() => {});
|
||||
|
||||
// 6. node rm
|
||||
const rmRes = await handleWorkflowCommand(
|
||||
{
|
||||
@@ -2169,3 +2206,127 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,24 +33,27 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size", "limit", "count", "n"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const stateOption = stringOption(parsed.options, ["state"]);
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (s === "STARTED" || s === "RUNNING") return false;
|
||||
const hasJobError = (job: any): boolean => {
|
||||
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
|
||||
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
|
||||
if (job.state === "FAILED" || job.status === "FAILED") return true;
|
||||
return false;
|
||||
};
|
||||
// Preserve the existing terminal-state filters while --has-error also sees in-flight errors.
|
||||
const isJobError = (job: any): boolean => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
return s !== "STARTED" && s !== "RUNNING" && hasJobError(job);
|
||||
};
|
||||
|
||||
let filteredJobList = rawResult.jobList;
|
||||
if (hasErrorFilter) {
|
||||
filteredJobList = filteredJobList.filter(isJobError);
|
||||
filteredJobList = filteredJobList.filter(hasJobError);
|
||||
} else if (stateOption) {
|
||||
const norm = stateOption.trim().toUpperCase();
|
||||
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
|
||||
@@ -115,8 +118,8 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
const formatErrorColumn = (job: any): string => {
|
||||
const s = (job.status || "").toUpperCase();
|
||||
if (hasJobError(job)) return "⚠️ 包含错误";
|
||||
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
|
||||
if (isJobError(job)) return "⚠️ 包含错误";
|
||||
return "正常";
|
||||
};
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -404,6 +404,13 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
})),
|
||||
]);
|
||||
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
|
||||
const workflowStateLabel = !workflowDetail
|
||||
? "未知(无法读取工作流详情)"
|
||||
: workflowDetail.state === 1
|
||||
? "🟢 启用中"
|
||||
: workflowDetail.state === 0
|
||||
? "⚪ 已停用"
|
||||
: "未知";
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
const conditionDiagnoses = explainConditionBranches(tree);
|
||||
@@ -451,7 +458,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
jobId,
|
||||
pipelineId: job.pipelineId,
|
||||
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
|
||||
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
workflowState: workflowStateLabel,
|
||||
jobStatus: job.state ?? job.status,
|
||||
totalTasks: timeline.length,
|
||||
executedTasks: tree.length,
|
||||
@@ -480,7 +487,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"定义总步骤数": timeline.length,
|
||||
"已调度步骤数": tree.length,
|
||||
@@ -509,7 +516,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
id: workflowDetail.id,
|
||||
name: workflowDetail.pipelineName || workflowDetail.label,
|
||||
state: workflowDetail.state,
|
||||
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
stateLabel: workflowStateLabel,
|
||||
totalTasks: workflowDetail.tasks?.length ?? tree.length,
|
||||
}
|
||||
: undefined,
|
||||
@@ -571,7 +578,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
|
||||
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
|
||||
"工作流状态": workflowStateLabel,
|
||||
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
@@ -629,6 +636,11 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
}
|
||||
}
|
||||
|
||||
const codeSummaries = extractCodeNodeSummaries(tree, flattenExecutionTree);
|
||||
if (codeSummaries.length > 0) {
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, job.id));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
@@ -14,36 +14,62 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const isFull = booleanOption(parsed.options, ["full", "with-tasks", "withTasks"], false);
|
||||
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
let workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
workflows = workflows.filter(
|
||||
(wf) =>
|
||||
wf.pipelineName.toLowerCase().includes(kw) ||
|
||||
wf.id.toLowerCase().includes(kw) ||
|
||||
Boolean(wf.platformName && wf.platformName.toLowerCase().includes(kw))
|
||||
);
|
||||
}
|
||||
|
||||
// 默认轻量化模式:列表态剥离庞大的 tasks 节点树与代码脚本,只输出核心元数据和节点数统计
|
||||
const outputWorkflows = isFull
|
||||
? workflows
|
||||
: workflows.map(({ tasks, ...rest }) => ({
|
||||
...rest,
|
||||
nodeCount: tasks?.length ?? 0,
|
||||
}));
|
||||
|
||||
const result = {
|
||||
...rawResult,
|
||||
workflows: outputWorkflows,
|
||||
totalWorkflows: workflows.length,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
if (workflows.length === 0) {
|
||||
const emptyMsg = keyword
|
||||
? `企业 [${runtime.selectedCorp!.name}] 下未找到包含关键词 "${keyword}" 的工作流\n`
|
||||
: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`;
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
||||
stdout: emptyMsg,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
const rows = workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
wf.tasks?.length ?? "-",
|
||||
wf.tasks?.length ?? (wf as any).nodeCount ?? "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
@@ -51,8 +77,15 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
rows
|
||||
);
|
||||
|
||||
const filterDesc = [
|
||||
filterPlatformId ? `应用: ${filterPlatformId}` : "",
|
||||
keyword ? `关键词: "${keyword}"` : "",
|
||||
].filter(Boolean).join(", ");
|
||||
|
||||
const titleSuffix = filterDesc ? ` (过滤: ${filterDesc}, 共 ${workflows.length} 条)` : ` (共 ${workflows.length} 条)`;
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表${titleSuffix} ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
import { handleWorkflowEvalScript } from "./script.js";
|
||||
|
||||
test("MVEL CLI JSON returns the terminal expression and preserves failure exit codes", async () => {
|
||||
for (const [code, success] of [
|
||||
['Map result = new java.util.HashMap(); result.put("value", 7); result;', true],
|
||||
['new java.util.Date();', false],
|
||||
['if (true) { 7; }', false],
|
||||
] as const) {
|
||||
const result = await handleWorkflowEvalScript(parseArgs(["workflow", "eval-script", "--type", "code", "--code", code, "--json"]), { jsonMode: true } as any);
|
||||
const report = JSON.parse(result.stdout);
|
||||
expect(result.exitCode).toBe(success ? 0 : 1);
|
||||
expect(report.success).toBe(success);
|
||||
if (success) expect(report.returnValue).toEqual({ value: 7 });
|
||||
else expect(report.error.name).toBe("UnsupportedMvelSyntax");
|
||||
}
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
addWorkflowTask,
|
||||
editWorkflowTask,
|
||||
removeWorkflowTask,
|
||||
applyNodeMapping,
|
||||
getWorkflowAvailableNodes,
|
||||
grantWorkflowNodes,
|
||||
} from "../../../domains/platform/services.js";
|
||||
@@ -20,7 +21,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createPiperClientForCorp } from "../../helpers.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
|
||||
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
|
||||
const CORP_LEVEL_ACTIONS = new Set(["available", "list-available", "catalog", "probe", "grant", "open"]);
|
||||
|
||||
export async function handleNodeCommand(
|
||||
@@ -78,6 +79,7 @@ export async function handleNodeCommand(
|
||||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||||
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||||
"",
|
||||
"子命令 (企业灰度节点级别):",
|
||||
@@ -110,6 +112,8 @@ export async function handleNodeCommand(
|
||||
case "update":
|
||||
case "set":
|
||||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "map":
|
||||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime);
|
||||
case "rm":
|
||||
case "remove":
|
||||
case "delete":
|
||||
@@ -248,7 +252,17 @@ async function handleAddNode(
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --type=<type> 节点类型 (如 code-js2 / code)",
|
||||
" --label=<标题> 节点显示名称",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||||
" --code=<代码片段> 传入代码字符串(仅限简短代码)",
|
||||
" --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||||
" --after=<前置节点name> 插入指定节点之后",
|
||||
" --yes 确认追加",
|
||||
"",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -329,7 +343,21 @@ async function handleEditNode(
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
|
||||
stderr: [
|
||||
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --label=<新名称> 更新节点显示标题",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||||
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||||
" --desc=<描述> 更新节点描述",
|
||||
" --set='key=value' 定向修改节点自定义属性",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow node edit 900682164608835609 action_cdd6fv --code-file=./clean.mvel --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -359,6 +387,14 @@ async function handleEditNode(
|
||||
}
|
||||
}
|
||||
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
|
||||
if (mappingFile) {
|
||||
const fs = await import("fs/promises");
|
||||
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||||
const mappingData = JSON.parse(rawContent);
|
||||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime, mappingData);
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -384,7 +420,7 @@ async function handleEditNode(
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
@@ -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 {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleMapNode(
|
||||
pipelineId: string,
|
||||
nodeTarget: string,
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
injectedMappingData?: any
|
||||
): Promise<CliResult> {
|
||||
if (!nodeTarget) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请提供目标节点标识 (name 或层级序号): hose-use workflow node map <pipelineId> <nodeNameOrIndex> --mapping-file=<path> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --mapping-file=<路径> 包含字段映射的本地 JSON 文件 (可为字段数组或属性对象)",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow node map 900682164608835609 action_datalink_create --mapping-file=./fields.json --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let mappingData = injectedMappingData;
|
||||
if (!mappingData) {
|
||||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||||
if (!mappingFile) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误: 请通过 --mapping-file=<路径> 指定本地字段映射 JSON 文件\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const fs = await import("fs/promises");
|
||||
try {
|
||||
const content = await fs.readFile(mappingFile, "utf-8");
|
||||
mappingData = JSON.parse(content);
|
||||
} catch (e: any) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `错误: 读取或解析映射文件失败: ${e.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量映射工作流节点配置",
|
||||
`hose-use workflow node map ${pipelineId} ${nodeTarget} --yes`
|
||||
);
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量映射工作流节点配置", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
nodeType: editedTask.type,
|
||||
changedKeys,
|
||||
mappingSummary: Array.isArray(mappingData)
|
||||
? `数组格式更新 (${mappingData.length} 项)`
|
||||
: `对象属性更新 (${Object.keys(mappingData).join(", ")})`,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await updateWorkflow(client, updatedWorkflow);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, pipelineId, editedTask, changedKeys, workflow: saveResult }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
lintJavaScriptCode,
|
||||
lintMvelCode,
|
||||
executeJavaScriptSandbox,
|
||||
executeMvelSandbox,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
@@ -196,6 +197,8 @@ export async function handleWorkflowEvalScript(
|
||||
const codeInline = stringOption(parsed.options, ["code"]);
|
||||
const timeoutStr = stringOption(parsed.options, ["timeout"]);
|
||||
const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000;
|
||||
const explicitType = (stringOption(parsed.options, ["type"]) || "").toLowerCase();
|
||||
const isMvel = explicitType === "code" || explicitType === "mvel" || (filePath ? filePath.endsWith(".mvel") : false);
|
||||
|
||||
// 1. 获取输入参数 inputs
|
||||
let inputs: Record<string, unknown> = {};
|
||||
@@ -245,7 +248,9 @@ export async function handleWorkflowEvalScript(
|
||||
code = fs.readFileSync(filePath, "utf-8");
|
||||
}
|
||||
|
||||
const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
const evalResult = isMvel
|
||||
? await executeMvelSandbox(code, inputs, { timeoutMs })
|
||||
: await executeJavaScriptSandbox(code, inputs, { timeoutMs });
|
||||
|
||||
if (isJson) {
|
||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
@@ -296,18 +301,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
const task = located.task;
|
||||
if (task.type !== "code-js2") {
|
||||
if (task.type === "code") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
`节点 [${task.name}] 是 MVEL (code) 节点。`,
|
||||
"当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。",
|
||||
"提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (task.type !== "code-js2" && task.type !== "code") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
|
||||
@@ -316,6 +310,7 @@ export async function handleWorkflowEvalScript(
|
||||
}
|
||||
|
||||
const code: string = (task as any).code || "";
|
||||
const isNodeMvel = task.type === "code";
|
||||
|
||||
// 如果没有显式传 input,尝试提取工作流样本数据
|
||||
if (Object.keys(inputs).length === 0) {
|
||||
@@ -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) {
|
||||
return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
@@ -56,3 +56,105 @@ export async function createJobPiperClient(
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
export interface CodeNodeSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
label: string;
|
||||
type: string;
|
||||
status: string;
|
||||
rawOutput: unknown;
|
||||
summaryLines: string[];
|
||||
}
|
||||
|
||||
export function extractCodeNodeSummaries(
|
||||
nodes: Array<any>,
|
||||
flattenExecutionTreeFn?: (nodes: any[]) => any[]
|
||||
): CodeNodeSummary[] {
|
||||
const flattened = (flattenExecutionTreeFn ?? flattenExecutionTree)(nodes);
|
||||
const summaries: CodeNodeSummary[] = [];
|
||||
|
||||
for (const node of flattened) {
|
||||
if (!node) continue;
|
||||
const type = String(node.type || "");
|
||||
if (type !== "code" && type !== "code-js2") continue;
|
||||
|
||||
const rawOutput = node.output ?? node.outputs ?? node.details;
|
||||
const summaryLines: string[] = [];
|
||||
|
||||
if (rawOutput === undefined || rawOutput === null) {
|
||||
summaryLines.push(" 出参: (无返回值或 null)");
|
||||
} else if (Array.isArray(rawOutput)) {
|
||||
summaryLines.push(` 出参类型: Array (${rawOutput.length} 项)`);
|
||||
if (rawOutput.length > 0) {
|
||||
const first = rawOutput[0];
|
||||
if (first && typeof first === "object") {
|
||||
const keys = ["planCode", "code", "id", "name", "title", "totalAmount", "amount"];
|
||||
const matchedKey = keys.find((k) => (first as Record<string, unknown>)[k] !== undefined);
|
||||
if (matchedKey) {
|
||||
summaryLines.push(` 首项 ${matchedKey}: ${String((first as Record<string, unknown>)[matchedKey])}`);
|
||||
}
|
||||
if ((first as any).amount !== undefined && matchedKey !== "amount") {
|
||||
summaryLines.push(` 首项金额: ${String((first as any).amount)}`);
|
||||
}
|
||||
} else {
|
||||
summaryLines.push(` 首项值: ${String(first)}`);
|
||||
}
|
||||
}
|
||||
} else if (typeof rawOutput === "object") {
|
||||
const obj = rawOutput as Record<string, unknown>;
|
||||
summaryLines.push(" 出参类型: Object");
|
||||
if (Array.isArray(obj.items)) {
|
||||
summaryLines.push(` items.length: ${obj.items.length}`);
|
||||
}
|
||||
for (const k of ["planCode", "totalAmount", "count", "code", "total", "amount", "success"]) {
|
||||
if (obj[k] !== undefined) {
|
||||
summaryLines.push(` ${k}: ${String(obj[k])}`);
|
||||
}
|
||||
}
|
||||
const allKeys = Object.keys(obj);
|
||||
if (summaryLines.length === 1 && allKeys.length > 0) {
|
||||
summaryLines.push(` 字段列表 (${allKeys.length} 个): ${allKeys.slice(0, 5).join(", ")}${allKeys.length > 5 ? "..." : ""}`);
|
||||
}
|
||||
} else {
|
||||
summaryLines.push(` 出参值: ${String(rawOutput)}`);
|
||||
}
|
||||
|
||||
summaries.push({
|
||||
id: node.id || "-",
|
||||
name: node.name || "-",
|
||||
label: node.label || node.displayName || (type === "code" ? "MVEL代码节点" : "JS代码节点"),
|
||||
type,
|
||||
status: node.status || "UNKNOWN",
|
||||
rawOutput,
|
||||
summaryLines,
|
||||
});
|
||||
}
|
||||
|
||||
return summaries;
|
||||
}
|
||||
|
||||
export function formatCodeNodeSummariesCard(
|
||||
summaries: CodeNodeSummary[],
|
||||
jobId?: string
|
||||
): string[] {
|
||||
if (summaries.length === 0) return [];
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
"── 🧮 核心代码节点出参即时摘要 (Code Return Values) ──",
|
||||
];
|
||||
|
||||
for (const s of summaries) {
|
||||
const statusIcon = s.status === "COMPLETED" || s.status === "SUCCESS" ? "✅" : s.status === "FAILED" ? "❌" : "⏳";
|
||||
lines.push(` ${statusIcon} [${s.name}] ${s.label} (${s.type}, 状态: ${s.status})`);
|
||||
for (const l of s.summaryLines) {
|
||||
lines.push(` ${l}`);
|
||||
}
|
||||
if (jobId) {
|
||||
lines.push(` ↳ 完整出参查看: hose-use workflow job ${jobId} --node=${s.name} --full`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { extractCodeNodeSummaries } from "./shared.js";
|
||||
import { flattenExecutionTree } from "../../../domains/platform/services.js";
|
||||
|
||||
test("test and job summaries retain nested execution containers and repeated loop executions", () => {
|
||||
const tree = [{ id: "loop", type: "every", children: [
|
||||
{ id: "iteration-1", type: "condition", tasks: [{ id: "a", name: "script", type: "code", output: { count: 3 } }] },
|
||||
{ id: "iteration-2", type: "condition", subTasks: [{ id: "b", name: "script", type: "code-js2", output: [1, 2] }] },
|
||||
{ id: "iteration-3", type: "condition", items: [{ id: "c", name: "script", type: "code", output: 7 }] },
|
||||
] }];
|
||||
const summaries = extractCodeNodeSummaries(tree);
|
||||
expect(summaries.map(item => item.id)).toEqual(["a", "b", "c"]);
|
||||
expect(summaries[0].rawOutput).toEqual({ count: 3 });
|
||||
expect(summaries).toEqual(extractCodeNodeSummaries(tree, flattenExecutionTree as any));
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { stringOption, booleanOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
|
||||
export async function handleWorkflowTest(
|
||||
@@ -58,9 +58,28 @@ export async function handleWorkflowTest(
|
||||
if (isProductionCorp) {
|
||||
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
|
||||
}
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
|
||||
const nextActionCmd = isProductionCorp
|
||||
? `hose-use workflow test ${pipelineId} --yes --force`
|
||||
: `hose-use workflow test ${pipelineId} --yes`;
|
||||
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
|
||||
if (isProductionCorp) {
|
||||
if (runtime.jsonMode) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(previewResult.stdout);
|
||||
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
|
||||
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
|
||||
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
} else {
|
||||
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
|
||||
}
|
||||
}
|
||||
return previewResult;
|
||||
}
|
||||
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
@@ -465,6 +484,11 @@ export async function handleWorkflowTest(
|
||||
}
|
||||
}
|
||||
|
||||
const codeSummaries = extractCodeNodeSummaries(report.executionTree);
|
||||
if (codeSummaries.length > 0) {
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
@@ -47,6 +47,21 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(redacted).toContain('"password": "<redacted>"');
|
||||
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||
});
|
||||
|
||||
test("保留 JSON 中的业务布尔标记与空值,凭据仍脱敏", () => {
|
||||
const source = { keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "fixture", clientSecret: "fixture-client", appSecurity: 123 };
|
||||
const output = redactSensitiveText(JSON.stringify(source, null, 2));
|
||||
expect(JSON.parse(output)).toEqual({ keepItSecret: false, nested: { keepItSecret: true, secret: null }, password: "<redacted>", clientSecret: "<redacted>", appSecurity: "<redacted>" });
|
||||
expect(output).not.toContain("fixture");
|
||||
});
|
||||
|
||||
test("结构化脱敏保留单行 NDJSON 和字符串转义", () => {
|
||||
const source = { rows: [{ password: 'quoted "credential"', keepItSecret: false }], url: "https://example.test/?token=fixture-token&corpId=corp", description: "two\nlines" };
|
||||
const output = redactSensitiveText(JSON.stringify(source) + "\n");
|
||||
expect(output.split("\n")).toHaveLength(2);
|
||||
expect(JSON.parse(output)).toEqual({ rows: [{ password: "<redacted>", keepItSecret: false }], url: "https://example.test/?token=<redacted>&corpId=corp", description: "two\nlines" });
|
||||
expect(output).not.toContain("credential");
|
||||
});
|
||||
});
|
||||
|
||||
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||
|
||||
+27
-1
@@ -13,13 +13,39 @@ export function writeStdoutChunk(chunk: string): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
function redactTextFragments(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|security-token|x-amz-security-token|signature|x-amz-signature|ossaccesskeyid|x-amz-credential)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
const redactValue = (item: unknown, key = ""): unknown => {
|
||||
// Boolean/null flags such as keepItSecret are business metadata, not credentials.
|
||||
if (item === null || typeof item === "boolean") return item;
|
||||
if (/(?:password|passwd|secret|appSecurity)$/i.test(key)) return "<redacted>";
|
||||
if (typeof item === "string") return redactTextFragments(item);
|
||||
if (Array.isArray(item)) return item.map((child) => redactValue(child));
|
||||
if (typeof item === "object") {
|
||||
return Object.fromEntries(Object.entries(item).map(([name, child]) => [name, redactValue(child, name)]));
|
||||
}
|
||||
return item;
|
||||
};
|
||||
const leading = value.match(/^\s*/)?.[0] || "";
|
||||
const trailing = value.match(/\s*$/)?.[0] || "";
|
||||
// Keep compact NDJSON records on one line and ordinary CLI JSON readable.
|
||||
const multiline = value.trim().includes("\n");
|
||||
let json = JSON.stringify(redactValue(parsed), null, multiline || value.includes(": ") ? 2 : undefined);
|
||||
if (!multiline) json = json.replace(/\n\s*/g, " ");
|
||||
return leading + json + trailing;
|
||||
} catch {
|
||||
return redactTextFragments(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||
if (options.allowFull || options.outputFile) return;
|
||||
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||
|
||||
@@ -281,8 +281,10 @@ export async function importCredentials(
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
if (typeof payload.isAdmin === "boolean") {
|
||||
isAdmin = payload.isAdmin;
|
||||
} else if (payload.isAdmin === "true" || payload.isAdmin === "false") {
|
||||
isAdmin = payload.isAdmin === "true";
|
||||
}
|
||||
if (payload.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
- 导入默认沿用底层最佳努力 OpenAPI 密钥提取:无密钥、无读取权限或存在多个密钥均不阻止有效临时会话保存。SDK 显式 `elevate: true` 仍要求成功提取密钥,`elevate: false` 跳过提取。
|
||||
- 身份画像输出可选的 `profileComplete` / `unavailableFields`,配置 `session` 对应保存可选的 `identityComplete` / `identityUnavailableFields`;旧配置仍可读取。员工、管理员标记、角色、权限或部门查询缺失时,完整度为 false;未知的 `isAdmin` / `isSeniorExecutive` 为 null,缺乏已知高风险证据时 `riskLevel` 为 `UNKNOWN`,不会假装 `NORMAL`。
|
||||
- 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。
|
||||
- 本次会话/JWT 确认当前员工的管理员布尔值后,清除对应的 `admin` 缺失项并重新计算完整度,再分析风险;`false` 同样是已知值。仅有历史画像时不冒充本次查询成功,其他缺失字段继续保留。
|
||||
- 新会话未取得 OpenAPI 密钥时,返回配置仅回填本次实际保存目录、同企业文件中已保留的完整密钥对,使运行态与磁盘一致;已有新密钥优先。不从其他目录恢复密钥,也不恢复旧员工的 Token、身份或会话。
|
||||
|
||||
SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import { loadCorpConfigs, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { loadCorpConfigs, resolveWritableEnterprisesDir, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
@@ -360,6 +360,17 @@ export async function importAssistSessionToLocal(
|
||||
.find((corp) => corp.id === sessionResult.corporationId);
|
||||
const corpConfig = await importFromLink(linkToImport, importOptions);
|
||||
|
||||
// 保存层可能保留目标文件中的旧密钥;仅同步这对已保存凭证,不恢复旧员工会话。
|
||||
if (!corpConfig.credentials.appKey) {
|
||||
const savedCorp = loadCorpConfigs([importOptions.enterprisesDir || resolveWritableEnterprisesDir()])
|
||||
.find((corp) => corp.id === corpConfig.id &&
|
||||
(corp.corpId || corp.credentials.corpId) === (corpConfig.corpId || corpConfig.credentials.corpId));
|
||||
if (savedCorp?.credentials.appKey && savedCorp.credentials.appSecurity) {
|
||||
corpConfig.credentials.appKey = savedCorp.credentials.appKey;
|
||||
corpConfig.credentials.appSecurity = savedCorp.credentials.appSecurity;
|
||||
}
|
||||
}
|
||||
|
||||
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
||||
if (sessionResult.identity) {
|
||||
const ident = sessionResult.identity;
|
||||
@@ -380,6 +391,13 @@ export async function importAssistSessionToLocal(
|
||||
ident.staffId = corpConfig.credentials.staffId || ident.staffId;
|
||||
ident.staffName = corpConfig.session?.staffName || ident.staffName;
|
||||
}
|
||||
if (Array.isArray(ident.unavailableFields)) {
|
||||
// 只有本次会话对当前员工的确认能补齐缺项,历史风险证据不代表本次查询成功。
|
||||
if (typeof corpConfig.session?.isAdmin === "boolean" && ident.staffId === corpConfig.credentials.staffId) {
|
||||
ident.unavailableFields = ident.unavailableFields.filter((field) => field !== "admin");
|
||||
}
|
||||
ident.profileComplete = ident.unavailableFields.length === 0;
|
||||
}
|
||||
Object.assign(ident, analyzeStaffRoleRisk(ident));
|
||||
// 同一员工的历史高风险证据不能因本次探测不完整而被降级。
|
||||
if (ident.profileComplete === false && previousSession?.riskLevel) {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import ky from "ky";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import type { CorpConfig, CorpSessionInfo } from "../../core/config/types.js";
|
||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { handleEnter } from "../../cli/commands/assist-platform/enter.js";
|
||||
import { parseArgs } from "../../cli/parser.js";
|
||||
import * as api from "./api.js";
|
||||
import * as services from "./services.js";
|
||||
import type { AssistIdentityProfile } from "./types.js";
|
||||
|
||||
interface FixtureOptions {
|
||||
meAdmin?: boolean | null;
|
||||
jwtAdmin?: unknown;
|
||||
omitJwtAdmin?: boolean;
|
||||
rolesUnavailable?: boolean;
|
||||
permissionsUnavailable?: boolean;
|
||||
newKeys?: boolean;
|
||||
}
|
||||
|
||||
describe("assist session import credentials and identity", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const envNames = ["HOSE_ENTERPRISES_DIR", "HOSE_USER_ENTERPRISES_DIR", "HOSE_CONFIG_FILE", "HOSE_ASSIST_PLATFORM_FILE"] as const;
|
||||
let oldEnv: Record<string, string | undefined>;
|
||||
let root: string;
|
||||
let target: string;
|
||||
let other: string;
|
||||
let spies: Array<{ mockRestore(): void }>;
|
||||
|
||||
beforeEach(() => {
|
||||
oldEnv = Object.fromEntries(envNames.map((name) => [name, process.env[name]]));
|
||||
root = mkdtempSync(join(tmpdir(), "hose-assist-import-"));
|
||||
target = join(root, "target");
|
||||
other = join(root, "other");
|
||||
mkdirSync(target);
|
||||
mkdirSync(other);
|
||||
process.env.HOSE_ENTERPRISES_DIR = target;
|
||||
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.HOSE_ASSIST_PLATFORM_FILE = join(root, "assist.json");
|
||||
spies = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
globalThis.fetch = originalFetch;
|
||||
for (const name of envNames) {
|
||||
if (oldEnv[name] === undefined) delete process.env[name];
|
||||
else process.env[name] = oldEnv[name];
|
||||
}
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function oldCorp(staffId = "corp:current", session: CorpSessionInfo = {}): CorpConfig {
|
||||
return {
|
||||
id: "corp", name: "old enterprise", source: "account", accountId: "old-account",
|
||||
baseUrl: "https://old.example",
|
||||
credentials: { corpId: "corp", staffId, accessToken: "old-token", appKey: "saved-key", appSecurity: "saved-secret" },
|
||||
auth: { refreshTtl: 300, refreshToken: "old-refresh" },
|
||||
session,
|
||||
};
|
||||
}
|
||||
|
||||
function fixture(options: FixtureOptions = {}) {
|
||||
const meAdmin = options.meAdmin === undefined ? false : options.meAdmin;
|
||||
const jwtAdmin = options.jwtAdmin === undefined ? false : options.jwtAdmin;
|
||||
globalThis.fetch = (async (input: Request | URL | string, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
const url = request.url;
|
||||
if (url.includes("assistPlatform/getToken")) return Response.json({ value: {
|
||||
token: "new-token", baseUrl: "https://session.example",
|
||||
loginUrl: "https://session.example/web/thirdparty.html?accessToken=new-token&ekbCorpId=corp",
|
||||
} });
|
||||
if (url.includes("organization/staffs/me")) return Response.json({ value: {
|
||||
staff: { id: "corp:current", name: "current employee", ...(meAdmin === null ? {} : { admin: meAdmin }) },
|
||||
...(options.permissionsUnavailable ? {} : { permissions: [] }),
|
||||
} });
|
||||
if (url.endsWith("/roles?corpId=corp")) {
|
||||
return options.rolesUnavailable ? new Response("roles denied", { status: 403 }) : Response.json({ items: [] });
|
||||
}
|
||||
if (url.includes("actions/jwt")) return Response.json({ id: `fixture.${Buffer.from(JSON.stringify({
|
||||
staffId: "corp:current", staffName: "current employee", corporationName: "new enterprise",
|
||||
...(options.omitJwtAdmin ? {} : { isAdmin: jwtAdmin }),
|
||||
})).toString("base64url")}.signature` });
|
||||
if (url.includes("account/v2/session")) return Response.json({ value: {
|
||||
id: "session", corporationId: "corp", loginStaffId: "corp:current", platform: "ASSIST", isShortTermToken: true,
|
||||
} });
|
||||
if (url.includes("innerapi/v1/key")) return options.newKeys
|
||||
? Response.json({ items: [{ id: "new-key-id", appKey: "new-key", appSecurity: "new-secret" }] })
|
||||
: new Response("keys denied", { status: 403 });
|
||||
throw new Error(`Unexpected mock URL: ${url}`);
|
||||
}) as typeof fetch;
|
||||
return ky.create({ prefix: "https://assist.example/api" });
|
||||
}
|
||||
|
||||
function imported(options: FixtureOptions = {}, params: Partial<services.ImportAssistSessionParams> = {}) {
|
||||
return services.importAssistSessionToLocal(fixture(options), { corpId: "corp", ticketId: "ticket", enterprisesDir: target, ...params });
|
||||
}
|
||||
|
||||
function persisted(): CorpConfig {
|
||||
return JSON.parse(readFileSync(join(target, "corp.json"), "utf8"));
|
||||
}
|
||||
|
||||
it("restores only the key pair actually retained by the save operation", async () => {
|
||||
saveCorpConfig(oldCorp("corp:previous", { staffName: "old employee", roles: ["主管理员"], isAdmin: true, riskLevel: "HIGH" }), target);
|
||||
const { corpConfig, sessionResult } = await imported({ meAdmin: null });
|
||||
expect(corpConfig.credentials).toEqual({ corpId: "corp", staffId: "corp:current", accessToken: "new-token", appKey: "saved-key", appSecurity: "saved-secret" });
|
||||
expect(persisted().credentials).toEqual(corpConfig.credentials);
|
||||
expect(corpConfig.accountId).toBeUndefined();
|
||||
expect(corpConfig.auth?.refreshToken).toBeUndefined();
|
||||
expect(corpConfig.baseUrl).toBe("https://session.example");
|
||||
expect(sessionResult.identity?.roleNames).toEqual([]);
|
||||
expect(sessionResult.identity?.isAdmin).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("NORMAL");
|
||||
const runtime = new CorpContext([], { stateful: false });
|
||||
runtime.upsertCorp(corpConfig);
|
||||
expect(runtime.listCorps()[0]).toMatchObject({ staffId: "corp:current", hasOpenApi: true });
|
||||
});
|
||||
|
||||
it("keeps newly acquired keys in preference to the old pair", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
const { corpConfig } = await imported({ newKeys: true });
|
||||
expect(corpConfig.credentials.appKey).toBe("new-key");
|
||||
expect(corpConfig.credentials.appSecurity).toBe("new-secret");
|
||||
expect(persisted().credentials.appKey).toBe("new-key");
|
||||
});
|
||||
|
||||
it("does not invent keys when no pair is saved", async () => {
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(corpConfig.credentials.appSecurity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not restore an incomplete saved pair", async () => {
|
||||
const previous = oldCorp();
|
||||
delete previous.credentials.appSecurity;
|
||||
saveCorpConfig(previous, target);
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(corpConfig.credentials.appSecurity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores the legacy auth key pair that the loader already preserves", async () => {
|
||||
const previous = oldCorp();
|
||||
delete previous.credentials.appKey;
|
||||
delete previous.credentials.appSecurity;
|
||||
previous.auth = { refreshTtl: 300, appKey: "legacy-key", appSecurity: "legacy-secret" };
|
||||
writeFileSync(join(target, "corp.json"), JSON.stringify(previous));
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBe("legacy-key");
|
||||
expect(corpConfig.credentials.appSecurity).toBe("legacy-secret");
|
||||
});
|
||||
|
||||
it("does not take keys from a same-id file outside the actual write directory", async () => {
|
||||
saveCorpConfig(oldCorp(), other);
|
||||
process.env.HOSE_ENTERPRISES_DIR = other;
|
||||
const { corpConfig } = await imported();
|
||||
expect(corpConfig.credentials.appKey).toBeUndefined();
|
||||
expect(persisted().credentials.appKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves the default write directory when no explicit directory is supplied", async () => {
|
||||
const previous = oldCorp();
|
||||
previous.credentials.appKey = "other-key";
|
||||
saveCorpConfig(previous, other);
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
process.env.HOSE_USER_ENTERPRISES_DIR = target;
|
||||
// A missing test directory must not override the configured user write directory.
|
||||
writeFileSync(process.env.HOSE_CONFIG_FILE!, JSON.stringify({ testEnterprisesDir: join(root, "missing") }));
|
||||
const { corpConfig } = await imported({}, { enterprisesDir: undefined });
|
||||
expect(corpConfig.credentials.appKey).toBe("saved-key");
|
||||
expect(persisted().credentials.appKey).toBe("saved-key");
|
||||
});
|
||||
|
||||
it("restores saved keys even if no identity profile could be generated", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
spies.push(spyOn(api, "getStaffMeAndRolesApi").mockRejectedValue(new Error("identity unavailable")));
|
||||
const { corpConfig, sessionResult } = await imported();
|
||||
expect(sessionResult.identity).toBeUndefined();
|
||||
expect(corpConfig.credentials.appKey).toBe("saved-key");
|
||||
});
|
||||
|
||||
it("does not bypass overwrite protection", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
await expect(imported({}, { overwrite: false })).rejects.toMatchObject({ name: "AuthenticationError" });
|
||||
expect(persisted().credentials.accessToken).toBe("old-token");
|
||||
});
|
||||
|
||||
for (const admin of [false, true, "false", "true"]) {
|
||||
it(`recomputes completeness when the current JWT confirms admin=${JSON.stringify(admin)}`, async () => {
|
||||
const expectedAdmin = admin === true || admin === "true";
|
||||
const { sessionResult, corpConfig } = await imported({ meAdmin: null, jwtAdmin: admin });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: expectedAdmin, unavailableFields: [], profileComplete: true, riskLevel: expectedAdmin ? "HIGH" : "NORMAL" });
|
||||
expect(corpConfig.session).toMatchObject({ isAdmin: expectedAdmin, identityComplete: true, identityUnavailableFields: [], riskLevel: expectedAdmin ? "HIGH" : "NORMAL" });
|
||||
expect(persisted().session).toEqual(corpConfig.session);
|
||||
});
|
||||
}
|
||||
|
||||
for (const admin of [null, "unknown", "", 0, 1, {}, []]) {
|
||||
it(`does not mistake JWT admin=${JSON.stringify(admin)} for a confirmed non-admin`, async () => {
|
||||
const { sessionResult, corpConfig } = await imported({ meAdmin: null, jwtAdmin: admin });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
expect(corpConfig.session?.isAdmin).toBeUndefined();
|
||||
expect(persisted().session).toMatchObject({ identityComplete: false, identityUnavailableFields: ["admin"], riskLevel: "UNKNOWN" });
|
||||
});
|
||||
}
|
||||
|
||||
it("keeps an omitted JWT admin unknown", async () => {
|
||||
const { sessionResult } = await imported({ meAdmin: null, omitJwtAdmin: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("does not treat other missing fields as complete after JWT admin recovery", async () => {
|
||||
const { sessionResult } = await imported({ meAdmin: null, rolesUnavailable: true, permissionsUnavailable: true });
|
||||
expect(sessionResult.identity?.unavailableFields).toEqual(["permissions", "roles"]);
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("does not turn historical admin evidence into a successful current query", async () => {
|
||||
saveCorpConfig(oldCorp("corp:current", { isAdmin: false }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, jwtAdmin: null });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: false, unavailableFields: ["admin"], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("preserves a same-employee high risk while the new profile remains incomplete", async () => {
|
||||
saveCorpConfig(oldCorp("corp:current", { isAdmin: true, riskLevel: "HIGH" }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, rolesUnavailable: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: false, unavailableFields: ["roles"], profileComplete: false, riskLevel: "HIGH", isSeniorExecutive: true });
|
||||
});
|
||||
|
||||
it("does not inherit another employee's historical admin, roles or risk", async () => {
|
||||
saveCorpConfig(oldCorp("corp:previous", { isAdmin: true, roles: ["主管理员"], permissions: ["SYS_ADMIN"], riskLevel: "HIGH" }), target);
|
||||
const { sessionResult } = await imported({ meAdmin: null, jwtAdmin: null, rolesUnavailable: true, permissionsUnavailable: true });
|
||||
expect(sessionResult.identity).toMatchObject({ isAdmin: null, roleNames: [], permissions: [], profileComplete: false, riskLevel: "UNKNOWN" });
|
||||
});
|
||||
|
||||
it("does not assume legacy profiles without a missing-field array are complete", async () => {
|
||||
const identity: AssistIdentityProfile = {
|
||||
staffId: "corp:current", staffName: "current employee", isAdmin: null, profileComplete: false,
|
||||
roles: [], roleNames: [], permissions: [], readablePermissions: [],
|
||||
isSeniorExecutive: null, seniorTitles: [], riskLevel: "UNKNOWN",
|
||||
};
|
||||
spies.push(spyOn(services, "inspectAssistIdentity").mockResolvedValue(identity));
|
||||
const { sessionResult } = await imported();
|
||||
expect(sessionResult.identity?.unavailableFields).toBeUndefined();
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("does not clear missing admin for a profile belonging to a different employee", async () => {
|
||||
spies.push(spyOn(services, "inspectAssistIdentity").mockResolvedValue({
|
||||
staffId: "corp:other", staffName: "other employee", isAdmin: null, profileComplete: false,
|
||||
unavailableFields: ["admin"], roles: [], roleNames: [], permissions: [], readablePermissions: [],
|
||||
isSeniorExecutive: null, seniorTitles: [], riskLevel: "UNKNOWN",
|
||||
}));
|
||||
const { sessionResult } = await imported();
|
||||
expect(sessionResult.identity?.unavailableFields).toEqual(["admin"]);
|
||||
expect(sessionResult.identity?.profileComplete).toBe(false);
|
||||
expect(sessionResult.identity?.riskLevel).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("reports saved keys consistently in CLI JSON and the runtime context", async () => {
|
||||
saveCorpConfig(oldCorp(), target);
|
||||
fixture({ meAdmin: null });
|
||||
const corpContext = new CorpContext([], { stateful: false });
|
||||
const result = await handleEnter(parseArgs(["assist-platform", "enter", "corp", "--save", "--yes", "--overwrite", "--ticket=ticket", "--token=fixture-operator"]), {
|
||||
jsonMode: true, corpContext,
|
||||
} as any);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).enterprise.hasOpenApi).toBe(true);
|
||||
expect(corpContext.getCorp("corp")?.credentials.appKey).toBe("saved-key");
|
||||
expect(result.stdout).not.toContain("saved-secret");
|
||||
});
|
||||
});
|
||||
@@ -6,11 +6,19 @@
|
||||
|
||||
```text
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
└── README.bill.md # 本说明文件
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
|
||||
├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文)
|
||||
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
|
||||
├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用)
|
||||
├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细)
|
||||
├── submit.ts # 计算审批计划并提交送审(freeflow.submit)
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
├── copy.test.ts # 复制转换单测
|
||||
├── draft-validation.test.ts # 校验规则单测
|
||||
└── README.bill.md # 本说明文件
|
||||
```
|
||||
|
||||
## 核心能力
|
||||
@@ -47,5 +55,64 @@ src/domains/bill/
|
||||
- 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`):
|
||||
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
|
||||
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
|
||||
- 穿透诊断不执行发票详情补全;`--no-invoice` / `--noInvoice` / `--basic` 继续接受为兼容空操作,显式使用时通过 stderr 说明,JSON stdout 与结果不变。未命中流程时的单据回退检索仍可能查询发票索引,这些参数不保证跳过该检索。
|
||||
|
||||
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
|
||||
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
|
||||
(甚至允许 CNY 与 USD 直接相加)。CLI 在写入前先跑本层校验:
|
||||
必填表头、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
|
||||
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期。
|
||||
10. **纯接口复制 (`copyBillAsDraft`)**:
|
||||
- 读取服务端最新的 `flow.form`;
|
||||
- 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`;
|
||||
- 重算报销/支付金额,附件默认保留;
|
||||
- `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。
|
||||
11. **草稿删除 (`deleteBillDraft`)**:
|
||||
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
|
||||
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
|
||||
|
||||
12. **单据模板列表 (`listBillTemplates`)**:
|
||||
- 与页面「快速新建单据」同源:`GET /api/form/v2/specificationGroups/withSpecificationVersioned`;
|
||||
- 响应按「规格分组 → 规格」组织,且已由服务端按当前身份做可见性过滤;
|
||||
- 默认只返回启用中的模板,`--all` 才会尝试带出停用项(服务端未返回停用项时两者一致)。
|
||||
|
||||
13. **按模板创建草稿 (`createBillDraft`)**:
|
||||
- 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细;
|
||||
- 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。
|
||||
14. **提交送审 (`submitBillDraft`)**:
|
||||
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
|
||||
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
||||
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
||||
|
||||
## 写接口契约(实测)
|
||||
|
||||
```text
|
||||
# 保存 / 提交 / 删除共用同一端点,靠 name 区分
|
||||
POST /api/flow/v1/flows/$<flowId>?corpId=
|
||||
{ id, name: "freeflow.edit", form } # 保存草稿
|
||||
{ id, name: "freeflow.delete" } # 删除草稿
|
||||
{ id, name: "freeflow.submit", form, formType, nodes } # 提交(nodes 来自审批计划)
|
||||
|
||||
# 新建草稿(不带 id)
|
||||
POST /api/flow/v1/flows?corpId=
|
||||
{ name: "freeflow.edit", form } -> { flow: { id, form: { code } } }
|
||||
|
||||
# 提交前必须先算审批计划
|
||||
POST /api/v1/flow/plans/computed
|
||||
{ flowId, flowPlanConfigId, form, formType, params } -> { value: { nodes: [...] } }
|
||||
```
|
||||
|
||||
注意:
|
||||
- 保存 `form` 必须使用**扁平 ID 字符串**(`specificationId`、`expenseDepartment`、`feeTypeId`、
|
||||
`u_预算科目`、`法人实体`、`detailId` 等),直接回传读取接口的对象会 200 但不生效;
|
||||
- 交付审批计划时 `nodes` 需原样回传给 `freeflow.submit`;
|
||||
- 附件上传与发票上传目前仍依赖前端 Uploader,纯服务端 presign 链路尚未验证;
|
||||
- 提交/撤回等破坏性动作只在测试企业验证,生产环境禁止演练。
|
||||
|
||||
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
|
||||
## 翻译上下文的发票读取预算
|
||||
|
||||
`getTranslatorContext` 的单张发票补全有 3 秒整体预算,包含请求和响应体读取。超时会取消该票请求,成功或失败都会清理计时器;单票失败不影响其他票和整体翻译,迟到结果不再写入返回字典。发票 GET 显式关闭普通自动重试,`getInvoiceValidationDetail` 的可选第四参数可传入 `signal`,原三参数调用保持兼容。
|
||||
|
||||
共享客户端的鉴权重放保留取消信号;已经开始的独立凭据续期不受该单票信号控制。自定义传输若忽略 AbortSignal,整体等待仍受预算限制,但无法保证强制中止其内部操作。
|
||||
+92
-5
@@ -66,6 +66,56 @@ export async function getRawBillFlow(
|
||||
const cleanTarget = target.trim();
|
||||
let match: Record<string, unknown> | undefined;
|
||||
|
||||
// 通道 0: flows/my & flows/approved 服务端按单号/ID 精确过滤
|
||||
// 覆盖已支付/已归档等不在 backlogs 中的单据,避免回退到「最近 N 条」本地匹配。
|
||||
try {
|
||||
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved"];
|
||||
let flowId: string | undefined;
|
||||
for (const ep of endpoints) {
|
||||
let items: Record<string, unknown>[] = [];
|
||||
try {
|
||||
const res = await client.post(ep, {
|
||||
searchParams: { corpId, type: "home5" },
|
||||
json: {
|
||||
limit: { start: 0, count: 10 },
|
||||
filterBy: `(form.code.in(${quoted(cleanTarget)}))||(id==${quoted(cleanTarget)})`,
|
||||
},
|
||||
});
|
||||
const body = (await res.json()) as { items?: Record<string, unknown>[] };
|
||||
items = body.items ?? [];
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const item = items.find((it) => {
|
||||
const flow = (it.flow && typeof it.flow === "object" ? it.flow : {}) as Record<string, unknown>;
|
||||
const form = (it.form && typeof it.form === "object"
|
||||
? it.form
|
||||
: (flow.form && typeof flow.form === "object" ? flow.form : {})) as Record<string, unknown>;
|
||||
return flow.id === cleanTarget || form.code === cleanTarget;
|
||||
});
|
||||
const flow = item && item.flow && typeof item.flow === "object" ? item.flow as Record<string, unknown> : undefined;
|
||||
if (flow && typeof flow.id === "string") {
|
||||
flowId = flow.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flowId) {
|
||||
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
|
||||
searchParams: { id: flowId, corpId },
|
||||
json: {
|
||||
filterBy: `(id==${quoted(flowId)})`,
|
||||
select: "id,state,form,logs",
|
||||
},
|
||||
});
|
||||
const json = (await detail.json()) as { value?: Record<string, unknown> };
|
||||
if (json.value) {
|
||||
return { flowId: json.value };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 通道 0 失败时继续走既有回溯通道
|
||||
}
|
||||
|
||||
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
|
||||
const searchFilters = [
|
||||
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
|
||||
@@ -122,6 +172,36 @@ export async function getRawBillFlow(
|
||||
}
|
||||
}
|
||||
|
||||
// 通道 0.5: 企业级按单号索引(跨身份,不依赖 flows/my 的“我发起”范围)
|
||||
// 部分单据由系统或其他员工创建,当前凭证身份在 flows/my 中不可见,但 searchByCode 可查。
|
||||
try {
|
||||
const res = await client.post("api/flow/v2/flows/searchByCode", {
|
||||
searchParams: { corpId },
|
||||
json: {},
|
||||
});
|
||||
const json = (await res.json()) as { items?: Record<string, unknown>[] };
|
||||
const item = (json.items ?? []).find((it) => {
|
||||
const form = (it.form && typeof it.form === "object" ? it.form : {}) as Record<string, unknown>;
|
||||
return it.id === cleanTarget || form.code === cleanTarget;
|
||||
});
|
||||
if (item) {
|
||||
const flowId = typeof item.id === "string" ? item.id : undefined;
|
||||
// searchByCode 返回的是精简表单(可能缺收款信息/部门等表头字段),
|
||||
// 命中后统一再拉一次完整详情,保证 bill get / bill validate 拿到的字段齐全。
|
||||
if (flowId) {
|
||||
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
|
||||
searchParams: { id: flowId, corpId },
|
||||
json: { filterBy: `(id==${quoted(flowId)})`, select: "id,state,form,logs" },
|
||||
});
|
||||
const detailJson = (await detail.json()) as { value?: Record<string, unknown> };
|
||||
if (detailJson.value) return { flowId: detailJson.value };
|
||||
}
|
||||
return { flowId: item };
|
||||
}
|
||||
} catch {
|
||||
// 通道 0.5 失败时继续走既有回溯通道
|
||||
}
|
||||
|
||||
const backlogId = typeof match?.id === "string" ? match.id : cleanTarget;
|
||||
const flowIdFromMatch = match?.flowId && typeof match.flowId === "object" && typeof (match.flowId as any).id === "string"
|
||||
? (match.flowId as any).id
|
||||
@@ -485,11 +565,14 @@ export async function listEntitySchemas(
|
||||
export async function getInvoiceValidationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
invoiceId: string
|
||||
invoiceId: string,
|
||||
options: { signal?: AbortSignal } = {}
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
try {
|
||||
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
|
||||
searchParams: { masterId: invoiceId, corpId }
|
||||
searchParams: { masterId: invoiceId, corpId },
|
||||
signal: options.signal,
|
||||
retry: 0,
|
||||
});
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
} catch {
|
||||
@@ -528,12 +611,16 @@ export async function getFormSpecification(
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecification | undefined> {
|
||||
const cleanId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!cleanId) return undefined;
|
||||
const rawId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!rawId) return undefined;
|
||||
// 服务端用于查询的是「原始规格 ID」,版本化 ID 形如 `<originalId>:<hash>`;
|
||||
// 仅剥离末尾的 hash(originalId 本身可能包含冒号,如 `<corpId>:system:<name>`)。
|
||||
const cleanId = rawId.replace(/:[0-9a-f]{32,64}$/i, "");
|
||||
const response = await client.get(
|
||||
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
searchParams: { corpId, _t: String(Date.now()) },
|
||||
headers: { "cache-control": "no-cache", pragma: "no-cache" },
|
||||
}
|
||||
);
|
||||
const json = (await response.json()) as {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { buildBillCopyForm } from "./copy.js";
|
||||
import type { BillDraftForm } from "./draft-validation.js";
|
||||
|
||||
function makeSource(): BillDraftForm {
|
||||
return {
|
||||
id: "ID_SOURCE",
|
||||
code: "B26015505",
|
||||
title: "报销 10月AI工具费用",
|
||||
specificationId: "spec-1",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDate: Date.UTC(2026, 9, 23),
|
||||
expenseDepartment: "corp:dept-1",
|
||||
payeeId: "payee-1",
|
||||
法人实体: "entity-1",
|
||||
u_最晚付款日期: Date.UTC(2026, 9, 31),
|
||||
description: "",
|
||||
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
payMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "321.14", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
attachments: [{ key: "bill-level.pdf" }],
|
||||
details: [
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 1,
|
||||
amount: { standard: "121.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "121.14", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
|
||||
attachments: [{ key: "bank.jpeg" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 2,
|
||||
amount: { standard: "200", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "200", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
|
||||
detailStatus: "draft",
|
||||
attachments: [{ key: "alipay.pdf" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildBillCopyForm", () => {
|
||||
it("清空发票绑定并把发票总额归零", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.u_发票总金额?.standard).toBe("0");
|
||||
for (const detail of form.details!) {
|
||||
expect(detail.feeTypeForm?.invoice).toBe("0");
|
||||
expect(detail.feeTypeForm?.invoiceForm).toEqual({ type: "exist", invoices: [] });
|
||||
expect(detail.feeTypeForm?.u_发票总金额?.standard).toBe("0");
|
||||
}
|
||||
});
|
||||
|
||||
it("重算报销金额与支付金额", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.expenseMoney?.standard).toBe("321.14");
|
||||
expect(form.payMoney?.standard).toBe("321.14");
|
||||
});
|
||||
|
||||
it("剔除明细草稿标记", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.details![1].feeTypeForm?.detailStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it("默认保留附件", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.attachments?.length).toBe(1);
|
||||
expect(form.details![0].feeTypeForm?.attachments?.length).toBe(1);
|
||||
});
|
||||
|
||||
it("dropAttachments 清空单据与明细附件", () => {
|
||||
const form = buildBillCopyForm(makeSource(), { keepAttachments: false });
|
||||
expect(form.attachments).toEqual([]);
|
||||
expect(form.details![0].feeTypeForm?.attachments).toEqual([]);
|
||||
expect(form.details![1].feeTypeForm?.attachments).toEqual([]);
|
||||
});
|
||||
|
||||
it("支持自定义标题并保留币种字段", () => {
|
||||
const form = buildBillCopyForm(makeSource(), { title: "报销 10月AI工具费用(副本)" });
|
||||
expect(form.title).toBe("报销 10月AI工具费用(副本)");
|
||||
expect(form.u_发票总金额?.standardStrCode).toBe("CNY");
|
||||
expect(form.u_发票总金额?.standardSymbol).toBe("¥");
|
||||
});
|
||||
|
||||
it("不修改源对象", () => {
|
||||
const source = makeSource();
|
||||
buildBillCopyForm(source);
|
||||
expect(source.u_发票总金额?.standard).toBe("321.14");
|
||||
expect(source.details![1].feeTypeForm?.detailStatus).toBe("draft");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError } from "../../core/errors.js";
|
||||
import { getRawBillFlow } from "./api.js";
|
||||
import type { BillDraftForm, BillMoney } from "./draft-validation.js";
|
||||
|
||||
/**
|
||||
* 纯接口复制单据。
|
||||
*
|
||||
* 合思前端的「复制」是内存行为:读取源单 → 在编辑器里生成一份新表单,点保存时才创建。
|
||||
* 而且它复制的是编辑器内存里的旧状态(可能带旧汇率/旧金额)。
|
||||
*
|
||||
* CLI 的复制走「服务端读取 → 本地转换 → 创建」:
|
||||
* 1. 读取服务端最新的 form;
|
||||
* 2. 清空发票绑定(invoiceForm.invoices)、发票总额归零、剔除明细草稿标记;
|
||||
* 3. 重算报销/支付金额;
|
||||
* 4. POST /api/flow/v1/flows 创建新草稿。
|
||||
*/
|
||||
|
||||
export interface CopyBillOptions {
|
||||
/** 新单据标题;默认沿用源单标题 */
|
||||
title?: string;
|
||||
/** 是否保留附件(默认保留,与前端行为一致) */
|
||||
keepAttachments?: boolean;
|
||||
}
|
||||
|
||||
export interface CopyBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
detailCount: number;
|
||||
expenseMoney: string;
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
const CURRENCY_FIELDS = [
|
||||
"standardStrCode",
|
||||
"standardNumCode",
|
||||
"standardSymbol",
|
||||
"standardUnit",
|
||||
"standardScale",
|
||||
] as const;
|
||||
|
||||
/** 生成一个金额为 0 的本位币金额对象。 */
|
||||
function zeroMoney(source: BillMoney | undefined): BillMoney {
|
||||
const money: BillMoney = { standard: "0" };
|
||||
for (const field of CURRENCY_FIELDS) {
|
||||
if (source && source[field] !== undefined) {
|
||||
(money as Record<string, unknown>)[field] = source[field];
|
||||
}
|
||||
}
|
||||
return money;
|
||||
}
|
||||
|
||||
function moneyNumber(money: BillMoney | undefined): number {
|
||||
const value = Number(money?.standard ?? 0);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把源单 form 转换成一个可创建的新草稿 form。
|
||||
* 纯函数,便于单测与实际调用共享。
|
||||
*/
|
||||
export function buildBillCopyForm(
|
||||
source: BillDraftForm,
|
||||
options: CopyBillOptions = {}
|
||||
): BillDraftForm {
|
||||
const keepAttachments = options.keepAttachments !== false;
|
||||
const form = structuredClone(source) as BillDraftForm;
|
||||
|
||||
delete (form as Record<string, unknown>).id;
|
||||
delete (form as Record<string, unknown>).code;
|
||||
if (options.title?.trim()) {
|
||||
form.title = options.title.trim();
|
||||
}
|
||||
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
let amountSum = 0;
|
||||
|
||||
for (const detail of details) {
|
||||
const ft = (detail.feeTypeForm ??= {});
|
||||
amountSum += moneyNumber(ft.amount);
|
||||
|
||||
// 复制不携带发票绑定;发票总额归零
|
||||
ft.invoice = "0";
|
||||
ft.invoiceForm = { type: "exist", invoices: [] };
|
||||
ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
|
||||
delete ft.detailStatus;
|
||||
|
||||
if (!keepAttachments) {
|
||||
ft.attachments = [];
|
||||
}
|
||||
}
|
||||
|
||||
form.u_发票总金额 = zeroMoney(form.u_发票总金额);
|
||||
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
if (!keepAttachments) {
|
||||
form.attachments = [];
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取源单并创建一份新草稿。
|
||||
*/
|
||||
export async function copyBillAsDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: CopyBillOptions = {}
|
||||
): Promise<CopyBillResult> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object"
|
||||
? (raw.flowId as Record<string, unknown>)
|
||||
: undefined;
|
||||
const sourceForm = flow && typeof flow.form === "object"
|
||||
? (flow.form as BillDraftForm)
|
||||
: undefined;
|
||||
|
||||
if (!flow || !sourceForm) {
|
||||
throw new NotFoundError(`在企业 [${corpId}] 下未找到单号或 ID 为 [${target}] 的单据,无法复制`);
|
||||
}
|
||||
|
||||
const form = buildBillCopyForm(sourceForm, options);
|
||||
const response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
});
|
||||
const json = (await response.json()) as {
|
||||
value?: { id?: string; form?: { code?: string } } | string;
|
||||
flow?: { id?: string; form?: { code?: string } };
|
||||
id?: string;
|
||||
form?: { code?: string };
|
||||
};
|
||||
const value = (json.value && typeof json.value === "object" ? json.value : undefined)
|
||||
?? json.flow
|
||||
?? json;
|
||||
const formSnapshot = (value.form ?? {}) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
flowId: String(value.id ?? ""),
|
||||
code: String(formSnapshot.code ?? ""),
|
||||
title: String(formSnapshot.title ?? form.title ?? ""),
|
||||
detailCount: form.details?.length ?? 0,
|
||||
expenseMoney: String(form.expenseMoney?.standard ?? "0"),
|
||||
form,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { filterBillFormByTemplate, filterFeeTypeFormBySpec } from "./create.js";
|
||||
|
||||
const components = [
|
||||
{ field: "title", optional: false },
|
||||
{ field: "submitterId", optional: false },
|
||||
{ field: "description", optional: true },
|
||||
{ field: "u_自定义字段", optional: true },
|
||||
];
|
||||
|
||||
describe("filterBillFormByTemplate", () => {
|
||||
it("只保留模板声明的字段,剔除未声明字段", () => {
|
||||
const { form, missingRequired } = filterBillFormByTemplate(
|
||||
{
|
||||
specificationId: "spec",
|
||||
title: "t",
|
||||
submitterId: "s",
|
||||
u_发票总金额: { standard: "0" },
|
||||
details: [],
|
||||
},
|
||||
components
|
||||
);
|
||||
expect(form).toEqual({ specificationId: "spec", title: "t", submitterId: "s", details: [] });
|
||||
expect(missingRequired).toEqual([]);
|
||||
});
|
||||
|
||||
it("返回缺失的必填字段", () => {
|
||||
const { missingRequired } = filterBillFormByTemplate(
|
||||
{ specificationId: "spec", details: [] },
|
||||
components
|
||||
);
|
||||
expect(missingRequired).toEqual(["title", "submitterId"]);
|
||||
});
|
||||
|
||||
it("模板没有 components 时保留 specificationId 与 details", () => {
|
||||
const { form } = filterBillFormByTemplate(
|
||||
{ specificationId: "spec", title: "t", details: [] },
|
||||
[]
|
||||
);
|
||||
expect(form).toEqual({ specificationId: "spec", details: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterFeeTypeFormBySpec", () => {
|
||||
it("剔除费用类型未声明的字段(如 feeDate)", () => {
|
||||
const form = filterFeeTypeFormBySpec(
|
||||
{ amount: { standard: "1" }, feeDate: 123 },
|
||||
[{ field: "amount" }, { field: "apportions" }]
|
||||
);
|
||||
expect(form).toEqual({ amount: { standard: "1" } });
|
||||
});
|
||||
|
||||
it("schema 为空时保留候选字段", () => {
|
||||
const candidate = { amount: { standard: "1" }, feeDate: 123 };
|
||||
expect(filterFeeTypeFormBySpec(candidate, [])).toEqual(candidate);
|
||||
});
|
||||
|
||||
it("保留 schema 声明的其它字段", () => {
|
||||
const form = filterFeeTypeFormBySpec(
|
||||
{ amount: { standard: "1" }, apportions: [], feeDate: 123 },
|
||||
[{ field: "amount" }, { field: "apportions" }]
|
||||
);
|
||||
expect(form).toEqual({ amount: { standard: "1" }, apportions: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js";
|
||||
import { listBillTemplates } from "./templates.js";
|
||||
|
||||
/**
|
||||
* 纯接口创建单据草稿。
|
||||
*
|
||||
* 模板决定必填字段;这里构造最小可用表单:
|
||||
* - 表头:specificationId / title / submitterId / expenseDate / expenseDepartment
|
||||
* - 明细:选中一个费用类型(默认「简单费用」或第一个可用类型),金额可配置
|
||||
*
|
||||
* 创建后仍为 draft,不会提交。
|
||||
*/
|
||||
|
||||
export interface CreateBillOptions {
|
||||
/** 模板 ID(bill templates 输出的 id) */
|
||||
templateId: string;
|
||||
title?: string;
|
||||
/** 本位币金额,默认 0.01 */
|
||||
amount?: string;
|
||||
reason?: string;
|
||||
/** 指定费用类型名称,默认「简单费用」,找不到则取第一个可用类型 */
|
||||
feeTypeName?: string;
|
||||
submitterId?: string;
|
||||
expenseDepartment?: string;
|
||||
expenseDate?: number;
|
||||
}
|
||||
|
||||
export interface TemplateComponent {
|
||||
field?: string;
|
||||
optional?: boolean;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按模板字段白名单过滤表单:只保留模板声明过的字段 + specificationId/details。
|
||||
* 返回缺失的必填字段,供调用方明确报错(而不是让服务端 412)。
|
||||
*/
|
||||
export function filterBillFormByTemplate(
|
||||
form: Record<string, unknown>,
|
||||
components: TemplateComponent[]
|
||||
): { form: Record<string, unknown>; missingRequired: string[] } {
|
||||
const allowed = new Set<string>(["specificationId", "details"]);
|
||||
for (const component of components) {
|
||||
if (component.field) allowed.add(component.field);
|
||||
}
|
||||
const filtered: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (allowed.has(key)) filtered[key] = value;
|
||||
}
|
||||
const missingRequired = components
|
||||
.filter((component) => component.field && component.optional === false && !(component.field in filtered))
|
||||
.map((component) => component.field as string);
|
||||
return { form: filtered, missingRequired };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按费用类型 schema 过滤明细字段:费用类型没有声明的字段不发(如 feeDate)。
|
||||
* schema 拉取失败(components 为空)时保留候选字段,由服务端兜底。
|
||||
*/
|
||||
export function filterFeeTypeFormBySpec(
|
||||
candidate: Record<string, unknown>,
|
||||
components: TemplateComponent[]
|
||||
): Record<string, unknown> {
|
||||
const allowed = new Set<string>();
|
||||
for (const component of components) {
|
||||
if (component.field) allowed.add(component.field);
|
||||
}
|
||||
if (allowed.size === 0) return candidate;
|
||||
return Object.fromEntries(Object.entries(candidate).filter(([key]) => allowed.has(key)));
|
||||
}
|
||||
|
||||
export interface CreateBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
amount: string;
|
||||
feeType: string;
|
||||
}
|
||||
|
||||
interface FeeTypeNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
expenseSpecificationId?: string;
|
||||
children?: FeeTypeNode[];
|
||||
}
|
||||
|
||||
function flattenFeeTypes(nodes: FeeTypeNode[]): FeeTypeNode[] {
|
||||
const out: FeeTypeNode[] = [];
|
||||
const walk = (list: FeeTypeNode[]) => {
|
||||
for (const node of list) {
|
||||
out.push(node);
|
||||
if (Array.isArray(node.children)) walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(nodes);
|
||||
return out;
|
||||
}
|
||||
|
||||
function zeroMoney(): Record<string, unknown> {
|
||||
return {
|
||||
standard: "0",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
};
|
||||
}
|
||||
|
||||
export async function createBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: CreateBillOptions
|
||||
): Promise<CreateBillResult> {
|
||||
const templateId = options.templateId.trim();
|
||||
if (!templateId) throw new ValidationError("请通过 --template 指定单据模板 ID");
|
||||
|
||||
const specification = await getFormSpecification(client, corpId, templateId);
|
||||
if (!specification) {
|
||||
throw new NotFoundError(`未找到单据模板: ${templateId}`);
|
||||
}
|
||||
|
||||
// 创建接口要求版本化 specificationId(`<originalId>:<hash>`);
|
||||
// 用户传入的通常是 bill templates 输出的原始 ID。
|
||||
let versionedSpecificationId = templateId;
|
||||
if (!/:[0-9a-f]{32,64}$/i.test(templateId)) {
|
||||
const templates = await listBillTemplates(client, corpId);
|
||||
const hit = templates.groups
|
||||
.flatMap((group) => group.specifications)
|
||||
.find((item) => item.id === templateId || item.name === templateId);
|
||||
if (!hit) throw new NotFoundError(`未找到单据模板: ${templateId}`);
|
||||
versionedSpecificationId = hit.versionedId;
|
||||
}
|
||||
|
||||
const meResponse = await client.get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const meJson = (await meResponse.json()) as Record<string, any>;
|
||||
const staff = meJson.value?.staff ?? meJson;
|
||||
const submitterId = options.submitterId || staff.id;
|
||||
const corpDeptCandidate = (value: unknown): string | undefined => {
|
||||
if (typeof value === "string" && value && value !== corpId) return value;
|
||||
if (value && typeof value === "object" && typeof (value as any).id === "string") {
|
||||
const id = (value as any).id as string;
|
||||
return id === corpId ? undefined : id;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
let expenseDepartment =
|
||||
options.expenseDepartment ||
|
||||
corpDeptCandidate(staff.defaultDepartment) ||
|
||||
corpDeptCandidate(staff.defaultDepartmentId) ||
|
||||
corpDeptCandidate(Array.isArray(staff.departments) ? staff.departments[0] : undefined);
|
||||
if (!expenseDepartment) {
|
||||
// OpenAPI/协助身份可能只返回企业 ID 作为部门;回退到部门树第一个有效节点。
|
||||
const tree = (await getDepartmentTree(client, corpId)) as Array<Record<string, any>>;
|
||||
const flat: Array<Record<string, any>> = [];
|
||||
const walk = (nodes: Array<Record<string, any>>) => {
|
||||
for (const node of nodes) {
|
||||
flat.push(node);
|
||||
if (Array.isArray(node.children)) walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(tree);
|
||||
expenseDepartment = corpDeptCandidate(flat.find((node) => corpDeptCandidate(node.id))?.id);
|
||||
}
|
||||
if (!submitterId || !expenseDepartment) {
|
||||
throw new ValidationError("无法确定提交人或报销部门,请通过 --submitter / --department 指定");
|
||||
}
|
||||
|
||||
const feeTypes = flattenFeeTypes((await getFeeTypeTree(client, corpId)) as FeeTypeNode[]);
|
||||
const preferred = options.feeTypeName?.trim();
|
||||
const feeType =
|
||||
(preferred
|
||||
? feeTypes.find((item) => item.name === preferred && item.expenseSpecificationId)
|
||||
: undefined) ||
|
||||
feeTypes.find((item) => item.name === "简单费用" && item.expenseSpecificationId) ||
|
||||
feeTypes.find((item) => item.active !== false && item.expenseSpecificationId);
|
||||
if (!feeType?.id || !feeType.expenseSpecificationId) {
|
||||
throw new NotFoundError("未找到可用的费用类型(缺少 expenseSpecificationId)");
|
||||
}
|
||||
|
||||
const amount = options.amount?.trim() || "0.01";
|
||||
if (!Number.isFinite(Number(amount)) || Number(amount) <= 0) {
|
||||
throw new ValidationError(`金额不合法: ${amount}`);
|
||||
}
|
||||
const expenseDate = options.expenseDate ?? Date.now();
|
||||
const title = options.title?.trim() || specification.name;
|
||||
|
||||
const amountMoney = {
|
||||
standard: amount,
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
};
|
||||
const detailSpec = await getFormSpecification(client, corpId, feeType.expenseSpecificationId);
|
||||
const detailComponents = ((detailSpec as { components?: TemplateComponent[] } | undefined)?.components ??
|
||||
[]) as TemplateComponent[];
|
||||
const feeTypeForm = filterFeeTypeFormBySpec(
|
||||
{ amount: amountMoney, feeDate: expenseDate },
|
||||
detailComponents
|
||||
);
|
||||
// 金额是核心字段:即使 schema 未声明也必须保留。
|
||||
if (!("amount" in feeTypeForm)) feeTypeForm.amount = amountMoney;
|
||||
|
||||
const detail = {
|
||||
feeTypeId: feeType.id,
|
||||
specificationId: feeType.expenseSpecificationId,
|
||||
feeTypeForm,
|
||||
};
|
||||
|
||||
const candidate = {
|
||||
specificationId: versionedSpecificationId,
|
||||
title,
|
||||
submitterId,
|
||||
expenseDate,
|
||||
expenseDepartment,
|
||||
...(options.reason?.trim() ? { description: options.reason.trim() } : {}),
|
||||
details: [detail],
|
||||
};
|
||||
const { form, missingRequired } = filterBillFormByTemplate(
|
||||
candidate as Record<string, unknown>,
|
||||
((specification as { components?: TemplateComponent[] }).components ?? []) as TemplateComponent[]
|
||||
);
|
||||
if (missingRequired.length > 0) {
|
||||
throw new ValidationError(
|
||||
`模板要求以下字段但 CLI 未提供:${missingRequired.join("、")}。` +
|
||||
`当前 create 仅自动填充标准表头与一条费用明细,请补充对应模板字段后再创建。`
|
||||
);
|
||||
}
|
||||
|
||||
const response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
});
|
||||
const json = (await response.json()) as Record<string, any>;
|
||||
const value =
|
||||
(json.value && typeof json.value === "object" ? json.value : undefined) ??
|
||||
json.flow ??
|
||||
json;
|
||||
|
||||
return {
|
||||
flowId: String(value?.id ?? ""),
|
||||
code: String(value?.form?.code ?? ""),
|
||||
title,
|
||||
amount,
|
||||
feeType: feeType.name ?? "",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
validateBillDraft,
|
||||
assertBillDraftValid,
|
||||
formatValidationIssues,
|
||||
type BillDraftForm,
|
||||
} from "./draft-validation.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const SUBMIT_AT = Date.UTC(2026, 9, 23);
|
||||
const PAY_BY = Date.UTC(2026, 9, 31);
|
||||
|
||||
function makeForm(): BillDraftForm {
|
||||
return {
|
||||
title: "报销 10月AI工具费用",
|
||||
specificationId: "spec-1",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDate: SUBMIT_AT,
|
||||
expenseDepartment: "corp:dept-1",
|
||||
payeeId: "payee-1",
|
||||
法人实体: "entity-1",
|
||||
u_最晚付款日期: PAY_BY,
|
||||
description: "",
|
||||
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
payMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "321.14", standardStrCode: "CNY" },
|
||||
details: [
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 1,
|
||||
amount: {
|
||||
standard: "121.14",
|
||||
standardStrCode: "CNY",
|
||||
foreign: "2860",
|
||||
foreignStrCode: "JPY",
|
||||
rate: "0.04235664",
|
||||
},
|
||||
u_发票总金额: { standard: "121.14", standardStrCode: "CNY" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 2,
|
||||
amount: { standard: "200", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "200", standardStrCode: "CNY" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function codes(form: BillDraftForm) {
|
||||
return validateBillDraft(form).map((item) => item.code);
|
||||
}
|
||||
|
||||
describe("validateBillDraft 派生字段校验", () => {
|
||||
it("合法的两明细单据通过校验", () => {
|
||||
expect(validateBillDraft(makeForm())).toEqual([]);
|
||||
expect(formatValidationIssues([])).toContain("校验通过");
|
||||
});
|
||||
|
||||
it("拦截币种混加(USD 明细混入 CNY 单据)", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.amount = {
|
||||
standard: "250.00",
|
||||
standardStrCode: "USD",
|
||||
standardSymbol: "$",
|
||||
standardUnit: "美元",
|
||||
};
|
||||
form.expenseMoney!.standard = "371.14";
|
||||
form.payMoney!.standard = "371.14";
|
||||
expect(codes(form)).toContain("CURRENCY_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截外币金额与汇率不匹配", () => {
|
||||
const form = makeForm();
|
||||
form.details![0].feeTypeForm!.amount!.rate = "0.06";
|
||||
form.details![0].feeTypeForm!.amount!.standard = "143.00";
|
||||
form.expenseMoney!.standard = "343.00";
|
||||
form.payMoney!.standard = "343.00";
|
||||
expect(codes(form)).toContain("FOREIGN_RATE_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截报销金额与明细合计不一致", () => {
|
||||
const form = makeForm();
|
||||
form.expenseMoney!.standard = "321.00";
|
||||
form.payMoney!.standard = "321.00";
|
||||
expect(codes(form)).toContain("EXPENSE_TOTAL_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截发票总金额与明细发票合计不一致", () => {
|
||||
const form = makeForm();
|
||||
form.u_发票总金额!.standard = "321.00";
|
||||
expect(codes(form)).toContain("INVOICE_TOTAL_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截残留 draft 状态的明细", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailStatus = "draft";
|
||||
expect(codes(form)).toContain("DETAIL_DRAFT_STATUS");
|
||||
});
|
||||
|
||||
it("拦截重复的明细序号", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailNo = 1;
|
||||
expect(codes(form)).toContain("DUPLICATE_DETAIL_NO");
|
||||
});
|
||||
|
||||
it("拦截最晚付款日期早于提交日期", () => {
|
||||
const form = makeForm();
|
||||
form.u_最晚付款日期 = SUBMIT_AT - DAY;
|
||||
expect(codes(form)).toContain("PAY_DATE_BEFORE_SUBMIT");
|
||||
});
|
||||
|
||||
it("重复绑定同一张发票给出 warning", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.invoiceForm = {
|
||||
type: "exist",
|
||||
invoices: [{ invoiceId: "invoice-A" }],
|
||||
};
|
||||
const issues = validateBillDraft(form);
|
||||
const duplicate = issues.find((item) => item.code === "DUPLICATE_INVOICE");
|
||||
expect(duplicate?.severity).toBe("warning");
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertBillDraftValid", () => {
|
||||
it("合法表单不抛错", () => {
|
||||
expect(() => assertBillDraftValid(makeForm())).not.toThrow();
|
||||
});
|
||||
|
||||
it("非法表单抛出 ValidationError 并列出错误字段", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailStatus = "draft";
|
||||
try {
|
||||
assertBillDraftValid(form);
|
||||
throw new Error("should have thrown");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ValidationError);
|
||||
expect(String((error as Error).message)).toContain("detailStatus");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,426 @@
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 单据草稿的派生字段一致性校验。
|
||||
*
|
||||
* 合思服务端把「金额/币种/发票总额」等派生字段的计算责任交给前端:
|
||||
* 保存接口只做弱校验,甚至允许 CNY/USD 直接相加。CLI 在写入前必须先跑这一层,
|
||||
* 避免把语义错误的表单写回服务端。
|
||||
*/
|
||||
|
||||
export interface BillMoney {
|
||||
standard?: string | number;
|
||||
standardStrCode?: string;
|
||||
standardSymbol?: string;
|
||||
standardUnit?: string;
|
||||
standardScale?: number;
|
||||
foreign?: string | number;
|
||||
foreignStrCode?: string;
|
||||
rate?: string | number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftInvoiceRef {
|
||||
invoiceId?: string;
|
||||
taxAmount?: BillMoney;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftInvoiceForm {
|
||||
type?: string;
|
||||
invoices?: BillDraftInvoiceRef[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftDetailForm {
|
||||
amount?: BillMoney;
|
||||
u_发票总金额?: BillMoney;
|
||||
invoice?: string | number;
|
||||
invoiceForm?: BillDraftInvoiceForm;
|
||||
attachments?: unknown[];
|
||||
detailNo?: number;
|
||||
detailId?: string;
|
||||
detailStatus?: string;
|
||||
consumptionReasons?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftDetail {
|
||||
feeTypeForm?: BillDraftDetailForm;
|
||||
feeTypeId?: unknown;
|
||||
specificationId?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftForm {
|
||||
title?: string;
|
||||
specificationId?: unknown;
|
||||
submitterId?: unknown;
|
||||
expenseDate?: number;
|
||||
expenseDepartment?: unknown;
|
||||
payeeId?: unknown;
|
||||
法人实体?: unknown;
|
||||
u_最晚付款日期?: number;
|
||||
description?: string;
|
||||
expenseMoney?: BillMoney;
|
||||
payMoney?: BillMoney;
|
||||
writtenOffMoney?: BillMoney;
|
||||
u_发票总金额?: BillMoney;
|
||||
attachments?: unknown[];
|
||||
details?: BillDraftDetail[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type ValidationSeverity = "error" | "warning";
|
||||
|
||||
export interface ValidationIssue {
|
||||
code: string;
|
||||
severity: ValidationSeverity;
|
||||
field: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ValidateOptions {
|
||||
/** 金额比较容差,默认 0.005(分位) */
|
||||
moneyTolerance?: number;
|
||||
/** 外币换算比较容差,默认 0.01 */
|
||||
rateTolerance?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MONEY_TOLERANCE = 0.005;
|
||||
const DEFAULT_RATE_TOLERANCE = 0.01;
|
||||
const MAX_DESCRIPTION_LENGTH = 800;
|
||||
|
||||
function toNumber(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string" && value.trim() !== "") {
|
||||
const parsed = Number(value.replaceAll(",", ""));
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function moneyStandard(money: BillMoney | undefined): number | undefined {
|
||||
return money ? toNumber(money.standard) : undefined;
|
||||
}
|
||||
|
||||
function issue(
|
||||
code: string,
|
||||
field: string,
|
||||
message: string,
|
||||
severity: ValidationSeverity = "error"
|
||||
): ValidationIssue {
|
||||
return { code, severity, field, message };
|
||||
}
|
||||
|
||||
function nearlyEqual(a: number, b: number, tolerance: number): boolean {
|
||||
return Math.abs(a - b) <= tolerance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单张草稿表单的派生字段一致性与必填项。
|
||||
* 返回空数组代表可以安全写入。
|
||||
*/
|
||||
export function validateBillDraft(
|
||||
form: BillDraftForm | undefined,
|
||||
options: ValidateOptions = {}
|
||||
): ValidationIssue[] {
|
||||
const moneyTolerance = options.moneyTolerance ?? DEFAULT_MONEY_TOLERANCE;
|
||||
const rateTolerance = options.rateTolerance ?? DEFAULT_RATE_TOLERANCE;
|
||||
const issues: ValidationIssue[] = [];
|
||||
|
||||
if (!form) {
|
||||
return [issue("EMPTY_FORM", "form", "单据表单为空")];
|
||||
}
|
||||
|
||||
// 1. 必填表头
|
||||
const requiredHeader: Array<[keyof BillDraftForm, string]> = [
|
||||
["title", "标题"],
|
||||
["specificationId", "单据模板"],
|
||||
["submitterId", "提交人"],
|
||||
["expenseDate", "提交日期"],
|
||||
["expenseDepartment", "费用承担部门"],
|
||||
["payeeId", "收款信息"],
|
||||
["法人实体", "公司(法人实体)"],
|
||||
["u_最晚付款日期", "最晚付款日期"],
|
||||
];
|
||||
for (const [key, label] of requiredHeader) {
|
||||
const value = form[key];
|
||||
if (value === undefined || value === null || value === "") {
|
||||
issues.push(issue("MISSING_FIELD", String(key), `缺少必填字段:${label}`));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 描述长度
|
||||
const description = typeof form.description === "string" ? form.description : "";
|
||||
if (description.length > MAX_DESCRIPTION_LENGTH) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DESCRIPTION_TOO_LONG",
|
||||
"description",
|
||||
`描述长度 ${description.length} 超过模板上限 ${MAX_DESCRIPTION_LENGTH}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 明细数量
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
if (details.length === 0) {
|
||||
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
|
||||
return issues;
|
||||
}
|
||||
|
||||
// 4. 本位币(以表头报销金额为准)
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode;
|
||||
|
||||
// 5. 逐条明细
|
||||
const seenDetailNos = new Map<number, number>();
|
||||
const seenInvoiceIds = new Map<string, number>();
|
||||
|
||||
let detailAmountSum = 0;
|
||||
let detailInvoiceSum = 0;
|
||||
let hasValidDetailAmounts = true;
|
||||
|
||||
details.forEach((detail, index) => {
|
||||
const ft = detail.feeTypeForm ?? {};
|
||||
const position = index + 1;
|
||||
const label = `明细 #${ft.detailNo ?? position}`;
|
||||
|
||||
if (ft.detailStatus === "draft") {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_DRAFT_STATUS",
|
||||
`details[${index}].feeTypeForm.detailStatus`,
|
||||
`${label} 仍处于草稿状态(detailStatus=draft),提交前必须保存该明细`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof ft.detailNo === "number") {
|
||||
const previous = seenDetailNos.get(ft.detailNo);
|
||||
if (previous !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DUPLICATE_DETAIL_NO",
|
||||
`details[${index}].feeTypeForm.detailNo`,
|
||||
`明细序号 ${ft.detailNo} 重复(第 ${previous + 1} 条与第 ${position} 条)`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
seenDetailNos.set(ft.detailNo, index);
|
||||
}
|
||||
}
|
||||
|
||||
const amount = ft.amount;
|
||||
const standard = moneyStandard(amount);
|
||||
if (standard === undefined) {
|
||||
hasValidDetailAmounts = false;
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_AMOUNT_INVALID",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的本位币金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailAmountSum += standard;
|
||||
if (standard <= 0) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_AMOUNT_NOT_POSITIVE",
|
||||
`details[${index}].feeTypeForm.amount.standard`,
|
||||
`${label} 的金额为 ${standard},应大于 0`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
}
|
||||
if (billCurrency && amount?.standardStrCode && amount.standardStrCode !== billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"CURRENCY_MISMATCH",
|
||||
`details[${index}].feeTypeForm.amount.standardStrCode`,
|
||||
`${label} 的本位币币种为 ${amount.standardStrCode},与单据本位币 ${billCurrency} 不一致` +
|
||||
`(合思服务端会直接相加不同币种,必须由 CLI 拦截)`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 外币明细:foreign × rate 必须能还原 standard
|
||||
const foreign = toNumber(amount?.foreign);
|
||||
const rate = toNumber(amount?.rate);
|
||||
if (foreign !== undefined && rate !== undefined) {
|
||||
if (rate <= 0) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_RATE_INVALID",
|
||||
`details[${index}].feeTypeForm.amount.rate`,
|
||||
`${label} 的汇率为 ${rate},应大于 0`
|
||||
)
|
||||
);
|
||||
} else if (standard !== undefined && !nearlyEqual(standard, foreign * rate, rateTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_RATE_MISMATCH",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的本位币金额 ${standard} 与外币 ${foreign} × 汇率 ${rate} = ${(foreign * rate).toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (!amount?.foreignStrCode) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_FIELDS_INCOMPLETE",
|
||||
`details[${index}].feeTypeForm.amount.foreignStrCode`,
|
||||
`${label} 有外资金额但缺少 foreignStrCode`
|
||||
)
|
||||
);
|
||||
} else if (billCurrency && amount.foreignStrCode === billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_SAME_CURRENCY",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币币种与本位币相同(${billCurrency}),不应同时设置外币字段`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
}
|
||||
} else if (foreign !== undefined || rate !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_FIELDS_INCOMPLETE",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币金额与汇率必须成对出现`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 明细发票总额
|
||||
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
|
||||
if (detailInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_INVOICE_TOTAL_INVALID",
|
||||
`details[${index}].feeTypeForm.u_发票总金额`,
|
||||
`${label} 的发票总金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailInvoiceSum += detailInvoiceTotal;
|
||||
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_CURRENCY_MISMATCH",
|
||||
`details[${index}].feeTypeForm.u_发票总金额.standardStrCode`,
|
||||
`${label} 的发票总金额币种 ${ft.u_发票总金额.standardStrCode} 与单据本位币 ${billCurrency} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 发票去重
|
||||
const invoices = ft.invoiceForm?.invoices ?? [];
|
||||
for (const invoice of invoices) {
|
||||
const invoiceId = typeof invoice.invoiceId === "string" ? invoice.invoiceId : undefined;
|
||||
if (!invoiceId) continue;
|
||||
const previous = seenInvoiceIds.get(invoiceId);
|
||||
if (previous !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DUPLICATE_INVOICE",
|
||||
`details[${index}].feeTypeForm.invoiceForm.invoices`,
|
||||
`发票 ${invoiceId} 同时绑定在明细 #${previous + 1} 与 ${label}`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
} else {
|
||||
seenInvoiceIds.set(invoiceId, index);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 表头派生金额
|
||||
const expenseMoney = moneyStandard(form.expenseMoney);
|
||||
if (expenseMoney === undefined) {
|
||||
issues.push(
|
||||
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"EXPENSE_TOTAL_MISMATCH",
|
||||
"expenseMoney.standard",
|
||||
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const payMoney = moneyStandard(form.payMoney);
|
||||
if (payMoney === undefined) {
|
||||
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
|
||||
} else if (expenseMoney !== undefined) {
|
||||
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
|
||||
const expectedPay = expenseMoney - writtenOff;
|
||||
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"PAY_TOTAL_MISMATCH",
|
||||
"payMoney.standard",
|
||||
`支付金额 ${payMoney} 与报销金额 ${expenseMoney} - 核销借款 ${writtenOff} = ${expectedPay.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
|
||||
if (billInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (!nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_TOTAL_MISMATCH",
|
||||
"u_发票总金额.standard",
|
||||
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 7. 日期
|
||||
const submitAt = toNumber(form.expenseDate);
|
||||
const payBy = toNumber(form.u_最晚付款日期);
|
||||
if (submitAt !== undefined && payBy !== undefined && payBy < submitAt) {
|
||||
issues.push(
|
||||
issue(
|
||||
"PAY_DATE_BEFORE_SUBMIT",
|
||||
"u_最晚付款日期",
|
||||
`最晚付款日期 ${new Date(payBy).toLocaleDateString("zh-CN")} 早于提交日期 ${new Date(submitAt).toLocaleDateString("zh-CN")}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
/** 存在 error 级别的校验问题时抛出 ValidationError。 */
|
||||
export function assertBillDraftValid(
|
||||
form: BillDraftForm | undefined,
|
||||
options: ValidateOptions = {}
|
||||
): void {
|
||||
const issues = validateBillDraft(form, options);
|
||||
const errors = issues.filter((item) => item.severity === "error");
|
||||
if (errors.length === 0) return;
|
||||
throw new ValidationError(
|
||||
`单据校验未通过(${errors.length} 项错误):\n` +
|
||||
errors.map((item) => ` - [${item.field}] ${item.message}`).join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
/** 文本输出格式化,供 CLI 复用。 */
|
||||
export function formatValidationIssues(issues: ValidationIssue[]): string {
|
||||
if (issues.length === 0) return "✅ 单据校验通过:派生字段与必填项一致";
|
||||
return issues
|
||||
.map((item) => `${item.severity === "error" ? "❌" : "⚠️"} [${item.field}] ${item.message}`)
|
||||
.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
import * as api from "./api.js";
|
||||
import * as cache from "../../core/cache/index.js";
|
||||
import * as dimensions from "../dimension/tools.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { getTranslatorContext } from "./tools.js";
|
||||
|
||||
const rawFlow = (ids = ["invoice"]) => ({
|
||||
form: { details: [{ feeTypeForm: { invoices: ids.map((invoiceId) => ({ invoiceId })) } }] },
|
||||
});
|
||||
|
||||
describe("invoice detail cancellation", () => {
|
||||
const realSetTimeout = globalThis.setTimeout;
|
||||
const realClearTimeout = globalThis.clearTimeout;
|
||||
const originalFetch = globalThis.fetch;
|
||||
let spies: Array<{ mockRestore(): void }>;
|
||||
let deadlines: Set<ReturnType<typeof setTimeout>>;
|
||||
let scheduled: number;
|
||||
|
||||
beforeEach(() => {
|
||||
deadlines = new Set();
|
||||
scheduled = 0;
|
||||
spies = [
|
||||
spyOn(api, "getFeeTypeTree").mockResolvedValue([]),
|
||||
spyOn(api, "listActiveStaffCatalog").mockResolvedValue([]),
|
||||
spyOn(api, "getDepartmentTree").mockResolvedValue([]),
|
||||
spyOn(dimensions, "resolveDimension").mockResolvedValue(undefined as any),
|
||||
spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, load: () => unknown) => load() } as any),
|
||||
spyOn(globalThis, "setTimeout").mockImplementation(((callback: (...args: any[]) => void, delay?: number, ...args: any[]) => {
|
||||
const timer = realSetTimeout(callback, delay === 3000 ? 40 : delay, ...args);
|
||||
if (delay === 3000) {
|
||||
scheduled++;
|
||||
deadlines.add(timer);
|
||||
}
|
||||
return timer;
|
||||
}) as typeof setTimeout),
|
||||
spyOn(globalThis, "clearTimeout").mockImplementation(((timer: ReturnType<typeof setTimeout>) => {
|
||||
deadlines.delete(timer);
|
||||
realClearTimeout(timer);
|
||||
}) as typeof clearTimeout),
|
||||
];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const timer of deadlines) realClearTimeout(timer);
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
function client(fetcher: (request: Request) => Response | Promise<Response>) {
|
||||
return ky.create({ prefix: "https://invoice.example", fetch: async (input) => fetcher(input as Request) });
|
||||
}
|
||||
|
||||
it("clears the deadline on fast success without cancelling the request", async () => {
|
||||
let signal!: AbortSignal;
|
||||
const result = await getTranslatorContext(client((request) => {
|
||||
signal = request.signal;
|
||||
return Response.json({ invoice: "fast" });
|
||||
}), "corp", rawFlow());
|
||||
expect(result.invoiceDetailMap?.get("invoice")).toEqual({ invoice: "fast" });
|
||||
expect(scheduled).toBe(1);
|
||||
expect(deadlines.size).toBe(0);
|
||||
expect(signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it("aborts a pending request and preserves successful invoices", async () => {
|
||||
let aborted = false;
|
||||
const result = await getTranslatorContext(client((request) => {
|
||||
if (request.url.includes("$good")) return Response.json({ invoice: "good" });
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
aborted = true;
|
||||
reject(request.signal.reason);
|
||||
}, { once: true });
|
||||
});
|
||||
}), "corp", rawFlow(["good", "pending"]));
|
||||
expect(aborted).toBe(true);
|
||||
expect(result.invoiceDetailMap?.get("good")).toEqual({ invoice: "good" });
|
||||
expect(result.invoiceDetailMap?.has("pending")).toBe(false);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps the deadline active while reading the response body", async () => {
|
||||
let cancelled = false;
|
||||
const result = await getTranslatorContext(client((request) => new Response(new ReadableStream({
|
||||
start(controller) {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
cancelled = true;
|
||||
controller.error(request.signal.reason);
|
||||
}, { once: true });
|
||||
},
|
||||
}))), "corp", rawFlow());
|
||||
expect(cancelled).toBe(true);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not use a generic Ky client's automatic retry for a 503", async () => {
|
||||
let attempts = 0;
|
||||
const result = await getTranslatorContext(client(() => {
|
||||
attempts++;
|
||||
return new Response("unavailable", { status: 503 });
|
||||
}), "corp", rawFlow());
|
||||
expect(attempts).toBe(1);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels the existing authentication replay at the same deadline", async () => {
|
||||
let attempts = 0;
|
||||
let renewals = 0;
|
||||
let replayAborted = false;
|
||||
globalThis.fetch = (async (input: Request | URL | string, init?: RequestInit) => {
|
||||
const request = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
if (++attempts === 1) return new Response("expired", { status: 401 });
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
request.signal.addEventListener("abort", () => {
|
||||
replayAborted = true;
|
||||
reject(request.signal.reason);
|
||||
}, { once: true });
|
||||
});
|
||||
}) as typeof fetch;
|
||||
const authClient = createAuthClient({
|
||||
prefixUrl: "https://invoice.example",
|
||||
getHeaders: () => ({ accesstoken: "fixture" }),
|
||||
onUnauthorized: () => { renewals++; },
|
||||
});
|
||||
const result = await getTranslatorContext(authClient, "corp", rawFlow());
|
||||
expect(attempts).toBe(2);
|
||||
expect(renewals).toBe(1);
|
||||
expect(replayAborted).toBe(true);
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not mutate the returned map when a fetch ignores cancellation", async () => {
|
||||
let finish!: (response: Response) => void;
|
||||
const result = await getTranslatorContext(client(() => new Promise<Response>((resolve) => { finish = resolve; })), "corp", rawFlow());
|
||||
finish(Response.json({ invoice: "late" }));
|
||||
await new Promise((resolve) => realSetTimeout(resolve, 0));
|
||||
expect(result.invoiceDetailMap?.size).toBe(0);
|
||||
expect(deadlines.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not create invoice requests or deadlines when skipped", async () => {
|
||||
let attempts = 0;
|
||||
await getTranslatorContext(client(() => {
|
||||
attempts++;
|
||||
return Response.json({});
|
||||
}), "corp", rawFlow(), { skipInvoices: true });
|
||||
expect(attempts).toBe(0);
|
||||
expect(scheduled).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { getFormSpecification, getRawBillFlow } from "./api.js";
|
||||
|
||||
/**
|
||||
* 纯接口提交单据草稿。
|
||||
*
|
||||
* 流程(实测):
|
||||
* 1. `POST /api/v1/flow/plans/computed` 计算审批计划(nodes)
|
||||
* 2. `POST /api/flow/v1/flows/$<flowId>?pushMessageCode=debug`
|
||||
* body: { name: "freeflow.submit", formType, form, nodes }
|
||||
*
|
||||
* 未指派审批人的节点必须由调用方通过 `--approver` 指定,绝不自动编造。
|
||||
*/
|
||||
|
||||
export interface SubmitBillOptions {
|
||||
/** 用于补齐未指派节点的审批人(员工 ID) */
|
||||
approverId?: string;
|
||||
}
|
||||
|
||||
export interface SubmitBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
nodeCount: number;
|
||||
response: unknown;
|
||||
}
|
||||
|
||||
interface PlanNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
approverId?: unknown;
|
||||
approverIds?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export async function submitBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: SubmitBillOptions = {}
|
||||
): Promise<SubmitBillResult> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : undefined;
|
||||
if (!flow || !form) {
|
||||
throw new NotFoundError(`未找到单号或 ID 为 [${target}] 的单据`);
|
||||
}
|
||||
|
||||
const flowId = String(flow.id ?? "");
|
||||
if (!flowId) throw new NotFoundError("单据缺少流程 ID");
|
||||
if (flow.state !== "draft") {
|
||||
throw new ValidationError(`单据当前状态为 ${String(flow.state)},仅 draft 可提交`);
|
||||
}
|
||||
|
||||
const specificationId = form.specificationId;
|
||||
const spec = specificationId
|
||||
? await getFormSpecification(client, corpId, String(specificationId))
|
||||
: undefined;
|
||||
const configs = (spec as { configs?: Array<{ ability?: string; flowPlanConfigId?: string }> } | undefined)?.configs;
|
||||
const flowPlanConfigId = configs?.find((config) => config.ability === "flow")?.flowPlanConfigId;
|
||||
if (!flowPlanConfigId) {
|
||||
throw new ValidationError("模板缺少审批流配置(flowPlanConfigId),无法计算审批计划");
|
||||
}
|
||||
|
||||
const formType = String(form.type ?? flow.formType ?? "expense");
|
||||
const planResponse = await client.post("api/v1/flow/plans/computed", {
|
||||
searchParams: { corpId },
|
||||
json: { flowId, flowPlanConfigId, form, formType, params: {} },
|
||||
});
|
||||
const planJson = (await planResponse.json()) as { value?: { nodes?: PlanNode[] } };
|
||||
const nodes = planJson.value?.nodes ?? [];
|
||||
if (nodes.length === 0) {
|
||||
throw new ValidationError("审批计划为空,无法提交");
|
||||
}
|
||||
|
||||
const unassigned: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.type === "ebot") continue;
|
||||
const hasApprover =
|
||||
Boolean(node.approverId) || (Array.isArray(node.approverIds) && node.approverIds.length > 0);
|
||||
if (hasApprover) continue;
|
||||
if (options.approverId) {
|
||||
if (node.type === "countersign") node.approverIds = [options.approverId];
|
||||
else node.approverId = options.approverId;
|
||||
} else {
|
||||
unassigned.push(String(node.name ?? node.id ?? "unknown"));
|
||||
}
|
||||
}
|
||||
if (unassigned.length > 0) {
|
||||
throw new ValidationError(
|
||||
`以下审批节点未指派审批人:${unassigned.join("、")};请通过 --approver 指定员工`
|
||||
);
|
||||
}
|
||||
|
||||
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
|
||||
searchParams: { corpId, pushMessageCode: "debug" },
|
||||
json: { id: flowId, name: "freeflow.submit", formType, form, nodes },
|
||||
});
|
||||
|
||||
return {
|
||||
flowId,
|
||||
code: String(form.code ?? target),
|
||||
nodeCount: nodes.length,
|
||||
response: await response.json(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { normalizeTemplateGroups } from "./templates.js";
|
||||
|
||||
const raw = [
|
||||
{
|
||||
name: "报销单拆单",
|
||||
active: true,
|
||||
specifications: [
|
||||
{ id: "a:1", originalId: "a", name: "AI合同审批单", type: "custom", active: true },
|
||||
{ id: "a:2", originalId: "a", name: "报销单-汇总", type: "expense", active: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "历史模板",
|
||||
active: true,
|
||||
specifications: [
|
||||
{ id: "b:1", originalId: "b", name: "旧报销单", type: "expense", active: false },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "空分组",
|
||||
active: true,
|
||||
specifications: [],
|
||||
},
|
||||
{
|
||||
name: "停用分组",
|
||||
active: false,
|
||||
specifications: [
|
||||
{ id: "c:1", originalId: "c", name: "隐藏模板", type: "expense", active: true },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("normalizeTemplateGroups", () => {
|
||||
it("默认只返回启用模板,并跳过空分组/停用分组", () => {
|
||||
const result = normalizeTemplateGroups(raw);
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.inactive).toBe(1);
|
||||
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单"]);
|
||||
expect(result.groups[0].specifications.map((s) => s.name)).toEqual([
|
||||
"AI合同审批单",
|
||||
"报销单-汇总",
|
||||
]);
|
||||
});
|
||||
|
||||
it("includeInactive 返回停用模板与停用分组", () => {
|
||||
const result = normalizeTemplateGroups(raw, { includeInactive: true });
|
||||
expect(result.total).toBe(4);
|
||||
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单", "历史模板", "停用分组"]);
|
||||
const inactiveSpecs = result.groups.flatMap((g) => g.specifications).filter((s) => !s.active);
|
||||
expect(inactiveSpecs.map((s) => s.name)).toEqual(["旧报销单"]);
|
||||
});
|
||||
|
||||
it("优先使用 originalId,兼容含冒号的原始 ID", () => {
|
||||
const result = normalizeTemplateGroups([
|
||||
{
|
||||
name: "系统模板",
|
||||
active: true,
|
||||
specifications: [
|
||||
{
|
||||
id: "ID01ofWoOC1wiX:system:预算调整申请单:d3ac4cb25935090ab684d3fa4537b3517a849646",
|
||||
originalId: "ID01ofWoOC1wiX:system:预算调整申请单",
|
||||
name: "预算调整申请单",
|
||||
type: "custom",
|
||||
active: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(result.groups[0].specifications[0].id).toBe("ID01ofWoOC1wiX:system:预算调整申请单");
|
||||
expect(result.groups[0].specifications[0].versionedId).toContain(":d3ac4cb");
|
||||
});
|
||||
|
||||
it("保留分组名与模板类型", () => {
|
||||
const result = normalizeTemplateGroups(raw);
|
||||
expect(result.groups[0].specifications[0]).toMatchObject({
|
||||
id: "a",
|
||||
versionedId: "a:1",
|
||||
name: "AI合同审批单",
|
||||
type: "custom",
|
||||
group: "报销单拆单",
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { KyInstance } from "ky";
|
||||
|
||||
/**
|
||||
* 单据模板(表单规格)列表。
|
||||
*
|
||||
* 页面「快速新建单据」读的是同一个接口:
|
||||
* GET /api/form/v2/specificationGroups/withSpecificationVersioned?corpId=
|
||||
* 响应按“规格分组 → 规格”组织,且已按当前身份做过可见性过滤。
|
||||
*
|
||||
* 默认只返回启用中的模板;`includeInactive` 用于排查/管理场景。
|
||||
*/
|
||||
|
||||
export interface BillTemplateSpec {
|
||||
/** 规格组 ID(可直接用于 `bill spec <id>` / 创建单据) */
|
||||
id: string;
|
||||
/** 服务端返回的版本化 ID(`<groupId>:<versionHash>`) */
|
||||
versionedId: string;
|
||||
name: string;
|
||||
type: string;
|
||||
active: boolean;
|
||||
group: string;
|
||||
}
|
||||
|
||||
export interface BillTemplateGroup {
|
||||
name: string;
|
||||
specifications: BillTemplateSpec[];
|
||||
}
|
||||
|
||||
export interface BillTemplateList {
|
||||
groups: BillTemplateGroup[];
|
||||
total: number;
|
||||
inactive: number;
|
||||
}
|
||||
|
||||
interface RawSpecification {
|
||||
id?: string;
|
||||
originalId?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/** 去掉版本化 ID 末尾的 `:<hash>`,保留可被 `bill spec` 使用的原始 ID。 */
|
||||
function stripVersionHash(id: string): string {
|
||||
return id.replace(/:[0-9a-f]{32,64}$/i, "");
|
||||
}
|
||||
|
||||
interface RawGroup {
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
specifications?: RawSpecification[];
|
||||
}
|
||||
|
||||
export interface ListBillTemplatesOptions {
|
||||
includeInactive?: boolean;
|
||||
}
|
||||
|
||||
export function normalizeTemplateGroups(
|
||||
items: RawGroup[],
|
||||
options: ListBillTemplatesOptions = {}
|
||||
): BillTemplateList {
|
||||
const includeInactive = options.includeInactive === true;
|
||||
const groups: BillTemplateGroup[] = [];
|
||||
let total = 0;
|
||||
let inactive = 0;
|
||||
|
||||
for (const item of items) {
|
||||
if (!includeInactive && item.active === false) continue;
|
||||
const specs: BillTemplateSpec[] = [];
|
||||
for (const spec of item.specifications ?? []) {
|
||||
if (!spec.id || !spec.name) continue;
|
||||
const active = spec.active !== false;
|
||||
if (!active) {
|
||||
inactive += 1;
|
||||
if (!includeInactive) continue;
|
||||
}
|
||||
const versionedId = spec.id;
|
||||
const originalId = typeof spec.originalId === "string" && spec.originalId.trim()
|
||||
? spec.originalId
|
||||
: stripVersionHash(versionedId);
|
||||
specs.push({
|
||||
id: originalId,
|
||||
versionedId,
|
||||
name: spec.name,
|
||||
type: spec.type ?? "unknown",
|
||||
active,
|
||||
group: item.name ?? "",
|
||||
});
|
||||
total += 1;
|
||||
}
|
||||
if (specs.length > 0) {
|
||||
groups.push({ name: item.name ?? "", specifications: specs });
|
||||
}
|
||||
}
|
||||
|
||||
return { groups, total, inactive };
|
||||
}
|
||||
|
||||
export async function listBillTemplates(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: ListBillTemplatesOptions = {}
|
||||
): Promise<BillTemplateList> {
|
||||
// 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。
|
||||
const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", {
|
||||
searchParams: { corpId, _t: String(Date.now()) },
|
||||
headers: { "cache-control": "no-cache", pragma: "no-cache" },
|
||||
});
|
||||
const json = (await response.json()) as { items?: RawGroup[]; value?: { items?: RawGroup[] } };
|
||||
const items = json.items ?? json.value?.items ?? [];
|
||||
return normalizeTemplateGroups(items, options);
|
||||
}
|
||||
+58
-20
@@ -830,23 +830,39 @@ export async function getBillByCodeOrId(
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
|
||||
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
|
||||
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;
|
||||
// 1.1 如果是典型单据编号特征(如 B26010730、R2023...),优先走审批流通道检索,避免 invoice/search 接口慢超时
|
||||
if (/^[A-Za-z][A-Za-z0-9_-]+$/.test(cleanQuery)) {
|
||||
try {
|
||||
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
|
||||
if (rawFlow) {
|
||||
return [formatFlowAsBill(rawFlow, dictionary)];
|
||||
}
|
||||
} catch {
|
||||
// 容错并继续回退到传统单据检索
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
if (matched.length > 0) {
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
}
|
||||
} catch {
|
||||
// 忽略 invoice/search 超时或错误,平滑回退
|
||||
}
|
||||
|
||||
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
|
||||
@@ -1045,11 +1061,13 @@ function buildDiagnosticReport(
|
||||
|
||||
/**
|
||||
* 全域单据穿透诊断与待办全貌洞察
|
||||
* options.skipInvoices 仅保留旧 SDK 调用兼容性;此诊断不补充加载发票详情。
|
||||
*/
|
||||
export async function traceBillFlowDetail(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
targetQuery: string
|
||||
targetQuery: string,
|
||||
options?: { skipInvoices?: boolean }
|
||||
): Promise<BillFlowTraceDiagnostic> {
|
||||
const cleanTarget = targetQuery.trim();
|
||||
if (!cleanTarget) {
|
||||
@@ -1616,7 +1634,8 @@ export async function searchAndFormatBills(
|
||||
export async function getTranslatorContext(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
rawFlow?: Record<string, unknown>
|
||||
rawFlow?: Record<string, unknown>,
|
||||
options?: { skipInvoices?: boolean }
|
||||
): Promise<TranslatorOptions> {
|
||||
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
|
||||
getFeeTypeTree(client, corpId),
|
||||
@@ -1667,10 +1686,29 @@ export async function getTranslatorContext(
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceFetches = Array.from(invoiceIds).map(async (id) => {
|
||||
const detail = await getInvoiceValidationDetail(client, corpId, id);
|
||||
if (detail) invoiceDetailMap.set(id, detail);
|
||||
});
|
||||
const invoiceFetches = options?.skipInvoices
|
||||
? []
|
||||
: Array.from(invoiceIds).map(async (id) => {
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error("Invoice timeout"));
|
||||
}, 3000);
|
||||
});
|
||||
const detail = await Promise.race([
|
||||
getInvoiceValidationDetail(client, corpId, id, { signal: controller.signal }),
|
||||
deadline,
|
||||
]);
|
||||
if (detail) invoiceDetailMap.set(id, detail);
|
||||
} catch {
|
||||
// 单张发票详情超时或获取失败不阻断整体流程解析
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
|
||||
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
|
||||
const cardCandidateIds = new Set<string>();
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { EkbApiError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$<flowId>` + `name` 区分)。
|
||||
*
|
||||
* 合思把「保存 / 提交 / 删除」都收敛在同一个端点,靠 action 名区分:
|
||||
* - `freeflow.edit` —— 保存草稿
|
||||
* - `freeflow.submit` —— 提交送审(需先计算审批计划并把 nodes 带回)
|
||||
* - `freeflow.delete` —— 删除草稿
|
||||
*
|
||||
* 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。
|
||||
*/
|
||||
|
||||
async function postFlowAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string,
|
||||
name: string,
|
||||
extra: Record<string, unknown> = {},
|
||||
searchParams: Record<string, string> = {}
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
|
||||
searchParams: { corpId, ...searchParams },
|
||||
json: { id: flowId, name, ...extra },
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!text) return undefined;
|
||||
const json = JSON.parse(text) as { flow?: Record<string, unknown> };
|
||||
if (json.flow) return json.flow;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除草稿单据及其费用明细(`freeflow.delete`)。
|
||||
* 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。
|
||||
*/
|
||||
export async function deleteBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string
|
||||
): Promise<void> {
|
||||
const flow = await postFlowAction(client, corpId, flowId, "freeflow.delete");
|
||||
if (!flow) {
|
||||
throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--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 toggle <应用> <业务对象> <记录ID> [--state=true|false] [--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 --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 --keyword="关键词" [--search-fields="字段1,字段2"]`:服务端原生索引检索。缺省检索 `name` 与 `code`;指定 `--search-fields` 时,自动解析业务字段(无论标签更名还是底层代码),自动附加 `form.E_...` 命名空间及货币复合对象(`standard`)过滤,服务端秒级精准返回,杜绝客户端无边界全表扫描。
|
||||
- `records --filter="表达式"`:服务端原生 `filterBy` 过滤。支持原生 DSL 语法,同时支持简写形式(如 `--filter="客户名称~猫子"`、`--filter="不含税金额=191700"`、`--filter="状态!=停用"`),自动结合业务对象元数据映射底层物理字段与数据类型。
|
||||
- `records --where="条件"`:支持在客户端按字段中文标签或物理名做声明式组合过滤(支持 `==`, `!=`, `>`, `<`, `>=`, `<=`, `in (...)`, 以及 `&&` 联合条件)。
|
||||
- **客户端谓词早退机制(Early-Exit)**:未显式指定 `--all` 时,检索采用流式迭代,匹配满 `count`(默认 20 条)即刻终止拉取,杜绝无脑拉取全量台账导致的大流量开销与终端假死。
|
||||
- 条件在分页和写入前完整编译校验;无效语法、未知字段和歧义字段报 `ValidationError`,空结果也不会掩盖语法错误。字符串中的逗号和 `&&` 可用引号保护。
|
||||
- 归一化记录的 `fields` 支持按中文标签或原字段名选择,可组合 `--flat --fields` 或 `--ndjson --fields`。
|
||||
- `audit --check-continuous="序号字段"`:台账连续性体检,精准识别期数序号序列中的断层缺失(MISSING)与重号重复(DUPLICATE)。
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
|
||||
import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
enrichDatalinkField,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
@@ -26,7 +27,11 @@ function numberOr(value: unknown, fallback: number): number {
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
@@ -16,10 +16,12 @@ import {
|
||||
auditLedgerContinuityAndBaseline,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
buildServerFieldFilter,
|
||||
calculateEntityRecordStats,
|
||||
compileRecordPredicate,
|
||||
fetchAllEntityRecords,
|
||||
filterRecordsByPredicate,
|
||||
formatServerFieldExpr,
|
||||
iterateAllEntityRecords,
|
||||
normalizeDatalinkRecord,
|
||||
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, '\\"');
|
||||
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(
|
||||
|
||||
@@ -20,9 +20,37 @@ export const DatalinkFieldSchema = z
|
||||
unit: z.string().nullable().optional(),
|
||||
index: 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();
|
||||
|
||||
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
|
||||
.object({
|
||||
id: z.string(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { flattenFeeTypeTree } from "./tools.js";
|
||||
import { flattenFeeTypeTree, collectSubtreeNodes } from "./tools.js";
|
||||
import { FeeTypeNode } from "./types.js";
|
||||
|
||||
describe("domains/feetype > tools & helpers", () => {
|
||||
@@ -71,4 +71,15 @@ describe("domains/feetype > tools & helpers", () => {
|
||||
expect(flat[3].parentName).toBe("");
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集 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;
|
||||
items: FlatFeeTypeItem[] | FeeTypeNode[];
|
||||
rawTree: FeeTypeNode[];
|
||||
ids: string[];
|
||||
}> {
|
||||
const rawTree = options.all
|
||||
? await getFullFeeTypeTree(client, corpId)
|
||||
: await getActiveFeeTypeTree(client, corpId);
|
||||
|
||||
let flat = flattenFeeTypeTree(rawTree);
|
||||
let flat = options.subtreeParentId
|
||||
? collectSubtreeNodes(rawTree, options.subtreeParentId)
|
||||
: flattenFeeTypeTree(rawTree);
|
||||
|
||||
if (options.keyword?.trim()) {
|
||||
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 {
|
||||
total: flat.length,
|
||||
items: options.flat ? flat : (options.keyword ? flat : rawTree),
|
||||
items: useFlat ? flat : (options.keyword ? flat : rawTree),
|
||||
rawTree,
|
||||
ids,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,8 @@ export interface FeeTypeQueryOptions {
|
||||
all?: boolean;
|
||||
keyword?: string;
|
||||
flat?: boolean;
|
||||
subtreeParentId?: string;
|
||||
idsOnly?: boolean;
|
||||
}
|
||||
|
||||
export interface FeeTypeView {
|
||||
|
||||
+27
-18
@@ -28,8 +28,23 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
function throwEasoResponseError(response: Response, record?: Record<string, unknown>): never {
|
||||
const code = record?.code;
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
async function readEasoResponse(response: Response) {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
@@ -38,23 +53,17 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
if (hasCodeError) throwEasoResponseError(response, record);
|
||||
return { raw, record };
|
||||
}
|
||||
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const { raw, record } = await readEasoResponse(response);
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
if (payload === null || payload === undefined) throwEasoResponseError(response, record);
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
@@ -240,8 +249,8 @@ export async function listRunningJobs(
|
||||
const response = await client.get("api/easo/jobs/running", {
|
||||
searchParams: { pipelineId, runType },
|
||||
});
|
||||
const json = (await response.json()) as { code?: number; data?: unknown };
|
||||
const rawData = json?.data;
|
||||
const { record } = await readEasoResponse(response);
|
||||
const rawData = record?.data;
|
||||
if (!rawData) return [];
|
||||
if (Array.isArray(rawData)) {
|
||||
return z.array(WorkflowJobSchema).parse(rawData);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { z } from "zod";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { classifyCliError } from "../../cli/errors.js";
|
||||
import { listRunningJobs, unwrap } from "./api.js";
|
||||
import { watchWorkflowPipeline } from "./workflow/watch/pipeline-watcher.js";
|
||||
|
||||
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
|
||||
|
||||
describe("running jobs response contract", () => {
|
||||
for (const code of [401, 403, "401", "403"]) {
|
||||
it(`rejects business authentication failure ${JSON.stringify(code)} before empty-data normalization`, async () => {
|
||||
await expect(listRunningJobs(responding({ code, data: null, msg: "session expired" }), "wf"))
|
||||
.rejects.toBeInstanceOf(AuthenticationError);
|
||||
await expect(listRunningJobs(responding({ code, data: { id: "job" } }), "wf"))
|
||||
.rejects.toBeInstanceOf(AuthenticationError);
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves the API error category and server message for other business failures", async () => {
|
||||
await expect(listRunningJobs(responding({ code: 500, data: null, errorMessage: "backend failed" }), "wf"))
|
||||
.rejects.toMatchObject({ name: "EkbApiError", code: "EASO_API_ERROR", status: 500, message: expect.stringContaining("backend failed") });
|
||||
});
|
||||
|
||||
it("preserves successful null, missing, single-job and array responses", async () => {
|
||||
for (const body of [{ code: 200, data: null }, { code: 200 }, { data: [] }]) {
|
||||
expect(await listRunningJobs(responding(body), "wf")).toEqual([]);
|
||||
}
|
||||
const single = await listRunningJobs(responding({ code: 200, data: { jobId: "job" } }), "wf");
|
||||
expect(single.map((job) => job.id)).toEqual(["job"]);
|
||||
const array = await listRunningJobs(responding({ code: "200", data: [{ id: "one" }, { id: "two" }] }), "wf");
|
||||
expect(array.map((job) => job.id)).toEqual(["one", "two"]);
|
||||
});
|
||||
|
||||
it("does not relax unwrap's nonempty-detail requirement", async () => {
|
||||
await expect(unwrap(Response.json({ code: 200, data: null }), z.unknown())).rejects.toBeInstanceOf(EkbApiError);
|
||||
await expect(unwrap(Response.json({ code: "401", data: [] }), z.array(z.unknown()))).rejects.toBeInstanceOf(AuthenticationError);
|
||||
expect(await unwrap(Response.json({ code: 200, value: { id: "detail" } }), z.object({ id: z.string() })))
|
||||
.toEqual({ id: "detail" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("running job watcher error propagation", () => {
|
||||
function watcherClient(running: unknown, otherFailure = false) {
|
||||
let logCalls = 0;
|
||||
const client = { get: async (path: string) => {
|
||||
if (path === "api/easo/jobs/running") return Response.json(running);
|
||||
if (path.endsWith("/log")) {
|
||||
logCalls++;
|
||||
return Response.json({ code: 200, data: { jobList: logCalls > 1 || otherFailure ? [{ jobId: "job", status: "COMPLETED" }] : [] } });
|
||||
}
|
||||
if (path.endsWith("/execution/level/failed")) return Response.json({ data: { items: [] } });
|
||||
if (path.endsWith("/execution")) return Response.json({ data: [] });
|
||||
if (path === "api/easo/jobs/job") return Response.json({ data: { id: "job", pipelineId: "wf", status: "COMPLETED" } });
|
||||
return Response.json({ data: { id: "wf", label: "workflow" } });
|
||||
} } as unknown as KyInstance;
|
||||
return { client, logCalls: () => logCalls };
|
||||
}
|
||||
|
||||
for (const once of [true, false]) {
|
||||
it(`propagates running-job authentication failure in ${once ? "snapshot" : "continuous"} mode`, async () => {
|
||||
const fixture = watcherClient({ code: 401, data: null });
|
||||
try {
|
||||
await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
|
||||
throw new Error("watcher unexpectedly succeeded");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AuthenticationError);
|
||||
expect(classifyCliError(error).exitCode).toBe(11);
|
||||
}
|
||||
expect(fixture.logCalls()).toBe(once ? 0 : 1);
|
||||
});
|
||||
|
||||
it(`retains non-authentication log fallback in ${once ? "snapshot" : "continuous"} mode`, async () => {
|
||||
const fixture = watcherClient({ code: 500, data: null }, once);
|
||||
const report = await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
|
||||
expect(report.totalJobsWatched).toBe(1);
|
||||
expect(report.jobs[0]?.jobId).toBe("job");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -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 映射
|
||||
export const FieldMappingSchema = z.union([
|
||||
z.object({ key: z.string() }),
|
||||
z.object({ key: z.string(), value: z.string() }),
|
||||
]);
|
||||
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
|
||||
export const FieldMappingSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any().optional(),
|
||||
}).passthrough();
|
||||
|
||||
// 错误处理配置
|
||||
export const OnErrorSchema = z.object({
|
||||
|
||||
@@ -5,7 +5,7 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界
|
||||
## CLI 常用命令
|
||||
|
||||
```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 enum [thirdId] [--third-id=<id>] [--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}'
|
||||
```
|
||||
|
||||
- `workflow list [-q|--keyword=<关键词>] [--full]`:工作流列表。默认采用**轻量化紧凑模式**,自动剥离每个流程内部包含的庞大 `tasks` 节点树与 MVEL/JS 脚本代码(仅保留 `nodeCount` 统计与核心元数据),将输出报文体积削减 97%(从数兆降至几十 KB),彻底解决上下文截断。传入 `--full` 或 `--with-tasks` 时恢复输出完整节点树。支持 `-q / --keyword` 模糊匹配工作流名称、ID 与应用名称。
|
||||
|
||||
## 触发器分类与调测路径分支 (Path Branching)
|
||||
|
||||
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
|
||||
@@ -75,6 +77,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
|
||||
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
|
||||
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
|
||||
- 代码出参摘要使用同一执行树展开函数,覆盖条件、循环及已有子执行容器;同名节点的多次执行分别保留。
|
||||
- `logs --has-error` 包括已经产生错误的在途任务,错误标记不被 RUNNING/STARTED 覆盖。`--state` 保留原有终态筛选兼容语义,不能替代“包含错误”筛选;筛选仍针对当前返回页。
|
||||
- `job` 无法读取工作流详情时,状态显示“未知”,不会把可用 Job 的未知工作流状态显示成“已停用”。
|
||||
- `tail` 的在途任务接口先校验业务错误码,再兼容成功的空值、单对象和数组;在途任务查询的鉴权错误会终止监听并沿用 CLI 认证错误退出码,其他既有日志回退保留。
|
||||
|
||||
## 企业可用节点探针与灰度开通(Nodes Probe & Grant)
|
||||
|
||||
@@ -135,6 +141,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
|
||||
`eval-script` 使用内嵌 QuickJS/WASM 独立运行时,输入经过 JSON 复制,脚本无法访问宿主的 `process`、`Bun`、文件或网络。保留同步 JavaScript、日志和结构化执行结果;Promise 返回值明确报错。执行时间默认 3000ms,内存上限 32MiB,输入和结果各不超过 1MiB,日志最多 500 条及 64KiB。WASM 随 MCP bundle 和单文件二进制一起分发,不需要额外运行时文件。
|
||||
|
||||
MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `java.util.HashMap` / `java.util.ArrayList` 构造器、Map/List 基本方法,以及可确定的末尾顶层表达式返回;末尾表达式只求值一次,显式 `return` 继续有效。Map.size 按自身键数量计数,List.size 按元素数计数,字符串和注释不参与代码改写。其他 Java 构造器、泛型及无法确定完成值的末项复合语句明确返回 `UnsupportedMvelSyntax`,不把错误仿真结果当作成功。它不模拟 JVM 精确数值、任意 Java 方法或完整原生 MVEL;本地成功不能替代合思真实引擎的兼容性验证。
|
||||
|
||||
`node edit --file=<脚本>` 是 `--code-file` 的兼容别名;编辑字段映射使用 `--mapping-file=<JSON>`,或独立的 `node map --file=<JSON>`。不根据文件扩展名猜测用途。
|
||||
|
||||
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。
|
||||
|
||||
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
|
||||
@@ -155,6 +165,8 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
|
||||
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
|
||||
|
||||
字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。`body` 等上下文根不按节点处理,来源无法静态确定或无法解析的表达式给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。
|
||||
|
||||
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
||||
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 控制台用户重新点开节点保存时产生配置倒退;
|
||||
|
||||
@@ -53,6 +53,96 @@ const KNOWN_TYPES = new Set([
|
||||
"task-dynamic-delay",
|
||||
]);
|
||||
|
||||
interface ChooseReference {
|
||||
raw: string;
|
||||
key?: string;
|
||||
descriptor?: boolean;
|
||||
problem?: string;
|
||||
}
|
||||
|
||||
/** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */
|
||||
function extractChooseTags(val: unknown): ChooseReference[] {
|
||||
if (typeof val !== "string") return [];
|
||||
const results: ChooseReference[] = [];
|
||||
const marker = /@\{\s*choose\s*\(/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = marker.exec(val))) {
|
||||
const from = marker.lastIndex;
|
||||
let quote = "";
|
||||
let escaped = false;
|
||||
let depth = 1;
|
||||
let end = from;
|
||||
for (; end < val.length; end++) {
|
||||
const ch = val[end];
|
||||
if (quote) {
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === "\\") escaped = true;
|
||||
else if (ch === quote) quote = "";
|
||||
} else if (ch === "'" || ch === '"') quote = ch;
|
||||
else if (ch === "(") depth++;
|
||||
else if (ch === ")" && --depth === 0) break;
|
||||
}
|
||||
const close = /^\s*\}/.exec(val.slice(end + 1));
|
||||
if (depth !== 0 || !close) {
|
||||
results.push({ raw: val.slice(match.index), problem: "choose 标签未闭合或缺少结束标记" });
|
||||
continue;
|
||||
}
|
||||
marker.lastIndex = end + 1 + close[0].length;
|
||||
const raw = val.slice(match.index, marker.lastIndex);
|
||||
const argument = val.slice(from, end).trim();
|
||||
try {
|
||||
let value = argument;
|
||||
if (argument.startsWith('"')) value = JSON.parse(argument);
|
||||
else if (argument.startsWith("'")) {
|
||||
if (!argument.endsWith("'")) throw new Error("未闭合的参数字符串");
|
||||
// 单引号是模板包裹符;保留 descriptor 内 JSON 自身的转义。
|
||||
value = argument.slice(1, -1).replace(/\\'/g, "'");
|
||||
}
|
||||
if (typeof value !== "string") throw new Error("参数应为节点描述或路径");
|
||||
if (value.trim().startsWith("{")) {
|
||||
const descriptor: unknown = JSON.parse(value);
|
||||
if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record<string, unknown>).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key");
|
||||
results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true });
|
||||
} else if (/^[$\p{L}_][$\p{L}\p{N}_]*(?:\.[$\p{L}\p{N}_]+)*$/u.test(value.trim())) {
|
||||
results.push({ raw, key: value.trim(), descriptor: false });
|
||||
} else throw new Error("参数不是可静态识别的节点路径");
|
||||
} catch {
|
||||
results.push({ raw, problem: "choose 参数不是可静态识别的节点描述或路径" });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function collectExpressionValues(value: unknown, path: string, result: Array<{ key: string; value: string }>, allowEntry = false): void {
|
||||
if (typeof value === "string") result.push({ key: path, value });
|
||||
else if (Array.isArray(value)) value.forEach((item, index) => {
|
||||
collectExpressionValues(item, `${path}[${index}]`, result, true);
|
||||
});
|
||||
else if (value && typeof value === "object") {
|
||||
const entry = value as Record<string, unknown>;
|
||||
if (allowEntry && Object.hasOwn(entry, "key") && typeof entry.key === "string" && Object.hasOwn(entry, "value")) {
|
||||
// 明确 key/value 条目的 label/type 是元信息;普通映射的 label 字段仍是业务值。
|
||||
collectExpressionValues(entry.value, `${path}[${entry.key}].value`, result);
|
||||
} else {
|
||||
for (const [key, child] of Object.entries(value)) collectExpressionValues(child, `${path}.${key}`, result, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CHOOSE_CONTEXT_ROOTS = new Set(["body", "input", "inputs", "output", "outputs", "context", "ctx"]);
|
||||
|
||||
function buildTaskNameMap(tasks: WorkflowTask[]): Map<string, WorkflowTask> {
|
||||
const map = new Map<string, WorkflowTask>();
|
||||
const walk = (list: WorkflowTask[]) => {
|
||||
for (const t of list) {
|
||||
if (t.name) map.set(t.name, t);
|
||||
if (Array.isArray(t.tasks)) walk(t.tasks);
|
||||
}
|
||||
};
|
||||
walk(tasks);
|
||||
return map;
|
||||
}
|
||||
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [
|
||||
@@ -359,6 +449,8 @@ export function analyzeWorkflow(
|
||||
});
|
||||
}
|
||||
|
||||
const taskNameMap = buildTaskNameMap(detail.tasks);
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
@@ -658,6 +750,61 @@ export function analyzeWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE)
|
||||
const inspectFields: Array<{ key: string; value: string }> = [];
|
||||
const rawTask = task as Record<string, unknown>;
|
||||
for (const key of ["inputs", "fields", "mapping", "form"]) collectExpressionValues(rawTask[key], key, inspectFields);
|
||||
|
||||
for (const field of inspectFields) {
|
||||
if (typeof field.value === "string") {
|
||||
const chooseList = extractChooseTags(field.value);
|
||||
for (const item of chooseList) {
|
||||
const chooseKey = item.key;
|
||||
if (!chooseKey) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const segments = chooseKey.split(".");
|
||||
const root = segments[0];
|
||||
const rootTask = taskNameMap.get(root);
|
||||
|
||||
// 5.1 循环内使用了旧版已弃用的 control_xxx.$item 语法,前端无法解析
|
||||
if (segments[1] === "$item" && (item.descriptor || rootTask?.type === "every" || root.startsWith("control_"))) {
|
||||
const baseNodeKey = root;
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
code: "BROKEN_LOOP_ITEM_REFERENCE",
|
||||
path,
|
||||
message: `字段 [${field.key || "未知"}] 引用了旧格式循环变量 '${chooseKey}'。新版合思流程设计器要求 key 必须指向循环节点 '${baseNodeKey}' 且 properties 中显式包含 { key: "$item", label: "单条数据", type: "MAP" },当前格式在前端页面将直接报错【引用变量不存在】并阻断保存发布。`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// 5.2 引用了一个在当前工作流中根本不存在的上游节点
|
||||
const sourceKey = item.descriptor ? chooseKey : root;
|
||||
if (taskNameMap.has(sourceKey) || (!item.descriptor && CHOOSE_CONTEXT_ROOTS.has(root))) continue;
|
||||
if (item.descriptor || /^(?:action|control|trigger)_/.test(root)) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "error",
|
||||
category: "hard_block",
|
||||
code: "BROKEN_CHOOSE_REFERENCE",
|
||||
path,
|
||||
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${sourceKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
|
||||
});
|
||||
} else {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: `字段 [${field.key}] 引用了 '${chooseKey}',无法静态确定根 '${root}' 是节点还是上下文;请在真实流程设计器中确认引用来源。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { analyzeWorkflow } from "./analyzer.js";
|
||||
|
||||
const descriptor = (key: string) => `@{choose('${JSON.stringify({ key, properties: [{ key: "data" }] })}')}`;
|
||||
function analyze(config: Record<string, unknown>, sources: Array<Record<string, unknown>> = [{ name: "trigger_actual", type: "webhook" }]) {
|
||||
return analyzeWorkflow({ id: "wf", label: "test", state: 1, version: "1", tasks: [
|
||||
...sources, { name: "action_write", type: "http", ...config },
|
||||
] } as any);
|
||||
}
|
||||
|
||||
describe("choose reference containers and source classification", () => {
|
||||
test("finds missing JSON node references in direct and nested form containers", () => {
|
||||
const tag = descriptor("missing_node");
|
||||
for (const config of [
|
||||
{ fields: [{ key: "title", value: tag }] },
|
||||
{ mapping: [{ key: "title", value: tag }] },
|
||||
{ mapping: { title: { nested: [tag] } } },
|
||||
{ form: [{ key: "title", value: tag }] },
|
||||
{ form: { title: tag } },
|
||||
{ inputs: { form: { title: tag } } },
|
||||
{ inputs: [{ key: "form", value: { title: tag } }] },
|
||||
{ inputs: [{ key: "form", value: [{ key: "title", value: tag }] }] },
|
||||
]) {
|
||||
const result = analyze(config);
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(1);
|
||||
expect(result.diagnostics.find(item => item.code === "BROKEN_CHOOSE_REFERENCE")?.message).toContain("title");
|
||||
}
|
||||
});
|
||||
|
||||
test("does not inspect script, descriptions or descriptor label/type metadata", () => {
|
||||
const tag = descriptor("missing_node");
|
||||
const result = analyze({ code: `return ${JSON.stringify(tag)};`, desc: tag, label: tag, fields: [{ key: "title", label: tag, type: tag, value: "ordinary value" }], inputs: { form: { nested: { key: "title", value: "ordinary value", label: tag, type: tag } } } });
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
// A raw form object may legitimately have a business field named label.
|
||||
expect(analyze({ form: { label: tag } }).summary.passed).toBe(false);
|
||||
expect(analyze({ form: { key: "ordinary field", value: "ordinary value", label: tag } }).summary.passed).toBe(false);
|
||||
});
|
||||
|
||||
test.each([
|
||||
"@{choose(action_missing.data)}",
|
||||
"@{choose('action_missing.data')}",
|
||||
'@{choose("action_missing.data")}',
|
||||
descriptor("action_missing"),
|
||||
])("blocks a clearly identified missing node in %s", tag => {
|
||||
const result = analyze({ mapping: [{ key: "value", value: tag }] });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_CHOOSE_REFERENCE");
|
||||
});
|
||||
|
||||
test("handles multiple descriptors, escaped quotes and parentheses inside labels", () => {
|
||||
const single = `@{choose('${JSON.stringify({ key: "action_first", label: 'text (with) "quotes"', properties: [] })}')}`;
|
||||
const double = `@{choose(${JSON.stringify(JSON.stringify({ key: "action_second", properties: [] }))})}`;
|
||||
const result = analyze({ inputs: { value: `prefix ${single} / ${double} suffix` } });
|
||||
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("recognizes real custom node names while preserving body and other context roots", () => {
|
||||
for (const tag of ["@{choose(source.data)}", "@{choose('source.data')}", descriptor("source"), "@{choose('body.invoices')}", "@{choose(input.value)}"]) {
|
||||
const result = analyze({ inputs: { value: tag } }, [{ name: "source", type: "webhook" }]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("requires explicit descriptor node keys even when they resemble context roots", () => {
|
||||
for (const key of ["body", "context"]) {
|
||||
expect(analyze({ form: { title: descriptor(key) } }).summary.passed).toBe(false);
|
||||
expect(analyze({ form: { title: descriptor(key) } }, [{ name: key, type: "webhook" }]).summary.passed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("warns for unknown bare roots and unsupported or malformed expressions without blocking", () => {
|
||||
for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')", "@{choose('{bad json}')}"]) {
|
||||
const result = analyze({ form: { title: tag } });
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("UNRESOLVED_CHOOSE_REFERENCE");
|
||||
expect(result.diagnostics.every(item => item.category === "soft_advice")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["@{choose(control_loop.$item)}", "@{choose('control_loop.$item.data')}", descriptor("control_loop.$item")])("blocks old loop item paths in %s", tag => {
|
||||
const result = analyze({ fields: [{ key: "value", value: tag }] });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_LOOP_ITEM_REFERENCE");
|
||||
});
|
||||
|
||||
test("accepts the new loop descriptor with $item in properties", () => {
|
||||
const tag = `@{choose('${JSON.stringify({ key: "control_loop", properties: [{ key: "$item" }, { key: "data" }] })}')}`;
|
||||
const result = analyze({ fields: [{ key: "value", value: tag }] }, [{ name: "control_loop", type: "every", tasks: [{ name: "inner", type: "http" }] }]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
test("never aliases missing trigger_1 to an actual trigger with another name", () => {
|
||||
for (const tag of [descriptor("trigger_1"), "@{choose(trigger_1.data)}"]) {
|
||||
expect(analyze({ inputs: { value: tag } }).summary.passed).toBe(false);
|
||||
const real = analyze({ inputs: { value: tag } }, [{ name: "trigger_1", type: "webhook" }]);
|
||||
expect(real.summary.passed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("finds actual nodes in nested task containers", () => {
|
||||
const result = analyze({ fields: [{ key: "value", value: descriptor("action_nested") }] }, [
|
||||
{ name: "condition", type: "condition", tasks: [{ name: "action_nested", type: "http" }] },
|
||||
]);
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,43 @@ describe("Workflow static analysis", () => {
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
|
||||
it("detects BROKEN_LOOP_ITEM_REFERENCE and BROKEN_CHOOSE_REFERENCE", () => {
|
||||
const wf = {
|
||||
id: "wf-broken",
|
||||
label: "循环变量破坏",
|
||||
state: 1,
|
||||
version: "1",
|
||||
tasks: [
|
||||
{
|
||||
name: "control_loop",
|
||||
type: "every",
|
||||
label: "循环",
|
||||
tasks: [
|
||||
{
|
||||
name: "action_create",
|
||||
type: "ekuaibao-datalink-create",
|
||||
fields: [
|
||||
{
|
||||
key: "E_field_1",
|
||||
value: "@{choose('{\"key\":\"control_loop.$item\",\"properties\":[{\"key\":\"E_field_1\"}]}')}",
|
||||
},
|
||||
{
|
||||
key: "E_field_2",
|
||||
value: "@{choose('{\"key\":\"non_existent_node\",\"properties\":[{\"key\":\"E_field_2\"}]}')}",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any);
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("BROKEN_LOOP_ITEM_REFERENCE");
|
||||
expect(codes).toContain("BROKEN_CHOOSE_REFERENCE");
|
||||
});
|
||||
|
||||
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
|
||||
const wf = {
|
||||
id: "886351399301758976",
|
||||
|
||||
@@ -310,3 +310,45 @@ export function removeWorkflowTask(
|
||||
reindexTasks(cloned.tasks);
|
||||
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 };
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
lintMvelCode,
|
||||
lintWorkflowScripts,
|
||||
executeJavaScriptSandbox,
|
||||
executeMvelSandbox,
|
||||
} from "./index.js";
|
||||
import type { WorkflowDetail } from "../../types.js";
|
||||
|
||||
@@ -164,6 +165,27 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
|
||||
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 () => {
|
||||
const code = `
|
||||
const a = 10;
|
||||
@@ -208,7 +230,7 @@ describe("MVEL lexical boundaries", () => {
|
||||
it("does not count quoted or commented return as executable code", () => {
|
||||
const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]);
|
||||
expect(result.issues).toEqual([]); // 赋值本身可作为末尾表达式,仍不算显式 return。
|
||||
});
|
||||
|
||||
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
|
||||
@@ -254,4 +276,30 @@ describe("isolated script runtime boundaries", () => {
|
||||
expect((await executeJavaScriptSandbox('return Promise.resolve(1);')).success).toBe(false);
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasMvelFinalExpression } from "./mvel-subset.js";
|
||||
|
||||
/** Mask literals/comments without moving offsets used by diagnostics. */
|
||||
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
|
||||
@@ -84,10 +85,10 @@ export function lintMvelCode(
|
||||
|
||||
const executableCode = scanMvelCode(code, issues);
|
||||
const hasRet = /\breturn\b/.test(executableCode);
|
||||
if (!hasRet) {
|
||||
if (!hasRet && !hasMvelFinalExpression(code)) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
message: "MVEL 代码中未发现显式 return 或可确定的末尾结果表达式;请确认所需结果位于脚本末尾",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { executeJavaScriptSandbox, executeMvelSandbox } from "./sandbox.js";
|
||||
import { lintMvelCode } from "./lint-mvel.js";
|
||||
|
||||
describe("MVEL collection and completion subset", () => {
|
||||
test.each(["HashMap", "Map", "java.util.HashMap"])("returns the final Map expression constructed with %s", async kind => {
|
||||
const result = await executeMvelSandbox(`Map result = new ${kind}(); result.put("value", 7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual({ value: 7 });
|
||||
});
|
||||
|
||||
test.each(["ArrayList", "List", "java.util.ArrayList"])("supports List constructor %s", async kind => {
|
||||
const result = await executeMvelSandbox(`List result = new ${kind}(); result.add(7); result;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([7]);
|
||||
const direct = await executeMvelSandbox(`new ${kind}().size();`);
|
||||
expect(direct.success).toBe(true);
|
||||
expect(direct.returnValue).toBe(0);
|
||||
});
|
||||
|
||||
test("counts Map keys including length and prototype names, without double counting replacements", async () => {
|
||||
const result = await executeMvelSandbox(`Map m = new HashMap(); List sizes = new ArrayList();
|
||||
sizes.add(m.size()); m.put("length", 99); sizes.add(m.size());
|
||||
m.put("length", 100); sizes.add(m.size()); m.put("__proto__", 8); sizes.add(m.size());
|
||||
sizes.add(m.get("absent")); sizes;`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toEqual([0, 1, 1, 2, null]);
|
||||
});
|
||||
|
||||
test("supports nested receivers, nested arguments, indexed inputs and collection return values", async () => {
|
||||
const nested = await executeMvelSandbox(`Map m = new HashMap(); List a = new ArrayList();
|
||||
a.add(Math.max(2, 3)); m.put("items", a); m.get("items").add(m.get("items").size());
|
||||
data.get("rows")[0].put("x", 2); a.add((data.get("rows")[0]).size()); m.get("items");`, { data: { rows: [{}] } });
|
||||
expect(nested.success).toBe(true);
|
||||
expect(nested.returnValue).toEqual([3, 1, 1]);
|
||||
});
|
||||
|
||||
test("preserves literal contents while ignoring comments during conversion", async () => {
|
||||
const literal = 'String x = new java.util.HashMap(); .put("x", 1).size() / 2 ? a : b;';
|
||||
const result = await executeMvelSandbox(`/* new Unsafe(); return 8; */ // new ArrayList(2)
|
||||
${JSON.stringify(literal)}; // final comment`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(literal);
|
||||
});
|
||||
|
||||
test.each(["result", "(result);", "result;;; // final comment", "result /* ; return 0; */"])("supports tail expression %s", async tail => {
|
||||
const result = await executeMvelSandbox(`var result = 7; ${tail}`);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(7);
|
||||
});
|
||||
|
||||
test("evaluates a terminal expression once and preserves put's previous-value return", async () => {
|
||||
const increment = await executeMvelSandbox("var count = 0; ++count;");
|
||||
expect(increment.success).toBe(true);
|
||||
expect(increment.returnValue).toBe(1);
|
||||
const put = await executeMvelSandbox('Map m = new HashMap(); m.put("x", 1); m.put("x", 2);');
|
||||
expect(put.success).toBe(true);
|
||||
expect(put.returnValue).toBe(1);
|
||||
});
|
||||
|
||||
test("preserves division, ternary, classic for and explicit return compatibility", async () => {
|
||||
const result = await executeMvelSandbox("int total = 0; for (int i = 0; i < 3; i++) { total += i; } if (total == 3) { total += 2; } else { total = 0; } return total > 0 ? total / 2 : 0;");
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(2.5);
|
||||
const assignment = await executeMvelSandbox("var x = 0; x = 9;");
|
||||
expect(assignment.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test("does not reject existing JavaScript-compatible blocks before a terminal result", async () => {
|
||||
const result = await executeMvelSandbox('function value() { return 8; } var result = 0; try { throw "probe"; } catch (error) { result = value(); } finally { result += 1; } result;');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe(9);
|
||||
});
|
||||
|
||||
test.each(["new java.util.Date();", "new HashMap(5);", "new java.util.ArrayList(2);", "Map<String, Object> m = new HashMap(); m;", "if (true) { 7; }", "var value = 7;", "for (item : items) { item; } item;"])("rejects unsupported syntax or completion: %s", async code => {
|
||||
const result = await executeMvelSandbox(code);
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.name).toBe("UnsupportedMvelSyntax");
|
||||
});
|
||||
|
||||
test("fails explicitly for invalid receiver types and List bounds", async () => {
|
||||
for (const code of ['value.size();', 'value.get(1);']) {
|
||||
const result = await executeMvelSandbox(code, { value: code.includes("get") ? [] : 7 });
|
||||
expect(result.success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the execution time budget and JavaScript completion behavior", async () => {
|
||||
const result = await executeMvelSandbox("while (true) {} 7;", {}, { timeoutMs: 10 });
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error?.message).toContain("timed out");
|
||||
const js = await executeJavaScriptSandbox("7;");
|
||||
expect(js.success).toBe(true);
|
||||
expect(js.returnValue).toBeUndefined();
|
||||
});
|
||||
|
||||
test("lint accepts a final expression without changing explicit hasReturn meaning", () => {
|
||||
const result = lintMvelCode('Map result = new java.util.HashMap(); result.put("x", 7); result;');
|
||||
expect(result.hasReturn).toBe(false);
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(lintMvelCode("var x = 1;").issues.map(issue => issue.rule)).toContain("missing-return");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { ValidationError } from "../../../../core/errors.js";
|
||||
|
||||
function unsupported(message: string): never {
|
||||
throw new ValidationError(`本地 MVEL 子集不支持 ${message};请使用真实 MVEL 运行时验证`);
|
||||
}
|
||||
|
||||
/** 字符串作为完整 token 保留;注释不参与语法转换。 */
|
||||
function tokenize(source: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|>>>=|===|!==|>>>|<<=|>>=|\*\*=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|%=|<<|>>|\*\*|[{}()[\].,;:+*/%=&|^~!<>?-]/y;
|
||||
let offset = 0;
|
||||
while (offset < source.length) {
|
||||
pattern.lastIndex = offset;
|
||||
const match = pattern.exec(source);
|
||||
if (!match) unsupported(`字符 ${JSON.stringify(source[offset])}(偏移 ${offset})`);
|
||||
const token = match[0];
|
||||
offset = pattern.lastIndex;
|
||||
if (!/^\s|^\/\//.test(token) && !token.startsWith("/*")) tokens.push(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function closing(tokens: string[], start: number): number {
|
||||
const stack: string[] = [];
|
||||
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
|
||||
for (let i = start; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (pairs[token]) stack.push(pairs[token]);
|
||||
else if ([")", "]", "}"].includes(token)) {
|
||||
if (stack.pop() !== token) unsupported("不匹配的括号");
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return unsupported("未闭合的括号");
|
||||
}
|
||||
|
||||
type Statement = { start: number; end: number; kind: "expression" | "return" | "declaration" | "compound" | "empty" };
|
||||
|
||||
/** 只识别语句边界,不模拟复合语句在 MVEL 中的完成值。 */
|
||||
function statementAt(tokens: string[], start: number): Statement {
|
||||
const token = tokens[start];
|
||||
const finish = (end: number, kind: Statement["kind"]): Statement => ({ start, end, kind });
|
||||
if (token === ";") return finish(start + 1, "empty");
|
||||
if (token === "{") return finish(closing(tokens, start) + 1, "compound");
|
||||
if (["if", "for", "while", "switch"].includes(token)) {
|
||||
if (tokens[start + 1] !== "(") unsupported(`${token} 语句`);
|
||||
const conditionEnd = closing(tokens, start + 1);
|
||||
if (token === "for") {
|
||||
// 三元表达式仍可使用冒号;没有分号的增强 for 不属于本地子集。
|
||||
const header = tokens.slice(start + 2, conditionEnd);
|
||||
if (!header.includes(";") && header.includes(":")) unsupported("增强 for 循环");
|
||||
}
|
||||
if (conditionEnd + 1 >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
let end = statementAt(tokens, conditionEnd + 1).end;
|
||||
if (token === "if" && tokens[end] === "else") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "do") {
|
||||
const bodyEnd = statementAt(tokens, start + 1).end;
|
||||
if (tokens[bodyEnd] !== "while" || tokens[bodyEnd + 1] !== "(") unsupported("do/while 语句");
|
||||
const end = closing(tokens, bodyEnd + 1) + 1;
|
||||
return finish(tokens[end] === ";" ? end + 1 : end, "compound");
|
||||
}
|
||||
if (token === "try") {
|
||||
let end = statementAt(tokens, start + 1).end;
|
||||
if (tokens[end] === "catch") {
|
||||
end++;
|
||||
if (tokens[end] === "(") end = closing(tokens, end) + 1;
|
||||
end = statementAt(tokens, end).end;
|
||||
}
|
||||
if (tokens[end] === "finally") end = statementAt(tokens, end + 1).end;
|
||||
return finish(end, "compound");
|
||||
}
|
||||
if (token === "function" || token === "class") {
|
||||
let body = start + 1;
|
||||
while (body < tokens.length && tokens[body] !== "{") {
|
||||
if (tokens[body] === "(") body = closing(tokens, body);
|
||||
body++;
|
||||
}
|
||||
if (body >= tokens.length) unsupported(`${token} 缺少语句体`);
|
||||
return finish(closing(tokens, body) + 1, "declaration");
|
||||
}
|
||||
if (["catch", "finally", "import", "package"].includes(token)) unsupported(`${token} 语句`);
|
||||
let end = start;
|
||||
while (end < tokens.length && tokens[end] !== ";") {
|
||||
if (["(", "[", "{"].includes(tokens[end])) end = closing(tokens, end);
|
||||
else if ([")", "]", "}"].includes(tokens[end])) unsupported("不匹配的括号");
|
||||
end++;
|
||||
}
|
||||
if (tokens[end] === ";") end++;
|
||||
const kind = token === "return" || token === "throw" ? "return" : ["var", "let", "const"].includes(token) ? "declaration" : "expression";
|
||||
return finish(end, kind);
|
||||
}
|
||||
|
||||
function finalStatement(tokens: string[]): Statement | undefined {
|
||||
let last: Statement | undefined;
|
||||
for (let i = 0; i < tokens.length;) {
|
||||
const statement = statementAt(tokens, i);
|
||||
if (statement.kind !== "empty") last = statement;
|
||||
i = statement.end;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
const declarations = new Set(["String", "int", "Integer", "long", "Long", "double", "Double", "float", "Float", "boolean", "Boolean", "List", "Map", "HashMap", "ArrayList", "Object"]);
|
||||
|
||||
/** lint 保留 hasReturn 的显式 return 含义,同时识别可确定的末尾表达式。 */
|
||||
export function hasMvelFinalExpression(source: string): boolean {
|
||||
try {
|
||||
const tokens = tokenize(source);
|
||||
const tail = finalStatement(tokens);
|
||||
return tail?.kind === "expression" && !declarations.has(tokens[tail.start]);
|
||||
} catch {
|
||||
// 原生 MVEL 可能超出本地子集,静态 lint 不因此宣告其语法非法。
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function receiverStart(tokens: string[], end: number): number {
|
||||
let start = end;
|
||||
if (tokens[end] === ")" || tokens[end] === "]") {
|
||||
const opening = tokens[end] === ")" ? "(" : "[";
|
||||
let depth = 1;
|
||||
while (--start >= 0) {
|
||||
if (tokens[start] === tokens[end]) depth++;
|
||||
if (tokens[start] === opening && --depth === 0) break;
|
||||
}
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
const previous = tokens[start - 1];
|
||||
const previousIsName = /^[A-Za-z_$][\w$]*$/.test(previous ?? "") && !["return", "throw", "if", "while", "for", "switch"].includes(previous);
|
||||
// 数组字面量不是索引表达式;不能把前面的 return/赋值运算符当作接收对象。
|
||||
if (previousIsName || (opening === "[" && [")", "]"].includes(previous))) start = receiverStart(tokens, start - 1);
|
||||
}
|
||||
if (tokens[start - 1] === ".") start = receiverStart(tokens, start - 2);
|
||||
if (start < 0) unsupported("缺少方法接收对象");
|
||||
return start;
|
||||
}
|
||||
|
||||
const arities: Record<string, number> = { put: 2, get: 1, size: 0, add: 1 };
|
||||
|
||||
function rewriteMethods(input: string[]): string[] {
|
||||
const tokens = [...input];
|
||||
for (let i = 1; i < tokens.length - 2; i++) {
|
||||
const method = tokens[i + 1];
|
||||
if (tokens[i] !== "." || tokens[i + 2] !== "(" || !Object.hasOwn(arities, method)) continue;
|
||||
const end = closing(tokens, i + 2);
|
||||
const args: string[][] = [];
|
||||
let from = i + 3;
|
||||
for (let j = from; j < end; j++) {
|
||||
if (["(", "[", "{"].includes(tokens[j])) j = closing(tokens, j);
|
||||
else if (tokens[j] === ",") { args.push(tokens.slice(from, j)); from = j + 1; }
|
||||
}
|
||||
if (from < end) args.push(tokens.slice(from, end));
|
||||
if (args.length !== arities[method] || args.some(arg => !arg.length)) unsupported(`${method} 的该参数数量`);
|
||||
const start = receiverStart(tokens, i - 1);
|
||||
const replacement = [`__hose_mvel_${method}`, "(", ...tokens.slice(start, i)];
|
||||
for (const arg of args) replacement.push(",", ...rewriteMethods(arg));
|
||||
replacement.push(")");
|
||||
tokens.splice(start, end - start + 1, ...replacement);
|
||||
i = start + replacement.length - 1;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** 必要的 MVEL 集合与末尾表达式子集;运算仍由隔离 QuickJS 执行。 */
|
||||
export function transpileMvelSubset(source: string): string {
|
||||
const tokens = tokenize(source);
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (/^__hose_mvel_/.test(token)) unsupported("保留的内部标识符");
|
||||
if (declarations.has(token) && tokens[i + 1] === "<") unsupported("泛型声明");
|
||||
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
|
||||
if (declarations.has(token) && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 1] ?? "") && ["=", ";"].includes(tokens[i + 2])) tokens[i] = "var";
|
||||
// 2. 转换 new HashMap() / new ArrayList(),仅精确扩展两个全限定名零参构造器。
|
||||
if (token === "new") {
|
||||
let end = i + 1;
|
||||
while (/^[A-Za-z_$][\w$]*$/.test(tokens[end] ?? "") && tokens[end + 1] === ".") end += 2;
|
||||
const kind = tokens.slice(i + 1, end + 1).join("");
|
||||
const map = ["HashMap", "Map", "java.util.HashMap"].includes(kind);
|
||||
if ((!map && !["ArrayList", "List", "java.util.ArrayList"].includes(kind)) || tokens[end + 1] !== "(" || tokens[end + 2] !== ")") unsupported("该构造器、泛型或构造参数");
|
||||
tokens.splice(i, end + 3 - i, ...(map ? ["__hose_mvel_map", "(", ")"] : ["[", "]"]));
|
||||
}
|
||||
}
|
||||
// 3. 常见 Map/List 方法调用模拟:
|
||||
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
|
||||
// 注入轻量 helper;按 token 边界处理,避免直接正则冲突,并保留方法返回值。
|
||||
const rewritten = rewriteMethods(tokens);
|
||||
const tail = finalStatement(rewritten);
|
||||
if (!tail || !["return", "expression"].includes(tail.kind)) unsupported("末项复合语句或声明的完成值;请添加明确的末尾结果表达式");
|
||||
if (tail.kind === "expression") {
|
||||
const end = rewritten[tail.end - 1] === ";" ? tail.end - 1 : tail.end;
|
||||
rewritten.splice(tail.start, tail.end - tail.start, "return", "(", ...rewritten.slice(tail.start, end), ")", ";");
|
||||
}
|
||||
// 恢复并使用 helper,Map 使用自身属性,避免原型键影响集合语义。
|
||||
const preamble = `
|
||||
function __hose_mvel_map() { return Object.create(null); }
|
||||
function __hose_mvel_put(obj, key, val) { if (!obj || Array.isArray(obj) || typeof obj !== 'object') throw new TypeError('put requires Map'); if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); const old = Object.hasOwn(obj, key) ? obj[key] : null; Object.defineProperty(obj, key, {value:val, writable:true, enumerable:true, configurable:true}); return old; }
|
||||
function __hose_mvel_get(obj, key) { if (!obj || typeof obj !== 'object') throw new TypeError('get requires Map/List'); if (Array.isArray(obj)) { if (!Number.isInteger(key) || key < 0 || key >= obj.length) throw new RangeError('List index out of bounds'); } else if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); return Object.hasOwn(obj, key) ? obj[key] : null; }
|
||||
function __hose_mvel_size(obj) { if (!obj || typeof obj !== 'object') throw new TypeError('size requires Map/List'); return Array.isArray(obj) ? obj.length : Object.keys(obj).length; }
|
||||
function __hose_mvel_add(arr, item) { if (!Array.isArray(arr)) throw new TypeError('add requires List'); arr.push(item); return true; }
|
||||
`;
|
||||
return preamble + rewritten.join(" ");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import variant from "@jitl/quickjs-singlefile-cjs-release-sync";
|
||||
import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
import { transpileMvelSubset } from "./mvel-subset.js";
|
||||
|
||||
const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_VALUE_BYTES = 1024 * 1024;
|
||||
@@ -51,6 +52,11 @@ export async function executeJavaScriptSandbox(
|
||||
const value = vm.getProp(parsed.value, key);
|
||||
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(); }
|
||||
|
||||
const recordLog = (args: Parameters<typeof vm.dump>) => {
|
||||
@@ -117,3 +123,28 @@ export async function executeJavaScriptSandbox(
|
||||
runtime?.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真
|
||||
*/
|
||||
export function transpileMvelToJs(mvelCode: string): string {
|
||||
return transpileMvelSubset(mvelCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量仿真执行 MVEL 节点
|
||||
*/
|
||||
export async function executeMvelSandbox(
|
||||
code: string,
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const start = performance.now();
|
||||
try {
|
||||
const transpiled = transpileMvelToJs(code);
|
||||
return await executeJavaScriptSandbox(transpiled, inputs, options);
|
||||
} catch (error) {
|
||||
return { success: false, durationMs: Number((performance.now() - start).toFixed(2)), returnValue: undefined, logs: [],
|
||||
error: { name: "UnsupportedMvelSyntax", message: (error as Error).message }, inputs };
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { AuthenticationError } from "../../../../core/errors.js";
|
||||
import * as api from "../../api.js";
|
||||
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
|
||||
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
|
||||
@@ -76,7 +77,8 @@ export async function watchWorkflowPipeline(
|
||||
try {
|
||||
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
|
||||
if (running.length > 0) targetJobId = running[0].id;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof AuthenticationError) throw error;
|
||||
// 忽略
|
||||
}
|
||||
|
||||
@@ -149,7 +151,8 @@ export async function watchWorkflowPipeline(
|
||||
if (found) {
|
||||
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
|
||||
}
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof AuthenticationError) throw error;
|
||||
// 忽略
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user