Compare commits

...
18 Commits
Author SHA1 Message Date
yunyingk 8571390f15 Merge pull request #147 from yunyingk/release/v0.8.21
CI / validate (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
release: v0.8.21
2026-10-25 22:58:11 +08:00
gitea e98463ab23 release: v0.8.21 2026-10-25 22:56:28 +08:00
yunyingk 7ac52e7981 Merge pull request #146 from yunyingk/fix/codex-review-findings
CI / validate (push) Has been cancelled
fix: 修复工作流、身份与 CLI 的 Codex 审查问题
2026-10-25 22:50:19 +08:00
gitea a7974abb08 fix: address Codex PR review findings 2026-10-25 22:32:45 +08:00
yunyingk 0f164b6de5 Merge pull request #144 from yunyingk/feat/bill-draft-ops
CI / validate (push) Has been cancelled
feat(bill): 修复单号查询并新增草稿校验/复制/删除
2026-10-23 18:38:34 +08:00
yunyingk a6e4836d2a Merge pull request #145 from yunyingk/feat/openapi-provisional-auth-and-workflow-ux
CI / validate (push) Has been cancelled
feat(workflow): 增强工作流循环与字段变量断裂静态门禁
2026-10-23 18:29:39 +08:00
gitea 39a5a7e669 feat(workflow): 增强循环与字段变量引用断裂静态诊断硬门禁 (BROKEN_LOOP_ITEM_REFERENCE & BROKEN_CHOOSE_REFERENCE) 2026-10-23 18:22:32 +08:00
gitea ebcebbfffc fix(bill): filter detail fields by fee type schema
- 费用类型结构:feeType.expenseSpecificationId → /api/form/v2/specifications/[id]
- 明细只发 schema 声明的字段(amount/apportions),剔除 feeDate 等未声明字段
- 金额作为核心字段始终保留
2026-10-23 18:14:16 +08:00
gitea af7362a346 fix(corps): resolve whoami staff names online by id
- whoami 默认在线核验 staffs/me,配置只依赖工号
- --offline 退回本地缓存
- 并发 5、单请求 8s 超时
2026-10-23 17:58:24 +08:00
gitea a797196caa feat(cli): show acting staff identity per enterprise
- hose-use whoami: 逐企业一行显示执行身份(姓名 + 工号 + 来源)
- corps ls: 新增「员工姓名」列
- context/status 保持全局诊断
2026-10-23 17:54:16 +08:00
gitea dda9b2c7a0 fix(bill): filter create payload by template components
- 只提交模板声明过的字段,避免 412「无法识别的属性」
- 缺失必填字段时本地报错,而不是让服务端拒绝
- 版本化 specificationId 解析已在前一提交修复
2026-10-23 17:41:05 +08:00
gitea 3c00a0c0a6 feat(bill): add pure-API create and submit commands
- bill create: 按模板创建草稿(最小表单 + 一条费用明细,版本化 specificationId)
- bill submit: plans/computed 计算审批计划 → freeflow.submit(未指派节点需显式 --approver)
- 文档与 Skill 路由同步
2026-10-23 17:38:12 +08:00
gitea 1de9e3f552 fix(bill): use original template ids and bust metadata cache
- bill templates / bill spec 改用服务端 originalId(支持含冒号的原始 ID)
- 元数据 GET 增加 _t 时间戳 + no-cache,避免改名后读到缓存旧值
- skill: 业务输入必须由用户提供,禁止编造驳回意见等占位内容
2026-10-23 17:32:03 +08:00
gitea 258b347d4d fix(bill): resolve bills outside the caller's own flow list
根因:flows/my 按当前凭证身份返回“我发起”的单据,系统或其他员工创建的单据不在其中,
导致 bill get 返回 NOT FOUND(测试企业 B26000012/B26000017 复现)。

修复:新增企业级通道 POST /api/flow/v2/flows/searchByCode 兜底,
命中后再拉一次完整详情,保证表头字段齐全。
2026-10-23 17:13:32 +08:00
gitea 782466ad80 fix(bill): expose usable template group ids
- bill templates 文本输出带 ID(组 ID,可直接用于 bill spec)
- getFormSpecification 自动剥离版本后缀,兼容 <groupId>:<hash>
- 修复 bill spec <模板ID> 返回 NOT FOUND
2026-10-23 17:05:49 +08:00
gitea 9d7df10994 feat(bill): list templates grouped by specification group
- bill templates [--all] [--keyword]: 与页面快速新建同源,默认仅启用
- 服务端已按身份过滤可见性,--all 仅尝试带出停用项
- docs: README.bill.md 与 Skill 路由同步
2026-10-23 16:59:06 +08:00
gitea 5d1e3e5d8e build: refresh MCP plugin bundle for new bill commands 2026-10-23 16:48:07 +08:00
gitea 6628a546c5 feat(bill): fix code lookup and add draft validate/copy/delete
- fix: resolve bill by code/ID via flows/my + flowId detail, covering draft and paid bills
- feat: draft validation engine (currency consistency, foreign rate, totals, draft status)
- feat: bill validate, bill copy, bill delete commands
- docs: write API contracts (freeflow.edit/delete/submit, plans/computed) and skill routing
2026-10-23 16:46:42 +08:00
73 changed files with 5834 additions and 704 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.20",
"version": "0.8.21",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.20)
# hose-use (v0.8.21)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+693 -595
View File
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
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.20",
"version": "0.8.21",
"module": "src/server.ts",
"type": "module",
"exports": {
+47
View File
@@ -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 });
}
});
+24 -2
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.8.20
version: 0.8.21
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.8.20)
# hose-use (v0.8.21)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -72,6 +72,14 @@ metadata:
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 验证)"之类的占位文案代替;
- 用户没有给出时,先停下来询问;宁可多问一句,也不要替客户写业务内容。
---
@@ -106,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) |
@@ -167,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 # 查看单据预算超限和预算接口状态
@@ -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:
+2
View File
@@ -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
+5
View File
@@ -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
@@ -328,6 +330,7 @@ hose-use workflow node add <pipelineId> --type=http --label="外部通知" --par
# 4. 定向修改指定节点配置 (别名: update, set)
# 支持修改 --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
@@ -373,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
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.20",
"version": "0.8.21",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.20
version: 0.8.21
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1
View File
@@ -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` 筛选。
+14 -4
View File
@@ -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": "全局运行模式与路径配置",
@@ -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 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") }
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": "查看审批流转时间线",
+105
View File
@@ -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,
};
}
+65
View File
@@ -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,
};
}
+86
View File
@@ -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 };
}
+36 -1
View File
@@ -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`);
}
}
+9 -6
View File
@@ -207,20 +207,23 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
}
const client = await ctx.getClient();
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
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,
};
}
@@ -235,7 +238,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
},
runtime.outputOptions
),
stderr: "",
stderr: compatibilityNotice,
exitCode: 0,
};
}
@@ -294,7 +297,7 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
stderr: compatibilityNotice,
exitCode: 0,
};
}
+62
View File
@@ -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,
};
}
+64
View File
@@ -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 };
}
+83
View File
@@ -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,
};
}
+2 -2
View File
@@ -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 () => {
+6
View File
@@ -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();
+5 -1
View File
@@ -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);
+2 -1
View File
@@ -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
);
+113
View File
@@ -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,
};
}
+1
View File
@@ -22,6 +22,7 @@ function printFlowHelp(): string {
" --corp=<id> 指定操作企业 (默认激活企业)",
" --json 以 JSON 结构化格式输出诊断数据",
" --verbose 显示完整调试信息",
" --no-invoice/--noInvoice/--basic 旧版兼容空操作;穿透诊断本身不补充加载发票详情",
" -h, --help 显示帮助信息",
].join("\n");
}
+1 -1
View File
@@ -73,7 +73,7 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
: "📝 业务字段";
return [
entity.name,
field.name,
field.fieldKey ?? field.name,
field.label,
field.type,
roleTag,
@@ -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);
}
});
}
});
+8 -5
View File
@@ -39,18 +39,21 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
});
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 "正常";
};
+11 -4
View File
@@ -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 || "-",
@@ -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");
}
});
+1 -1
View File
@@ -387,7 +387,7 @@ async function handleEditNode(
}
}
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
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");
+2 -2
View File
@@ -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";
@@ -71,7 +71,7 @@ export function extractCodeNodeSummaries(
nodes: Array<any>,
flattenExecutionTreeFn?: (nodes: any[]) => any[]
): CodeNodeSummary[] {
const flattened = flattenExecutionTreeFn ? flattenExecutionTreeFn(nodes) : nodes;
const flattened = (flattenExecutionTreeFn ?? flattenExecutionTree)(nodes);
const summaries: CodeNodeSummary[] = [];
for (const node of flattened) {
@@ -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));
});
+15
View File
@@ -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
View File
@@ -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");
+4 -2
View File
@@ -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 类型不变。
+19 -1
View File
@@ -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");
});
});
+72 -5
View File
@@ -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
View File
@@ -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 {
+96
View File
@@ -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");
});
});
+149
View File
@@ -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,
};
}
+65
View File
@@ -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: [] });
});
});
+254
View File
@@ -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 ?? "",
};
}
+148
View File
@@ -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");
}
});
});
+426
View File
@@ -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");
}
+155
View File
@@ -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);
});
});
+107
View File
@@ -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(),
};
}
+85
View File
@@ -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,
});
});
});
+112
View File
@@ -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);
}
+13 -2
View File
@@ -1061,6 +1061,7 @@ function buildDiagnosticReport(
/**
* 全域单据穿透诊断与待办全貌洞察
* options.skipInvoices 仅保留旧 SDK 调用兼容性;此诊断不补充加载发票详情。
*/
export async function traceBillFlowDetail(
client: KyInstance,
@@ -1688,14 +1689,24 @@ export async function getTranslatorContext(
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),
new Promise<null>((_, reject) => setTimeout(() => reject(new Error("Invoice timeout")), 3000)),
getInvoiceValidationDetail(client, corpId, id, { signal: controller.signal }),
deadline,
]);
if (detail) invoiceDetailMap.set(id, detail);
} catch {
// 单张发票详情超时或获取失败不阻断整体流程解析
} finally {
clearTimeout(timer);
}
});
+47
View File
@@ -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);
}
}
+27 -18
View File
@@ -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);
+81
View File
@@ -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");
});
}
});
@@ -77,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)
@@ -137,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 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
@@ -157,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",
@@ -230,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", () => {
@@ -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(" ");
}
+10 -35
View File
@@ -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;
@@ -127,38 +128,7 @@ export async function executeJavaScriptSandbox(
* 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真
*/
export function transpileMvelToJs(mvelCode: string): string {
let js = mvelCode;
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
// 2. 转换 new HashMap() / new ArrayList()
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
// 3. 常见 Map/List 方法调用模拟:
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
// 注入轻量 helper
const preamble = [
"function _mvel_put(obj, key, val) { if (obj && typeof obj === 'object') { obj[key] = val; } return val; }",
"function _mvel_get(obj, key) { return obj ? obj[key] : undefined; }",
"function _mvel_size(obj) { if (!obj) return 0; if (Array.isArray(obj)) return obj.length; if (typeof obj === 'object') return Object.keys(obj).length; return 0; }",
"function _mvel_add(arr, item) { if (Array.isArray(arr)) arr.push(item); return arr; }",
"",
].join("\n");
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, ""); // 避免直接正则冲突,使用下面逐行或更精确替换
// 恢复并使用 helper
js = mvelCode;
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, "[$1] = $2");
js = js.replace(/\.size\s*\(\s*\)/g, ".length");
return `${preamble}${js}`;
return transpileMvelSubset(mvelCode);
}
/**
@@ -169,7 +139,12 @@ export async function executeMvelSandbox(
inputs: Record<string, unknown> = {},
options: { timeoutMs?: number } = {}
): Promise<ScriptEvalResult> {
const transpiled = transpileMvelToJs(code);
const result = await executeJavaScriptSandbox(transpiled, inputs, options);
return result;
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;
// 忽略
}