Compare commits

...
14 Commits
Author SHA1 Message Date
yunyingk 0e51dc9db5 Merge pull request #208 from yunyingk/release/v0.9.10
CI / validate (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Canceled after 0s
release: 发布 v0.9.10
2026-12-02 10:52:33 +08:00
gitea e9f6caa76f release: 提升版本号至 v0.9.10 并同步构建产物
- 将 `package.json`、`README.md`、`skills/hose-use/SKILL.md`、`skills/hose-aipro/SKILL.md`、`specs/hose-open-api/openapi.yaml`、`.zcode-plugin/plugin.json` 版本号由 `0.9.9` 提升至 `0.9.10`
- 重建 `specs/openapi.json` 与 plugin bundle(`dist/mcp/server.js`),通过 `check:version` 同步校验
2026-12-02 10:51:28 +08:00
yunyingk df7b583014 Merge pull request #207 from yunyingk/feat/bill-requisition-write
CI / validate (push) Canceled after 0s
feat(bill): 统一单据类型路由并适配申请单复制、编辑、校验与提交
2026-12-02 10:50:31 +08:00
gitea dd67c88f49 feat(bill): 统一单据类型路由并适配申请单复制、编辑、校验与提交
- 新增 `src/domains/bill/form-helpers.ts`:统一单据类型路由(`resolveBillFormType`:模板类型 > 流程类型 > 字段特征)、东八区日期区间解析、历史流转字段剥离、以及 `dataLinkEdits` 强制重置 `dataLinkId: null`
- 更新 `draft-validation.ts`:按类型路由明细校验(非报销单允许无 `details`)、跳过 `hide`/`hidden` 必填字段、强制拦截缺失 `dataLinkId` 键的行程条目(`DATALINK_ID_KEY_MISSING`)与非法 `feeDatePeriod`
- 更新 `copy.ts` 与 `cli/commands/bill/copy.ts`:支持申请单复制(不注入 `expenseMoney`/`payMoney`,自动升级最新启用模板版本并重置行程 `dataLinkId: null`),新增 `--reason`/`--description`、`--amount`、`--start-date`、`--end-date`
- 新增 `bill edit`(别名 `update`)草稿编辑命令与 `editBillDraft` / `updateBillFlow`,支持修改 `draft` 草稿的标题、事由、申请金额与差旅起止日期(同步联动行程日期)
- 更新 `submit.ts`:正确传递 `requisition` 等 `formType`,放行 `ebot`、自动跳过节点(`skippedType`)及条件/延迟计算节点(`conditionalType` / `laterCalcReason`)
- 补齐域层与 CLI 单元测试并同步更新 `README.bill.md` 与 `skills/hose-use/references/bill.md`
2026-12-02 10:45:25 +08:00
yunyingk debfdec77d Merge pull request #205 from yunyingk/feat/mvel-date-conversion-node
CI / validate (push) Canceled after 0s
feat(workflow): 节点只读透视与样本固化、终止节点契约修正与凭证通道规范
2026-11-24 16:59:23 +08:00
gitea d7a7203eeb fix(workflow): 纠正终止节点groupName契约,补齐凭证通道与节点契约规范
- workflow: 修正终止节点 (stop) 模板 groupName 为 action,杜绝 Piper 前端 fallback 降级为灰色扳手图标
- skill: 补充三大凭证通道矩阵规范,明确 OpenAPI 永久凭证与动态直通链接机制
- skill: 补充工作流节点 Schema 契约与图标降级防范原则,更新 workflow node inspect/sample-save 参考文档
2026-11-24 16:57:04 +08:00
gitea 86a02b82b7 feat(workflow): 支持节点只读透视与样本固化,规范企业切换上下文持久化
- skill: 补充终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) 最佳实践
- config: 修复 switchCorp / enter --switch 持久化写入 defaultCorpId 与激活 stateful 模式
- workflow node: 新增 inspect (探针透视配置/样本/执行) 与 sample-save (一键固化出参至 sampleData 并刷新选择树)
- workflow test: 新增 --save-sample 选项,调测通过后自动将产生出参的节点固化为 sampleData
- parser/metadata: 注册 save-sample 选项词汇表,补充单测 workflow-node-sample-inspect.test.ts
2026-11-24 11:45:46 +08:00
yunyingk 5e59c835f1 Merge pull request #204 from yunyingk/feat/global-timeout-support
feat: 全局支持 --timeout 和 -T 参数限制运行时间
2026-11-18 19:20:26 +08:00
gitea f9422ee431 feat: 全局支持 --timeout 和 -T 参数限制运行时间,并明确扫码登录自动交互规范
1. 为所有 hose-use 命令增加全局参数 --timeout (或 -T),允许通过命令行参数直接指定进程运行的最长时限。
2. 在 Agent 执行原则中明确扫码登录后的二维码自动渲染交互规范,确保 Agent 主动展示二维码而非被动等待。
2026-11-18 19:16:34 +08:00
gitea 41503917ce feat: 全局支持 --timeout 和 -T 参数限制运行时间
为所有 hose-use 命令增加全局参数 --timeout (或 -T),允许通过命令行参数直接指定进程运行的最长时限,超过时自动终止。适用于自动化脚本与 CI 环境的防阻塞防护。
2026-11-18 19:14:32 +08:00
yunyingk 6f60803c66 Merge pull request #203 from yunyingk/feat/login-qr-auto-save
feat: 协助平台登录支持自动保存钉钉二维码
2026-11-18 19:10:07 +08:00
gitea c63ec24344 feat: 协助平台登录支持自动保存钉钉二维码
在钉钉扫码登录流程中,自动将生成的登录二维码图片保存到本地 `~/Downloads/dingtalk-login.png`,方便用户在终端无法直接识别或使用二维码时,直接从下载目录打开图片进行扫码。
2026-11-18 19:08:35 +08:00
yunyingk 35a118c456 Merge pull request #202 from yunyingk/fix/mcp-manifest-collision
CI / validate (push) Canceled after 0s
fix(mcp): 拆分插件 MCP 清单与 Claude Code 项目配置
2026-11-18 18:55:48 +08:00
giteaandClaude 0e8d844f3f fix(mcp): 拆分插件 MCP 清单与 Claude Code 项目配置
- 根因:.mcp.json 同时被 ZCode 插件清单和 Claude Code 项目配置读取;
  项目上下文没有 ${CLAUDE_PLUGIN_ROOT} / ${user_config.*},bun 找不到
  /dist/mcp/server.js,stdio 进程立即退出并表现为 Connection closed
- 将插件清单改名为 mcp.json,plugin.json 指向 ./mcp.json,打包脚本、
  插件冒烟测试与发布校验同步更新
- 新增项目级 .mcp.json:bun src/server.ts + HOSE_USE_MCP_ENABLED=true,
  不再包含任何插件变量
- README 与打包说明区分插件清单和项目配置;发布校验增加回归断言

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 18:50:35 +08:00
42 changed files with 2743 additions and 345 deletions

No files matched your search

+2 -2
View File
@@ -4,10 +4,10 @@
"type": "stdio",
"command": "bun",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
"src/server.ts"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
"HOSE_USE_MCP_ENABLED": "true"
},
"timeoutMs": 120000
}
+2 -2
View File
@@ -1,13 +1,13 @@
{
"name": "hose-use",
"version": "0.9.9",
"version": "0.9.10",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"mcpServers": "./mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
+4 -4
View File
@@ -1,4 +1,4 @@
# hose-use (v0.9.9)
# hose-use (v0.9.10)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -138,7 +138,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install --yes` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `mcp.json` 插件清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;仓库根目录的 `.mcp.json` 是 Claude Code 项目级 MCP 配置,直接以 `bun src/server.ts` 启动当前源码;
- **MCP 单文件产物**:`bun run build:plugin` 生成 `dist/mcp/server.js`,整个 `dist/` 不纳入 Git。源码方式加载插件须先安装依赖并执行此构建;插件使用 Bun 1.3.14+ 运行,以支持共享 CLI 的 `bun:sqlite`。独立二进制的 `hose-use mcp` 已内嵌运行时,可直接启动。
- **完整插件包**:`bun run package:plugin` 从当前源码构建并生成 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,内含清单、MCP 配置、Skill 与 bundle。Release 发布此包并纳入 `checksums.txt` 和 Gitea 镜像;解包目录可作为本地插件根目录,无需源码或 `node_modules/`,仍需 Bun。打包命令需要 `tar`;详细用法见 [构建与分发说明](./src/packaging/README.packaging.md)。
@@ -155,7 +155,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
| `.github/` | CI 与 Release 工作流,负责校验、构建和发布。 |
| `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 |
| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`hose-open-api/` 是 hose-use 包装层对外 API 的 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。[hose-close-api/](./specs/hose-close-api/README.md) 保存从代码整理的合思内部接口清单与 Schema;本地临时抓包不纳入 Git。生成入口见下文。 |
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [.mcp.json](.mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
| `dist/`(本地) | 全部是已忽略的构建输出:`mcp/server.js` 是 [mcp.json](mcp.json) 引用的插件 bundle,`bin/` 保存独立二进制与发布归档。可重新构建,不随 Git 分发;删除后再次加载源码插件前须先构建。详见 [构建与分发说明](./src/packaging/README.packaging.md)。 |
| `docs/` | 跨模块参考与审阅记录;Platform 模块说明和各域 README 提供当前 CLI 与服务导航,架构总纲见 [AGENTS.md](./AGENTS.md);`reviews/` 保留历史审阅及验证证据。 |
| `enterprises/` | 仅跟踪配置示例与 [目录说明](./enterprises/README.md)。实际企业配置默认放在 `~/.config/hose-use/enterprises/`,仓库内其他企业 JSON 被忽略。 |
| `.git/` 或 `.git` 文件 | Git 元数据;独立工作树中通常是指向共享仓库的文件。 |
@@ -167,7 +167,7 @@ hose-use mcp # 启动 MCP Server (默认暴露
- [AGENTS.md](./AGENTS.md) 是项目开发规则总入口;`CLAUDE.md → AGENTS.md` 是兼容软链接,共享同一份内容。
- [package.json](./package.json)、`bun.lock` 与 [tsconfig.json](./tsconfig.json) 分别管理项目入口和命令、锁定依赖、配置 TypeScript;[.env.example](.env.example) 是环境变量示例。
- [.mcp.json](.mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
- [mcp.json](mcp.json) 声明插件 MCP 启动方式,与 `.zcode-plugin/plugin.json` 配套;[.mcp.json](.mcp.json) 是 Claude Code 项目级 MCP 配置,避免把插件变量 `${CLAUDE_PLUGIN_ROOT}` 带到项目上下文;[.gitignore](.gitignore) 声明本地数据与产物的忽略边界。
- `ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。
规范生成关系与命令:
+62
View File
@@ -9,6 +9,7 @@
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
@@ -17,6 +18,7 @@
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
"typescript": "^5.9.3",
},
@@ -37,42 +39,102 @@
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
"@types/qrcode": ["@types/qrcode@1.5.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
"@types/qrcode-terminal": ["@types/qrcode-terminal@0.12.2", "", {}, "sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q=="],
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"camelcase": ["camelcase@5.3.1", "", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="],
"cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
"dijkstrajs": ["dijkstrajs@1.0.3", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
"emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
"find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
"p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
"p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
"p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
"qrcode": ["qrcode@1.5.4", "", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
"qrcode-terminal": ["qrcode-terminal@0.12.0", "", { "bin": { "qrcode-terminal": "./bin/qrcode-terminal.js" } }, "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ=="],
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"require-main-filename": ["require-main-filename@2.0.0", "", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="],
"set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
"wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"y18n": ["y18n@4.0.3", "", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="],
"yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"hose-use": {
"type": "stdio",
"command": "bun",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
},
"timeoutMs": 120000
}
}
}
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.9.9",
"version": "0.9.10",
"module": "src/server.ts",
"type": "module",
"exports": {
@@ -49,6 +49,7 @@
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0",
"quickjs-emscripten-core": "0.32.0",
"yaml": "^2.9.0",
@@ -57,6 +58,7 @@
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
"typescript": "^5.9.3"
}
+2 -2
View File
@@ -22,13 +22,13 @@ function run(command, commandArgs) {
try {
// Explicit package inputs keep credentials, local notes and dependencies out of the archive.
for (const path of [".zcode-plugin/plugin.json", ".mcp.json", "skills"]) {
for (const path of [".zcode-plugin/plugin.json", "mcp.json", "skills"]) {
cpSync(join(root, path), join(stage, path), { recursive: true });
}
// Always build from current source; never package a stale local dist/ bundle.
run(process.execPath, [join(root, "scripts/build/build-plugin.mjs"), `--outfile=${join(stage, "dist/mcp/server.js")}`]);
mkdirSync(outputDir, { recursive: true });
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", ".mcp.json", "skills", "dist"]);
run("tar", ["-czf", archive, "-C", stage, ".zcode-plugin", "mcp.json", "skills", "dist"]);
console.log(`✓ Packaged plugin: ${archive}`);
} finally {
rmSync(stage, { recursive: true, force: true });
+1 -1
View File
@@ -17,7 +17,7 @@ test("source and freshly packaged plugin preserve offline review and MCP contrac
mkdirSync(pluginRoot);
const extracted = Bun.spawnSync(["tar", "-xzf", archive, "-C", pluginRoot]);
expect(extracted.exitCode, extracted.stderr.toString()).toBe(0);
expect(readdirSync(pluginRoot).sort()).toEqual([".mcp.json", ".zcode-plugin", "dist", "skills"]);
expect(readdirSync(pluginRoot).sort()).toEqual([".zcode-plugin", "dist", "mcp.json", "skills"]);
const manifest = JSON.parse(readFileSync(join(pluginRoot, ".zcode-plugin/plugin.json"), "utf8"));
expect(manifest.version).toBe(version);
expect(manifest.skills).toBe("skills");
+123
View File
@@ -0,0 +1,123 @@
// ==============================================================================
// 合思代码节点 (MVEL): 单据日期/日期范围字段转化为具体时间字符串与时间戳
// ==============================================================================
// ── 1. 配置区(按需修改)───────────────────────────────────────────────────────
// (1) 前置工作流节点 ID(例如:第2步单据详情节点 action_pfsq28)
upstreamNode = action_pfsq28;
// (2) 需要转化的单据层面字段 ID(例如标准起止日期 "feeDatePeriod",或自定义字段 "u_出差起止日期")
dateFieldKey = "feeDatePeriod";
// ── 2. 字段取值与防御提取 ──────────────────────────────────────────────────────
fieldVal = null;
if (upstreamNode != null) {
fieldVal = upstreamNode.get(dateFieldKey);
if (fieldVal == null && upstreamNode.get("form") != null) {
fieldVal = upstreamNode.get("form").get(dateFieldKey);
}
}
rawStart = null;
rawEnd = null;
if (fieldVal != null) {
if (fieldVal instanceof java.util.Map) {
rawStart = fieldVal.get("start");
rawEnd = fieldVal.get("end");
} else {
rawStart = fieldVal;
}
}
// ── 3. 初始化日期格式化器(强制北京时间 GMT+8) ────────────────────────────────
tz = java.util.TimeZone.getTimeZone("GMT+8");
sdfSecond = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfSecond.setTimeZone(tz);
sdfMinute = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
sdfMinute.setTimeZone(tz);
sdfDay = new java.text.SimpleDateFormat("yyyy-MM-dd");
sdfDay.setTimeZone(tz);
// ── 4. 转换开始时间 (start) ───────────────────────────────────────────────────
startStr = "";
startMinute = "";
startDay = "";
startMs = 0L;
startSec = 0L;
dStart = null;
if (rawStart != null && String.valueOf(rawStart).trim() != "") {
startMs = java.lang.Long.parseLong(String.valueOf(rawStart).trim());
if (startMs < 10000000000L) {
startMs = startMs * 1000L;
}
startSec = startMs / 1000L;
dStart = new java.util.Date(startMs);
startStr = sdfSecond.format(dStart);
startMinute = sdfMinute.format(dStart);
startDay = sdfDay.format(dStart);
}
// ── 5. 转换结束时间 (end) ─────────────────────────────────────────────────────
endStr = "";
endMinute = "";
endDay = "";
endMs = 0L;
endSec = 0L;
dEnd = null;
if (rawEnd != null && String.valueOf(rawEnd).trim() != "") {
endMs = java.lang.Long.parseLong(String.valueOf(rawEnd).trim());
if (endMs < 10000000000L) {
endMs = endMs * 1000L;
}
endSec = endMs / 1000L;
dEnd = new java.util.Date(endMs);
endStr = sdfSecond.format(dEnd);
endMinute = sdfMinute.format(dEnd);
endDay = sdfDay.format(dEnd);
}
// ── 6. 组合区间显示文本 ───────────────────────────────────────────────────────
rangeMinuteStr = "";
rangeSecondStr = "";
if (startMinute != "" && endMinute != "") {
rangeMinuteStr = startMinute + " ~ " + endMinute;
rangeSecondStr = startStr + " ~ " + endStr;
} else if (startMinute != "") {
rangeMinuteStr = startMinute;
rangeSecondStr = startStr;
}
// ── 7. 组装返回结果 ───────────────────────────────────────────────────────────
result = new java.util.HashMap();
// 开始时间 / 单个时间
result.put("startTimeStr", startStr); // 如: "2026-11-19 20:59:00"
result.put("startTimeMinute", startMinute); // 如: "2026-11-19 20:59"
result.put("startDate", startDay); // 如: "2026-11-19"
result.put("startTimestampMs", startMs); // 毫秒时间戳 (Long)
result.put("startTimestampSec", startSec); // 秒时间戳 (Long)
// 结束时间
result.put("endTimeStr", endStr); // 如: "2026-11-20 16:55:00"
result.put("endTimeMinute", endMinute); // 如: "2026-11-20 16:55"
result.put("endDate", endDay); // 如: "2026-11-20"
result.put("endTimestampMs", endMs); // 毫秒时间戳 (Long)
result.put("endTimestampSec", endSec); // 秒时间戳 (Long)
// 区间文本(方便下游直接放入 comment 或通知)
result.put("rangeMinuteStr", rangeMinuteStr); // 如: "2026-11-19 20:59 ~ 2026-11-20 16:55"
result.put("rangeSecondStr", rangeSecondStr); // 如: "2026-11-19 20:59:00 ~ 2026-11-20 16:55:00"
// 兼容单日期直接取用别名
result.put("formattedTime", startStr);
result.put("formattedMinute", startMinute);
result.put("timestampMs", startMs);
result.put("timestampSec", startSec);
return result;
+8 -1
View File
@@ -136,7 +136,14 @@ describe("release preparation and publication guards", () => {
expect(runs.some((s: string) => s.includes("verify-release.ts"))).toBe(true);
expect(runs.some((s: string) => s.includes("sha256sum hose-use-* > checksums.txt"))).toBe(true);
for (const step of [...ci.jobs.validate.steps, ...steps]) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/);
expect(JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"].command).toBe("bun");
const pluginMcp = JSON.parse(readFileSync(join(root, "mcp.json"), "utf8")).mcpServers["hose-use"];
expect(pluginMcp.command).toBe("bun");
expect(pluginMcp.args[0]).toContain("${CLAUDE_PLUGIN_ROOT}");
const projectMcp = JSON.parse(readFileSync(join(root, ".mcp.json"), "utf8")).mcpServers["hose-use"];
expect(projectMcp.command).toBe("bun");
expect(projectMcp.args).toEqual(["src/server.ts"]);
expect(JSON.stringify(projectMcp)).not.toContain("${CLAUDE_PLUGIN_ROOT}");
expect(JSON.stringify(projectMcp)).not.toContain("${user_config");
expect(release.on.workflow_dispatch.inputs.mirror_only.type).toBe("boolean");
for (const name of ["Compile multi-target binaries", "Package plugin archive", "Package release archives", "Publish GitHub Release"]) {
expect(steps.find((s: { name?: string }) => s.name === name).if).toBe("${{ !inputs.mirror_only }}");
+2 -2
View File
@@ -2,11 +2,11 @@
name: hose-aipro
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
metadata:
version: 0.9.9
version: 0.9.10
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
---
# hose-aipro (v0.9.9)
# hose-aipro (v0.9.10)
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
+13 -2
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.9.9
version: 0.9.10
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.9.9)
# hose-use (v0.9.10)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -39,6 +39,7 @@ metadata:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
- **扫码登录交互**:在执行扫码登录 (`login --qr`) 时,Agent 必须主动监控终端输出。一旦识别出二维码已保存(如提示 “💡 二维码已自动保存至: ...”),Agent **必须立即且自动**调用 `SendUserFile` 将该二维码图片渲染给用户查看,严禁等待用户主动提示。
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
@@ -97,6 +98,15 @@ metadata:
2. 关键词检索:`hose-use docs search <关键词> [--category=<分类>] [--json]`(毫秒级获取接口清单与废弃标记);
3. 单篇精细查阅:`hose-use docs show <Path|URL|名称> [--json]`(获取官方完整参数规格、类型约束与 CURL 示例);
- 细节查阅专属参考文档:[references/docs.md](./references/docs.md)。
19. **三大凭证通道矩阵与人工直通链接守则 (Three-Tier Credential Channels & Passwordless Direct Links)**:
- **通道 A:企业 OpenAPI 持久化凭证 (`appKey` + `appSecurity`)**:企业级永久凭证,永不过期。当用户/开发者提出“生成免密链接 / 去界面人工 review / 看看画布”等直达需求时,**第一首选动作**是调用 `hose-use corps link <corpId>` 或 `hose-use workflow link <pipelineId>`。底层通过 `getProvisionalAuth` 动态签发带安全签名的 Web 直达 URL(`thirdparty.html?accessToken=...` 或直接带 EASO JWT 的 Piper 画布链接),任意浏览器点开即免密登录!
- **通道 B:用户个人会话凭证 (`userAuthToken` / `cloudAuthToken`)**:个人会话凭证(手机验证码/密码),存在 TTL。供 CLI 在终端执行 API 读写、单据查询、调测。
- **通道 C:协助运营平台工单会话 (`assist-platform`)**:合思官方技术支持(实施/客服)跨企业工单流转平台(Unity)。仅限在处理客户授权工单流转时使用(`assist-platform transfer` / `assist-platform list`),**严禁**直接向用户丢出未签名的 Unity 运营平台登录页让用户手动登录。
- **非冲突双轨共存**:企业即便通过用户个人凭证登录,如果本地已配置过自建应用的 `appKey` / `appSecurity`,两者完全互不冲突、协同工作。
20. **工作流节点 Schema 规范与前端图标降级防范 (Workflow Node Schema & Fallback Trap)**:
- 合思前端微前端设计器(Piper)将节点图标分为 `action`(基础通用)与 `control`(控制节点:仅包含 condition、every、while、loop、if)两套硬编码字典;
- **终止节点 (`stop`) 必须标记为 `groupName: "action"`**(归属基础通用);若错误标记为 `control`,前端在控制字典查无此项时会触发 Fallback 降级,被强行渲染为灰色通用工具扳手(`[🔧]` `OutlinedGeneralTool`);只有保持 `groupName: "action"` 才会正常渲染为官方红色禁止标(`[⛔]` `OutlinedTipsNo`)。
- **代码节点 (`code` / `code-js2`)** 同样归属于 `action`。
---
@@ -316,6 +326,7 @@ hose-use docs sync # 强制与 docs.ekuaib
## 全局选项
- `--timeout`, `-T <seconds>`:命令全局超时时间,超时后自动终止运行。
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
- `--json`, `-j`:以标准 JSON 结构化输出结果
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
@@ -158,3 +158,22 @@ Treat tenant-specific behavior as evidence, not a universal rule. Say what assum
- **Deploy to workflow node**: `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/node_calc.mvel --yes`
- **End-to-end cloud simulation test**: `hose-use workflow test <pipelineId> --flow <billCode> --yes --force`
## 沙箱调试绝佳技巧:终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning)
在真实业务流程(尤其包含单据驳回、审批通过、企微/钉钉消息推送、台账更新等危险副作用)中调测新增的代码节点时,强烈建议采用**紧随终止节点 (Stop Node Barrier)** 模式:
```text
[前置查询/触发节点] ──> [新代码节点 (MVEL)] ──> [临时终止节点 (stop)] ──x (下游循环/驳回/审批被彻底物理隔离)
```
### 1. 为什么必须紧随终止节点?
1. **防止业务穿透与脏数据(安全第一)**:调试执行由云端真实引擎运行。若不设断点,引擎向下执行一旦命中驳回 HTTP 节点或审批同意,会向真实系统发起调用;紧随插入一个 `stop` 节点可形成绝对安全隔离,执行到代码节点后即刻安全着陆。
2. **纯净捕获真实出参**:在安全阻断的同时,当次调试 Job 的 `executionTree` 产物中能完整记录新代码节点的实际返回值(`output`),验证数据精度与格式。
### 2. 保存样本数据 (Sample Pinning) 赋能设计器下拉树
代码节点在没有样本数据(`sampleData`)前,下游节点在合思设计器中打开「引用字段」下拉菜单时**无法识别其输出属性**。
- **固化样本**:调试成功后,将当次执行的 `output` 一键回写为该节点的 `sampleData`(如使用 `hose-use workflow test ... --save-sample` 或 `workflow node sample-save`);
- **设计器自动解析**:一旦保存样本,合思工作流会自动为该代码节点生成选择器树(chooses),后续人工在配置下游驳回、条件或消息节点时,即可在界面下拉树中直接点选其格式化变量(如 `startTimeMinute`, `rangeMinuteStr`);
- **调试后清理**:业务验证并完成下游表达式配置后,在界面上手动删除该临时的终止节点即可。
+14
View File
@@ -53,6 +53,20 @@ hose-use bill get <单号|flowId>
> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中;
> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get <flowId>` 直读详情。
### 草稿复制与编辑(支持报销单与差旅申请单)
- `bill copy <单号|ID>` 支持报销单与申请单(`requisition`)自动路由:
- 复制差旅申请单时会自动清理历史流转字段、重置 `u_行程规划` 等 `dataLinkEdits` 条目为 `"dataLinkId": null`(避免审批通过后无法生成行程订单),并支持通过 `--title`、`--reason`/`--description`、`--amount`、`--start-date=YYYY-MM-DD`、`--end-date=YYYY-MM-DD` 覆写标题、事由、额度与差旅日期(联动行程内日期与天数)。
- `bill edit <单号|ID>`(别名 `update`)支持在草稿态(`draft`)修改 `--title`、`--reason`/`--description`、`--amount`(申请单)、`--start-date` 与 `--end-date`,支持 `--dry-run` 预览与 `--yes` 保存。
```bash
# 复制历史差旅申请单为新草稿(预览 → 确认)
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --dry-run
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --yes
# 修改已有草稿的标题或事由
hose-use bill edit S26005804 --title="新标题" --reason="新事由" --yes
```
---
## 2. 单据详情精准下钻 (`bill get`)
+7
View File
@@ -352,6 +352,13 @@ hose-use workflow node edit <pipelineId> 2 --set="method=GET" --yes
hose-use workflow node rm <pipelineId> action_dx9cci --dry-run
hose-use workflow node rm <pipelineId> action_dx9cci --yes
hose-use workflow node rm <pipelineId> 3 --yes
# 6. 只读探针与样本数据固化 (inspect / sample-save)
# 定向透视指定节点的固化样本数据 (sampleData) 以及最近一次调试执行出参 (execution output)
hose-use workflow node inspect <pipelineId> <nodeName>
# 将最近一次调测出参一键固化为 sampleData,使设计器下游节点可自动解析其选择器树 (chooses)
hose-use workflow node sample-save <pipelineId> <nodeName> --yes
```
---
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.9.9
version: 0.9.10
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.9.9",
"version": "0.9.10",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+19 -2
View File
@@ -15,6 +15,23 @@ process.stderr.on("error", (err: any) => {
const entryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(entryFile));
// 命令行参数超时处理:--timeout [秒] / -T [秒]
const args = process.argv.slice(2);
for (let i = args.length - 1; i >= 0; i--) {
if (args[i] === "--timeout" || args[i] === "-T") {
if (i + 1 < args.length) {
const timeoutSec = parseInt(args[i + 1], 10);
if (!isNaN(timeoutSec) && timeoutSec > 0) {
setTimeout(() => {
console.error(`[ERROR] 命令执行超时 (${timeoutSec}秒)`);
process.exit(1);
}, timeoutSec * 1000);
}
args.splice(i, 2);
}
}
}
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
const isAiPro = candidates.some((c) => {
@@ -23,8 +40,8 @@ const isAiPro = candidates.some((c) => {
});
const result = isAiPro
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
: await runCli(process.argv.slice(2), {
? await (await import("./aipro-cli.js")).runAiProCli(args)
: await runCli(args, {
appRoot,
entryFile,
writeStdout: writeStdoutChunk,
+7 -5
View File
@@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"outbound-message": "outbound"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail is-test json none once publish save-sample saveSample save-samples saveSamples snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
@@ -365,8 +365,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"attachments": "列出附件",
"download": "下载附件",
"link": "生成单据详情链接",
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态/行程dataLinkId)",
"copy": "复制单据为新草稿(支持报销单与申请单,不提交)",
"edit": "编辑草稿单据字段(仅 draft,支持标题/事由/金额/差旅日期,需 --yes)",
"delete": "删除草稿单据(仅 draft,需 --yes)",
"templates": "查看单据模板(默认仅启用,--all 含停用)",
"create": "按模板创建单据草稿(不提交)",
@@ -414,9 +415,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"files": "attachments",
"file-download": "download",
"url": "link",
"specification": "spec"
"specification": "spec",
"update": "edit"
},
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 page 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") }
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 description 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 page 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": "审批流全域透视与穿透诊断",
+15
View File
@@ -11,6 +11,9 @@ import {
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
// ... other imports ...
import os from "os";
import path from "path";
export async function handleLogin(
parsed: CliParsedArgs,
@@ -184,6 +187,18 @@ export async function handleLogin(
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
process.stdout.write(`${qrText}\n\n`);
// 自动保存二维码
const downloadsDir = path.join(os.homedir(), "Downloads");
const qrPath = path.join(downloadsDir, "dingtalk-login.png");
(async () => {
const QRCode = await import("qrcode");
await QRCode.toFile(qrPath, dingUrl);
process.stdout.write(`💡 二维码已自动保存至: ${qrPath}\n\n`);
})().catch((e: Error) => {
process.stdout.write(`[WARN] 自动保存二维码失败: ${e.message}\n\n`);
});
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
}
+1 -1
View File
@@ -8,7 +8,7 @@
|---|---|
| [search.ts](./search.ts) | 列表、详情和定位诊断 |
| [templates.ts](./templates.ts)、[meta.ts](./meta.ts) | 可用模板、字段规格、结构与链接 |
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[delete.ts](./delete.ts) | 草稿创建、复制与删除 |
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[edit.ts](./edit.ts)、[delete.ts](./delete.ts) | 草稿创建、复制(含申请单/行程适配)、编辑与删除 |
| [validate.ts](./validate.ts)、[submit.ts](./submit.ts) | 现有草稿校验及提交 |
| [approve.ts](./approve.ts) | 同意、驳回、转交、加签、评论的命令适配 |
| [flow.ts](./flow.ts)、[related.ts](./related.ts) | 审批时间线、风险预算、关联记录与附件 |
+69 -33
View File
@@ -1,53 +1,62 @@
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 { copyBillAsDraft, prepareBillCopy } from "../../../domains/bill/copy.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";
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
if (!period?.start || !period?.end) return "-";
const fmt = (ms: number) =>
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
}
/**
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
* `hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--drop-attachments] [--dry-run] --yes`
*
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
* 纯接口复制(支持报销单与差旅/常规申请单):
* 读取服务端最新表单 → 重置行程 dataLinkId 为 null / 清空发票绑定 → 一致性校验 → 创建新草稿。
* 只创建草稿,不提交。
*/
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");
throw new Error(
"请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
);
}
const title = stringOption(parsed.options, ["title"]);
const reason = stringOption(parsed.options, ["reason", "description"]);
const amount = stringOption(parsed.options, ["amount"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
const copyOptions = { title, reason, amount, startDate, endDate, keepAttachments };
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 });
const prepared = await prepareBillCopy(client, corpId, target, copyOptions);
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,
sourceTitle: prepared.sourceTitle,
title: prepared.form.title,
formType: prepared.formType,
detailCount: prepared.detailCount,
expenseMoney: prepared.expenseMoney,
amount: prepared.amount,
tripCount: prepared.tripCount,
dataLinkIdsReset: prepared.dataLinkIdsReset,
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
keepAttachments,
invoicesCleared: true,
invoicesCleared: prepared.formType === "expense",
},
runtime.outputOptions
),
@@ -55,23 +64,41 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
exitCode: 0,
};
}
const lines = [
`====== 复制单据(dry-run,未创建) ======`,
` 源单 : ${target}(${prepared.sourceTitle || "-"})`,
` 类型 : ${prepared.formType}`,
` 新标题 : ${prepared.form.title ?? "-"}`,
];
if (prepared.form.description) {
lines.push(` 事由 : ${prepared.form.description}`);
}
if (prepared.formType === "expense") {
lines.push(` 明细 : ${prepared.detailCount} 条`);
lines.push(` 金额 : ${prepared.expenseMoney} CNY`);
lines.push(` 发票 : 清空绑定,发票总额归零`);
} else {
lines.push(` 金额 : ${prepared.amount} CNY`);
if (prepared.feeDatePeriod) {
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
}
if (prepared.tripCount > 0) {
lines.push(` 行程 : ${prepared.tripCount} 条(dataLinkId 已重置为 null)`);
}
}
lines.push(` 附件 : ${keepAttachments ? "保留" : "清空"}`);
lines.push("", "提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)", "");
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`,
stdout: lines.join("\n"),
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
const result = await copyBillAsDraft(client, corpId, target, copyOptions);
if (runtime.jsonMode) {
return {
@@ -81,8 +108,11 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
flowId: result.flowId,
code: result.code,
title: result.title,
formType: result.formType,
detailCount: result.detailCount,
expenseMoney: result.expenseMoney,
amount: result.amount,
tripCount: result.tripCount,
submitted: false,
},
runtime.outputOptions
@@ -92,13 +122,19 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
};
}
const summaryLine =
result.formType === "expense"
? ` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`
: ` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`;
return {
stdout:
`复制成功(已创建草稿,未提交)\n` +
` 新单号 : ${result.code}\n` +
` 单据 ID : ${result.flowId}\n` +
` 类型 : ${result.formType}\n` +
` 标题 : ${result.title}\n` +
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
summaryLine,
stderr: "",
exitCode: 0,
};
+143
View File
@@ -0,0 +1,143 @@
import { expect, test } from "bun:test";
import { handleCopy } from "./copy.js";
import { handleEdit } from "./edit.js";
import { parseArgs } from "../../parser.js";
function makeReqFixture() {
const writes: Array<{ url: string; json: any }> = [];
const sourceForm = {
code: "S26003502",
title: "旧差旅标题",
description: "旧事由",
specificationId: `reqSpec:${"a".repeat(32)}`,
submitterId: "staff-1",
requisitionDate: 1784563200000,
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
u_差旅天数: "2",
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
u_行程规划: [
{
dataLinkId: "OLD_TRIP_ID",
dataLinkTemplateId: "tpl-trip",
dataLinkForm: { E_x_行程开始日期: "2026-07-24", E_x_行程结束日期: "2026-07-25" },
},
],
};
const draftForm = structuredClone(sourceForm) as Record<string, any>;
draftForm.code = "S26005804";
draftForm.u_行程规划[0].dataLinkId = null;
const client = {
get: (url: string) => ({
json: async () => {
if (url.includes("specifications/")) {
return {
items: [
{
id: "reqSpec",
name: "4.1日常差旅申请单",
type: "requisition",
components: [
{ field: "title", optional: false },
{ field: "u_行程规划", type: "dataLinkEdits", optional: false },
],
},
],
};
}
return { items: [] };
},
}),
post: (url: string, payload: { json: any }) => ({
json: async () => {
if (url.endsWith("/flows/searchByCode")) {
return {
items: [
{ id: "ID01SRC", form: sourceForm },
{ id: "ID01DRAFT", form: draftForm },
],
};
}
if (url.includes("/flows/flowId/")) {
const isDraft = url.includes("ID01DRAFT");
return {
value: {
id: isDraft ? "ID01DRAFT" : "ID01SRC",
state: isDraft ? "draft" : "paid",
formType: "requisition",
form: isDraft ? draftForm : sourceForm,
},
};
}
if (url.includes("/backlogs/") || url.endsWith("/flows/my") || url.endsWith("/flows/approved") || url.endsWith("/carbonCopy/search")) {
return { items: [] };
}
writes.push({ url, json: payload.json });
return { flow: { id: "ID01DRAFT", form: { ...(payload.json?.form ?? {}), code: payload.json?.form?.code ?? "S26005999" } } };
},
}),
};
const context = (args: string[]) =>
({
parsed: parseArgs(args),
runtime: { jsonMode: true },
corpId: "corp",
getClient: async () => client,
requireWriteConfirmation: async () => {},
}) as any;
return { writes, context };
}
test("bill copy 支持申请单 --dry-run 预览并校验,不发写请求", async () => {
const { writes, context } = makeReqFixture();
const res = await handleCopy(
context([
"bill",
"copy",
"S26003502",
"--title",
"新差旅标题",
"--reason",
"团建",
"--amount",
"1000",
"--start-date",
"2026-12-04",
"--end-date",
"2026-12-05",
"--dry-run",
"--json",
])
);
const out = JSON.parse(res.stdout);
expect(out.dryRun).toBe(true);
expect(out.formType).toBe("requisition");
expect(out.tripCount).toBe(1);
expect(out.dataLinkIdsReset).toBe(true);
expect(out.amount).toBe("1000");
expect(writes).toEqual([]);
});
test("bill edit 支持 --dry-run 预览与 --yes 保存草稿", async () => {
const { writes, context } = makeReqFixture();
const preview = await handleEdit(
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--dry-run", "--json"])
);
const pOut = JSON.parse(preview.stdout);
expect(pOut.dryRun).toBe(true);
expect(pOut.beforeTitle).toBe("旧差旅标题");
expect(pOut.afterTitle).toBe("更新后标题");
expect(writes).toEqual([]);
const saved = await handleEdit(
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--yes", "--json"])
);
const sOut = JSON.parse(saved.stdout);
expect(sOut.updated).toBe(true);
expect(sOut.title).toBe("更新后标题");
expect(sOut.description).toBe("新事由");
expect(writes).toHaveLength(1);
expect(writes[0].json.name).toBe("freeflow.edit");
});
+120
View File
@@ -0,0 +1,120 @@
import { editBillDraft, prepareBillEdit } 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";
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
if (!period?.start || !period?.end) return "-";
const fmt = (ms: number) =>
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
}
/**
* `hose-use bill edit <单号|ID> [--title=...] [--reason=...] [--description=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--dry-run] --yes`
*
* 仅允许编辑 `draft` 状态草稿(`freeflow.edit`)。
*/
export async function handleEdit(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 edit <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
);
}
const title = stringOption(parsed.options, ["title"]);
const reason = stringOption(parsed.options, ["reason", "description"]);
const amount = stringOption(parsed.options, ["amount"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
const editOptions = { title, reason, amount, startDate, endDate };
const client = await ctx.getClient();
if (isDryRun(parsed, runtime)) {
const prepared = await prepareBillEdit(client, corpId, target, editOptions);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
dryRun: true,
code: prepared.code,
flowId: prepared.flowId,
formType: prepared.formType,
beforeTitle: prepared.beforeTitle,
afterTitle: prepared.afterTitle,
beforeDescription: prepared.beforeDescription,
afterDescription: prepared.afterDescription,
amount: prepared.amount,
tripCount: prepared.tripCount,
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const lines = [
`====== 编辑草稿(dry-run,未保存) ======`,
` 单号 : ${prepared.code}(${prepared.flowId})`,
` 类型 : ${prepared.formType}`,
` 标题 : ${prepared.beforeTitle === prepared.afterTitle ? prepared.afterTitle : `${prepared.beforeTitle} -> ${prepared.afterTitle}`}`,
` 事由 : ${prepared.beforeDescription === prepared.afterDescription ? (prepared.afterDescription || "-") : `${prepared.beforeDescription || "(空)"} -> ${prepared.afterDescription || "(空)"}`}`,
` 金额 : ${prepared.amount} CNY`,
];
if (prepared.feeDatePeriod) {
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
}
if (prepared.tripCount > 0) {
lines.push(` 行程 : ${prepared.tripCount} 条`);
}
lines.push("", "提示: 确认无误后追加 --yes 保存草稿(不会提交)", "");
return {
stdout: lines.join("\n"),
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
const result = await editBillDraft(client, corpId, target, editOptions);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
updated: true,
code: result.code,
flowId: result.flowId,
title: result.title,
description: result.description,
formType: result.formType,
amount: result.amount,
tripCount: result.tripCount,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout:
`草稿保存成功(未提交)\n` +
` 单号 : ${result.code}\n` +
` 单据 ID : ${result.flowId}\n` +
` 标题 : ${result.title}\n` +
` 事由 : ${result.description || "-"}\n` +
` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`,
stderr: "",
exitCode: 0,
};
}
+6 -1
View File
@@ -7,6 +7,7 @@ import { handleRefs, handleRelations, handleAttachments, handleDownload } from "
import { handleSchema, handleLink, handleSpec } from "./meta.js";
import { handleValidate } from "./validate.js";
import { handleCopy } from "./copy.js";
import { handleEdit } from "./edit.js";
import { handleDelete } from "./delete.js";
import { handleTemplates } from "./templates.js";
import { handleCreate } from "./create.js";
@@ -120,6 +121,10 @@ export async function handleBillCommand(
case "clone":
return handleCopy(ctx);
case "edit":
case "update":
return handleEdit(ctx);
case "delete":
case "rm":
case "remove":
@@ -140,6 +145,6 @@ export async function handleBillCommand(
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 <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, edit <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
}
}
@@ -0,0 +1,478 @@
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { handleWorkflowCommand } from "./workflow/index.js";
import * as helpers from "./workflow/shared.js";
import { CorpContext } from "../../core/config/manager.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { CliRuntime } from "../types.js";
const mockCorp: CorpConfig = {
id: "ID01ofWoOC1wiX",
name: "沈玥妍测试企业",
baseUrl: "https://app.ekuaibao.com",
cluster: "app",
source: "link",
credentials: {
accessToken: "test-token",
corpId: "ID01ofWoOC1wiX",
staffId: "ID01ofWoOC1wiX:ID01KsDgHaH5nN",
},
env: "test",
isTest: true,
};
describe("CLI - workflow node inspect 与 sample-save (只读探针与样本一键固化)", () => {
let spies: any[] = [];
let mockRuntime: CliRuntime;
beforeEach(() => {
spies = [];
const corpContext = new CorpContext([mockCorp], { stateful: true, defaultCorpId: mockCorp.id });
mockRuntime = {
corpContext,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
});
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("workflow node inspect: 成功透视节点配置、已存样本与历史调试出参", async () => {
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-ebot-trigger",
label: "EBOT触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_calc_1",
type: "code",
label: "代码节点",
displayName: "时间转换节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "result = ['minute': '2026-11-19 20:59'];\nreturn result;",
sampleData: {
minute: "2026-11-19 20:59",
},
},
];
const mockDetail = {
id: "wf_inspect_test",
label: "测试工作流",
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_1",
name: "action_calc_1",
status: "COMPLETED",
executionTime: 8,
output: {
minute: "2026-11-19 20:59",
timestampMs: 1795093140000,
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_inspect_test/log")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({
code: 200,
data: {
totalCount: 1,
items: [{ id: "job_test_100", status: "COMPLETED" }],
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_inspect_test")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockDetail }),
};
}
if (url.includes("api/easo/jobs/job_test_100/execution")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockExecutionTree }),
};
}
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. 终端文本透视
const resText = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1"],
},
mockRuntime
);
expect(resText.exitCode).toBe(0);
expect(resText.stdout).toContain("工作流节点只读探针");
expect(resText.stdout).toContain("action_calc_1");
expect(resText.stdout).toContain("时间转换节点");
expect(resText.stdout).toContain("已固化样本");
expect(resText.stdout).toContain("最近一次调试执行出参");
expect(resText.stdout).toContain("job_test_100");
expect(resText.stdout).toContain("1795093140000");
// 2. JSON 模式结构化输出
mockRuntime.jsonMode = true;
const resJson = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1", "--json"],
},
mockRuntime
);
expect(resJson.exitCode).toBe(0);
const parsedJson = JSON.parse(resJson.stdout);
expect(parsedJson.sampleData.minute).toBe("2026-11-19 20:59");
expect(parsedJson.executionProbe.jobId).toBe("job_test_100");
expect(parsedJson.executionProbe.output.timestampMs).toBe(1795093140000);
});
it("workflow node sample-save: 支持 dry-run 预览并一键固化出参至节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "action_target_node",
type: "code",
label: "代码节点",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
];
const mockDetail = {
id: "wf_save_sample_test",
label: "样本固化测试流",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_node_target",
name: "action_target_node",
status: "COMPLETED",
output: {
formattedDate: "2026-11-24 11:30",
rangeSec: "2026-11-24 11:30:00 ~ 2026-11-24 12:00:00",
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
return { json: async () => ({ code: 200, data: mockDetail }) };
}
if (url.includes("api/easo/jobs/job_custom_999/execution")) {
return { json: async () => ({ code: 200, data: mockExecutionTree }) };
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. Dry-run 预览
const dryRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { dryRun: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--dry-run"],
},
mockRuntime
);
expect(dryRes.exitCode).toBe(0);
expect(dryRes.stdout).toContain("[DRY-RUN]");
expect(dryRes.stdout).toContain("固化节点样本数据 (sampleData)");
expect(savedTasks).toBeNull();
// 2. 确认执行
const execRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { yes: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--yes"],
},
mockRuntime
);
expect(execRes.exitCode).toBe(0);
expect(execRes.stdout).toContain("样本数据 (sampleData) 固化成功");
expect(execRes.stdout).toContain("固化字段数 : 2 个属性");
expect(savedTasks).not.toBeNull();
expect(savedTasks[0].sampleData.formattedDate).toBe("2026-11-24 11:30");
expect(choosesRefreshed).toBe(true);
});
it("workflow test --save-sample: 调试通过后自动固化执行出参为节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_code_date",
type: "code",
label: "代码节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "return ['minute': '2026-11-24 11:35'];",
},
];
const mockDetail = {
id: "wf_test_save_sample",
label: "自动保存样本流程",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockClient = {
post: (url: string) => {
if (url.includes("debugSource")) {
return {
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
items: [{ id: "S26000001", title: "测试单据", flowState: "审批中" }],
},
}),
};
}
if (url.includes("api/easo/jobs")) {
return {
json: async () => ({
code: 200,
data: "job_auto_sample_123",
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
get: (url: string) => {
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
if (url.includes("execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "e1",
name: "trigger_1",
label: "单据触发",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
executionTime: 10,
},
{
id: "e2",
name: "action_code_date",
label: "代码节点",
type: "code",
status: "COMPLETED",
executionTime: 5,
output: {
minute: "2026-11-24 11:35",
timestampMs: 1795093140000,
},
},
],
}),
};
}
if (url.includes("api/easo/jobs/job_auto_sample_123")) {
return {
json: async () => ({
code: 200,
data: {
id: "job_auto_sample_123",
pipelineId: "wf_test_save_sample",
status: "COMPLETED",
startTime: 1795490000000,
endTime: 1795490001000,
executionTime: 1000,
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
return {
json: async () => ({
code: 200,
data: mockDetail,
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
const testRes = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_save_sample"],
options: { flow: "S26000001", saveSample: true, yes: true },
raw: ["workflow", "test", "wf_test_save_sample", "--flow=S26000001", "--save-sample", "--yes"],
},
mockRuntime
);
expect(testRes.exitCode).toBe(0);
expect(testRes.stdout).toContain("工作流自动化调测报告");
expect(testRes.stdout).toContain("样本数据自动固化");
expect(testRes.stdout).toContain("action_code_date");
expect(savedTasks).not.toBeNull();
expect(savedTasks[1].sampleData.minute).toBe("2026-11-24 11:35");
expect(savedTasks[1].sampleData.timestampMs).toBe(1795093140000);
expect(choosesRefreshed).toBe(true);
});
});
+271 -7
View File
@@ -7,6 +7,9 @@ import {
editWorkflowTask,
removeWorkflowTask,
applyNodeMapping,
getJobExecutionTree,
listWorkflowLogs,
refreshWorkflowChooses,
} from "../../../domains/platform/workflow/services.js";
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
import { ValidationError } from "../../../core/errors.js";
@@ -26,7 +29,11 @@ async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0],
});
}
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
const SUB_ACTIONS = new Set([
"list", "ls", "get", "show", "info", "add", "append", "insert",
"edit", "update", "set", "map", "rm", "remove", "delete", "del",
"inspect", "probe", "examine", "sample-save", "save-sample",
]);
export async function handleNodeCommand(
parsed: CliParsedArgs,
@@ -79,12 +86,14 @@ export async function handleNodeCommand(
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
"",
"子命令 (工作流级别):",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
"",
"子命令 (企业灰度节点级别):",
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
@@ -107,6 +116,13 @@ export async function handleNodeCommand(
case "list":
case "ls":
return handleListNodes(pipelineId, parsed, runtime);
case "inspect":
case "probe":
case "examine":
return handleInspectNode(pipelineId, nodeTarget, parsed, runtime);
case "sample-save":
case "save-sample":
return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime);
case "get":
case "show":
case "info":
@@ -677,3 +693,251 @@ async function handleRemoveNode(
exitCode: 0,
};
}
async function handleInspectNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task, hierarchicalIndex, path, parentName } = located;
const sampleData = (task as any).sampleData ?? null;
let executionProbe: {
jobId: string;
status: string;
executionTime?: number;
output?: any;
error?: any;
} | null = null;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
try {
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (jobIdToProbe) {
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (matchExecution) {
executionProbe = {
jobId: jobIdToProbe,
status: matchExecution.status || "UNKNOWN",
executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime,
output: matchExecution.output,
error: matchExecution.error,
};
}
}
} catch {
// 探针容错
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
pipelineId,
node: located,
sampleData,
executionProbe,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [
`====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`,
`节点标识 (name) : ${task.name}`,
`层级编号 (#) : ${hierarchicalIndex}`,
`节点类型 (type) : ${task.type}`,
`节点标题 (label) : ${task.label || "-"}`,
`节点显示名 (display): ${(task as any).displayName || "-"}`,
`父容器节点 : ${parentName || "顶级节点 (root)"}`,
`JSON 路径 : ${path}`,
];
if ((task as any).code !== undefined) {
outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`);
}
if ((task as any).url) {
outLines.push(`请求 URL : ${(task as any).url}`);
}
if ((task as any).specificationId) {
outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`);
}
outLines.push("");
outLines.push("── 📦 节点固化样本数据 (sampleData) ──");
if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) {
const keys = Object.keys(sampleData);
outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`);
outLines.push(printJson(sampleData, runtime.outputOptions));
} else {
outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)");
outLines.push("💡 提示: 可运行 hose-use workflow node sample-save <pipelineId> <nodeName> 固化最近调测出参");
}
outLines.push("");
outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──");
if (executionProbe) {
outLines.push(`来源 Job ID : ${executionProbe.jobId}`);
outLines.push(`执行状态 (status) : ${executionProbe.status}`);
outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`);
if (executionProbe.output && typeof executionProbe.output === "object") {
outLines.push(`出参全貌 (output):`);
outLines.push(printJson(executionProbe.output, runtime.outputOptions));
} else {
outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`);
}
} else {
outLines.push("未找到或无匹配的最近调试执行记录。");
}
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
async function handleSaveNodeSample(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task } = located;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (!jobIdToProbe) {
return {
stdout: "",
stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job=<id> 指定。\n`,
exitCode: 1,
};
}
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (!matchExecution || matchExecution.output === undefined) {
return {
stdout: "",
stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`,
exitCode: 1,
};
}
const samplePayload = matchExecution.output;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, {
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
samplePayload,
});
}
requireMutationConfirmation(
parsed,
runtime,
"固化节点样本数据 (sampleData)",
`hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes`
);
(task as any).sampleData = samplePayload;
const saveResult = await saveNodeChanges(client, detail, detail, platformId);
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
fieldsSaved: fieldCount,
sampleData: samplePayload,
workflow: saveResult,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`,
` • 来源 Job ID : ${jobIdToProbe}`,
` • 固化字段数 : ${fieldCount} 个属性`,
` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`,
`📌 ${formatWorkflowVersion(saveResult)}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
+54 -1
View File
@@ -6,6 +6,9 @@ import {
getWorkflowDetail,
getWorkflowSampleData,
runWorkflowDebugTest,
updateWorkflow,
refreshWorkflowChooses,
flattenWorkflowTaskTree,
type WorkflowTriggerCategory,
} from "../../../domains/platform/workflow/services.js";
import { stringOption, booleanOption, numberOption } from "../../parser.js";
@@ -46,6 +49,7 @@ export async function handleWorkflowTest(
" 4. 外部调用 (webhook): --body='{...}' 或 --file=<path.json> 传入事件请求体",
"",
"通用选项:",
" --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)",
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
" --auto-publish 是否自动发布测试快照 (默认 false)",
" --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)",
@@ -59,6 +63,7 @@ export async function handleWorkflowTest(
}
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
const saveSample = booleanOption(parsed.options, ["save-sample", "saveSample", "save-samples", "saveSamples"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
const filePath = stringOption(parsed.options, ["file", "path"]);
@@ -109,7 +114,7 @@ export async function handleWorkflowTest(
});
if (blocked) return blocked;
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
// 1. 获取工作流详情与触发器元数据
const detail = await getWorkflowDetail(client, pipelineId).catch(() => {
@@ -414,9 +419,48 @@ export async function handleWorkflowTest(
autoPublish,
timeoutMs,
});
const savedSampleNodes: Array<{ name: string; label: string; fieldCount: number }> = [];
if (saveSample && execution.outcome === "completed" && execution.executionTree?.length > 0) {
try {
const latestDetail = await getWorkflowDetail(client, pipelineId);
const flattened = flattenWorkflowTaskTree(latestDetail.tasks || []);
let updatedCount = 0;
for (const execNode of execution.executionTree) {
if (!execNode.name || execNode.output === undefined || execNode.output === null) continue;
if (typeof execNode.output !== "object" || Object.keys(execNode.output).length === 0) continue;
const matched = flattened.find((f) => f.task.name === execNode.name);
if (matched) {
(matched.task as any).sampleData = execNode.output;
savedSampleNodes.push({
name: matched.task.name,
label: (matched.task as any).displayName || matched.task.label || matched.task.type,
fieldCount: Object.keys(execNode.output).length,
});
updatedCount++;
}
}
if (updatedCount > 0) {
await updateWorkflow(client, latestDetail, {
platformId,
expectedVersion: { version: latestDetail.version, tasksVersion: latestDetail.tasksVersion },
});
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
}
} catch (sampleErr: any) {
warnings.push(`自动固化样本数据警告: ${sampleErr.message || String(sampleErr)}`);
}
}
const report = {
...execution,
productionEnabled: detail ? isEnabled : null,
savedSampleNodes: savedSampleNodes.length > 0 ? savedSampleNodes : undefined,
warnings,
...productionOverrideMeta(
parsed,
@@ -514,6 +558,15 @@ export async function handleWorkflowTest(
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
}
if (savedSampleNodes.length > 0) {
outLines.push("");
outLines.push("── ✨ 样本数据自动固化 (Sample Data Saved) ──");
outLines.push(`已自动将 ${savedSampleNodes.length} 个节点的真实调试出参固化为 sampleData 并刷新设计器选择树:`);
for (const sn of savedSampleNodes) {
outLines.push(` • [${sn.name}] (${sn.label}): 固化 ${sn.fieldCount} 个属性`);
}
}
if (category === "WEBHOOK" && report.outcome !== "completed") {
outLines.push("");
outLines.push("💡 [Webhook 流程调试提示]");
+3 -2
View File
@@ -149,8 +149,9 @@ export class CorpContext {
if (!corp) return false;
this.current = corp;
this.defaultCorpId = corp.id;
if (persist && this.stateful) {
saveGlobalConfig({ defaultCorpId: corp.id });
if (persist) {
this.stateful = true;
saveGlobalConfig({ defaultCorpId: corp.id, stateful: true });
}
return true;
}
+18 -15
View File
@@ -8,9 +8,10 @@
src/domains/bill/
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
├── write.ts # 草稿写动作门面:freeflow.delete 等(传输统一在 api.ts)
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
├── copy.ts # 草稿复制:服务端读取 → 按单据类型路由转换(报销/申请) → 创建新草稿
├── form-helpers.ts # 单据类型路由(expense/requisition)、东八区日期解析、dataLinkId 重置与编辑辅助
├── write.ts # 草稿写动作门面:freeflow.edit / freeflow.delete 等(传输统一在 api.ts)
├── draft-validation.ts # 草稿派生字段与必填项校验(含 dataLinkId 键检查与隐藏字段放行)
├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用)
├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细)
├── submit.ts # 计算审批计划并提交送审(freeflow.submit)
@@ -60,17 +61,18 @@ src/domains/bill/
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
(甚至允许 CNY 与 USD 直接相加)。CLI 在写入前先跑本层校验:
必填表头、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期。
10. **纯接口复制 (`copyBillAsDraft`)**:
- 读取服务端最新的 `flow.form`;
- 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`;
- 只重置源单实际包含的发票字段,不向通用模板注入 `u_发票总金额` 等租户自定义属性。
- 重算报销/支付金额,附件默认保留;
必填表头(自动忽略 `hide`/`hidden` 字段)、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期、
`feeDatePeriod` 合法性以及 `dataLinkEdits`(如 `u_行程规划`)条目显式携带 `dataLinkId` 键(防止审批后无法生成行程实例);
- 按 `resolveBillFormType` 自动路由单据类型:报销单(`expense`)强制至少一条 `details`,申请单(`requisition`)允许无明细。
10. **纯接口复制 (`copyBillAsDraft` / `prepareBillCopy`)**:
- 读取服务端最新的 `flow.form`,自动识别模板最新启用 `versionedId`,清理历史流转/只读字段;
- 对所有 `dataLinkEdits` 条目强制重置 `"dataLinkId": null`(绝不删除键、绝不复用旧 ID);
- 按单据类型路由:报销单清空发票绑定、发票总额归零、剔除 `detailStatus` 并重算报销/支付金额;申请单不注入 `expenseMoney`/`payMoney`,支持覆写标题、事由、金额与差旅起止日期(同步联动 `feeDatePeriod`、`u_差旅天数` 与行程内日期);
- `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。
11. **草稿删除 (`deleteBillDraft`)**:
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
11. **草稿编辑与删除 (`editBillDraft` / `deleteBillDraft`)**:
- `editBillDraft`:通过 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.edit`)保存修改,仅允许 `draft` 状态单据,支持修改标题、事由、申请单金额与差旅起止日期(同步联动行程日期),写入前必跑 `assertBillDraftValid`;
- `deleteBillDraft`:`POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`,仅允许删除 `draft` 状态单据。
12. **单据模板列表 (`listBillTemplates`)**:
- 与页面「快速新建单据」同源:`GET /api/form/v2/specificationGroups/withSpecificationVersioned`;
@@ -82,9 +84,10 @@ src/domains/bill/
- 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细;
- 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。
14. **提交送审 (`submitBillDraft`)**:
- 创建、复制、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。
- 创建、复制、编辑、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。
- 自动识别 `formType`(`spec.type` / `flow.formType` / 字段特征路由,确保申请单传 `requisition` 而非 `expense`);
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
- 仅要求普通必填审批节点存在审批人(放行 `ebot`、自动跳过 `skippedType != NO_SKIPPED` 与条件/延迟计算节点,并原样回传),未指派节点必须由 `--approver` 显式指定;
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
15. **未提交草稿列表 (`searchAndFormatDraftBills`)**:
- 草稿未进入 `POST /api/v2/invoice/search` 台账索引,`bill list --state=draft` 改走 `POST /api/flow/v1/flows/my`;
+8
View File
@@ -791,6 +791,14 @@ export async function createBillFlow(client: KyInstance, corpId: string, form: R
return billFlowResult(await response.json());
}
export async function updateBillFlow(client: KyInstance, corpId: string, flowId: string, form: Record<string, unknown>): Promise<BillFlowWriteResult> {
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
searchParams: { corpId },
json: { id: flowId, name: "freeflow.edit", form },
});
return billFlowResult(await response.json());
}
export async function computeBillApprovalPlan(client: KyInstance, corpId: string, flowId: string, flowPlanConfigId: string, form: Record<string, unknown>, formType: string): Promise<BillPlanNode[]> {
const response = await client.post("api/v1/flow/plans/computed", {
searchParams: { corpId }, json: { flowId, flowPlanConfigId, form, formType, params: {} },
+99
View File
@@ -94,3 +94,102 @@ describe("buildBillCopyForm", () => {
expect(source.details![1].feeTypeForm?.detailStatus).toBe("draft");
});
});
describe("buildBillCopyForm 申请单 (requisition) 适配", () => {
function makeTravelSource(): BillDraftForm {
return {
id: "ID01ULT7Igvigv",
code: "S26003502",
title: "申请部门季度总结及团队建设差旅-谢子豪",
description: "旧事由说明",
specificationId: "huI8ciI19Y3Q00:oldhash",
submitterId: "corp:staff-1",
submitDate: 1784614796613,
flowEndTime: 1784615989225,
preApprovedNodeName: "所属部门主管",
preNodeApprovedTime: 1784615989218,
rejectionNum: "0",
printCount: "0",
printState: "noPrint",
voucherNo: "",
voucherStatus: "未生成",
voucherCreateTime: 0,
onlyOwnerPrint: false,
ownerAndApproverPrintNodeFlag: false,
requisitionDate: 1784563200000,
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
u_差旅天数: "2",
requisitionMoney: { standard: "1000", standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY" },
u_申请额度: { standard: "1000.00", standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY" },
u_行程规划: [
{
dataLinkId: "ID01ULUK6llXUH",
dataLinkTemplateId: "s-IaWFum-QeI00",
dataLinkForm: {
E_88080aea9796fb433000_name: "杭州市区 - 苏州市区",
E_88080aea9796fb433000_入住日期: 1784822400000,
E_88080aea9796fb433000_离店日期: 1784995199999,
E_88080aea9796fb433000_行程日期: 1784822400000,
E_88080aea9796fb433000_行程开始日期: "2026-07-24",
E_88080aea9796fb433000_行程结束日期: "2026-07-25",
},
},
{
dataLinkId: "ID01ULUI6VSSuj",
dataLinkTemplateId: "GxUaWFum-Qek00",
dataLinkForm: {
E_88080aea9796fb433000_name: "苏州市区",
E_88080aea9796fb433000_入住日期: 1784822400000,
E_88080aea9796fb433000_离店日期: 1784995199999,
E_88080aea9796fb433000_行程开始日期: "2026-07-24",
E_88080aea9796fb433000_行程结束日期: "2026-07-25",
},
},
],
};
}
it("不注入 expenseMoney/payMoney,剥离历史流转字段,并强制显式设置 dataLinkId: null", () => {
const form = buildBillCopyForm(makeTravelSource(), {
formType: "requisition",
requisitionDate: 1796054400000,
});
expect(form.expenseMoney).toBeUndefined();
expect(form.payMoney).toBeUndefined();
expect((form as Record<string, unknown>).flowEndTime).toBeUndefined();
expect((form as Record<string, unknown>).preApprovedNodeName).toBeUndefined();
expect((form as Record<string, unknown>).submitDate).toBeUndefined();
expect((form as Record<string, unknown>).requisitionDate).toBe(1796054400000);
const trips = (form as Record<string, unknown>).u_行程规划 as Array<Record<string, unknown>>;
expect(trips).toHaveLength(2);
for (const trip of trips) {
expect(Object.prototype.hasOwnProperty.call(trip, "dataLinkId")).toBe(true);
expect(trip.dataLinkId).toBeNull();
}
});
it("支持覆写标题、事由、金额与差旅起止日期并联动行程和天数", () => {
const form = buildBillCopyForm(makeTravelSource(), {
title: "申请差旅建设行程(谢子豪)",
reason: "根据公司统一安排,参加团队建设活动。",
amount: "1500",
startDate: "2026-12-04",
endDate: "2026-12-06",
}) as Record<string, any>;
expect(form.title).toBe("申请差旅建设行程(谢子豪)");
expect(form.description).toBe("根据公司统一安排,参加团队建设活动。");
expect(form.requisitionMoney.standard).toBe("1500");
expect(form["u_申请额度"].standard).toBe("1500.00");
expect(form["u_差旅天数"]).toBe("3");
expect(form.feeDatePeriod).toEqual({
start: Date.parse("2026-12-04T00:00:00+08:00"),
end: Date.parse("2026-12-06T23:59:59.999+08:00"),
});
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程开始日期).toBe("2026-12-04");
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程结束日期).toBe("2026-12-06");
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程日期).toBe(Date.parse("2026-12-04T00:00:00+08:00"));
expect(form["u_行程规划"][1].dataLinkForm.E_88080aea9796fb433000_离店日期).toBe(Date.parse("2026-12-06T23:59:59.999+08:00"));
});
});
+205 -40
View File
@@ -1,34 +1,81 @@
import type { KyInstance } from "ky";
import { NotFoundError } from "../../core/errors.js";
import { createBillFlow, getRawBillFlow } from "./api.js";
import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js";
import {
assertBillDraftValid,
loadBillValidationOptions,
type BillDraftForm,
type BillMoney,
type BillValidationComponent,
} from "./draft-validation.js";
import {
applyCommonAndRequisitionEdits,
collectDataLinkEditFields,
resetDataLinkEditsForNewDraft,
resolveBillFormType,
stripHistoricalFlowFields,
todayStartCstMs,
} from "./form-helpers.js";
import { listBillTemplates } from "./templates.js";
/**
* 纯接口复制单据。
* 纯接口复制单据(支持报销单与差旅/常规申请单)。
*
* 合思前端的「复制」是内存行为:读取源单 → 在编辑器里生成一份新表单,点保存时才创建。
* 而且它复制的是编辑器内存里的旧状态(可能带旧汇率/旧金额)。
*
* CLI 的复制走「服务端读取 → 本地转换 → 创建」:
* 1. 读取服务端最新的 form;
* 2. 清空发票绑定(invoiceForm.invoices)、发票总额归零、剔除明细草稿标记;
* 3. 重算报销/支付金额;
* 4. POST /api/flow/v1/flows 创建新草稿。
* CLI 的复制走「服务端读取 → 本地转换与校验 → 创建」:
* 1. 读取服务端最新的 form,清理历史流转与只读字段;
* 2. 对所有 dataLinkEdits(如行程规划)强制重置 `"dataLinkId": null`(不可删键,也不可复用旧 ID);
* 3. 按单据类型路由:
* - expense(报销单):清空发票绑定、发票总额归零、剔除明细草稿标记、重算报销/支付金额;
* - requisition(申请单):不注入报销/支付金额,支持覆写事由、金额、差旅起止日期(同步更新行程日期与天数);
* 4. 校验通过后 POST /api/flow/v1/flows 创建新草稿。
*/
export interface CopyBillOptions {
/** 新单据标题;默认沿用源单标题 */
title?: string;
/** 事由/描述覆写 */
reason?: string;
/** 申请单金额覆写(仅非报销单) */
amount?: string;
/** 差旅开始日期(YYYY-MM-DD,需与 endDate 成对使用) */
startDate?: string;
/** 差旅结束日期(YYYY-MM-DD,需与 startDate 成对使用) */
endDate?: string;
/** 申请日期时间戳(默认东八区当天 00:00) */
requisitionDate?: number;
/** 是否保留附件(默认保留,与前端行为一致) */
keepAttachments?: boolean;
/** 显式指定单据类型(不传时自动按模板或字段特征路由) */
formType?: string;
/** 覆写模板版本化 ID */
specificationId?: string;
/** 模板组件定义,用于字段识别与日期联动 */
components?: BillValidationComponent[];
}
export interface PreparedBillCopy {
sourceCode: string;
sourceTitle: string;
formType: string;
detailCount: number;
expenseMoney: string;
amount: string;
tripCount: number;
dataLinkIdsReset: boolean;
feeDatePeriod?: { start?: number; end?: number };
form: BillDraftForm;
}
export interface CopyBillResult {
flowId: string;
code: string;
title: string;
formType: string;
detailCount: number;
expenseMoney: string;
amount: string;
tripCount: number;
form: BillDraftForm;
}
@@ -56,6 +103,24 @@ function moneyNumber(money: BillMoney | undefined): number {
return Number.isFinite(value) ? value : 0;
}
function countDataLinkItems(form: Record<string, unknown>, components?: BillValidationComponent[]): number {
let total = 0;
for (const field of collectDataLinkEditFields(form, components)) {
const list = form[field];
if (Array.isArray(list)) total += list.length;
}
return total;
}
function resolveCopyAmount(form: BillDraftForm, formType: string): string {
if (formType === "expense") {
return String(form.expenseMoney?.standard ?? "0");
}
const reqMoney = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
const quotaMoney = (form as Record<string, unknown>)["u_申请额度"] as BillMoney | undefined;
return String(reqMoney?.standard ?? quotaMoney?.standard ?? "0");
}
/**
* 把源单 form 转换成一个可创建的新草稿 form。
* 纯函数,便于单测与实际调用共享。
@@ -66,50 +131,104 @@ export function buildBillCopyForm(
): BillDraftForm {
const keepAttachments = options.keepAttachments !== false;
const form = structuredClone(source) as BillDraftForm;
const formRecord = form as Record<string, unknown>;
delete (form as Record<string, unknown>).id;
delete (form as Record<string, unknown>).code;
if (options.title?.trim()) {
form.title = options.title.trim();
stripHistoricalFlowFields(formRecord);
if (options.specificationId?.trim()) {
form.specificationId = options.specificationId.trim();
}
const details = Array.isArray(form.details) ? form.details : [];
let amountSum = 0;
const formType = resolveBillFormType(form, { specType: options.formType });
resetDataLinkEditsForNewDraft(formRecord, options.components);
for (const detail of details) {
const ft = (detail.feeTypeForm ??= {});
amountSum += moneyNumber(ft.amount);
if (formType === "expense") {
const details = Array.isArray(form.details) ? form.details : [];
let amountSum = 0;
// 复制不携带发票绑定;发票总额归零
if (ft.invoice !== undefined) ft.invoice = "0";
if (ft.invoiceForm !== undefined) ft.invoiceForm = { type: "exist", invoices: [] };
if (ft.u_发票总金额 !== undefined) ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
delete ft.detailStatus;
for (const detail of details) {
const ft = (detail.feeTypeForm ??= {});
amountSum += moneyNumber(ft.amount);
if (!keepAttachments && ft.attachments !== undefined) {
ft.attachments = [];
// 复制不携带发票绑定;发票总额归零
if (ft.invoice !== undefined) ft.invoice = "0";
if (ft.invoiceForm !== undefined) ft.invoiceForm = { type: "exist", invoices: [] };
if (ft.u_发票总金额 !== undefined) ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
delete ft.detailStatus;
if (!keepAttachments && ft.attachments !== undefined) {
ft.attachments = [];
}
}
if (form.u_发票总金额 !== undefined) form.u_发票总金额 = zeroMoney(form.u_发票总金额);
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) };
if (!keepAttachments && form.attachments !== undefined) {
form.attachments = [];
}
applyCommonAndRequisitionEdits(formRecord, {
title: options.title,
reason: options.reason,
components: options.components,
});
return form;
}
if (form.u_发票总金额 !== undefined) form.u_发票总金额 = zeroMoney(form.u_发票总金额);
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) };
// 非报销单(如差旅申请单):不注入 expenseMoney/payMoney,保留原有申请金额并应用覆盖项
if (!keepAttachments && form.attachments !== undefined) {
form.attachments = [];
}
const hasReqDate =
"requisitionDate" in formRecord ||
Boolean(options.components?.some((item) => item.field === "requisitionDate")) ||
options.requisitionDate !== undefined;
if (hasReqDate) {
formRecord.requisitionDate = options.requisitionDate ?? todayStartCstMs();
}
applyCommonAndRequisitionEdits(formRecord, {
title: options.title,
reason: options.reason,
amount: options.amount,
startDate: options.startDate,
endDate: options.endDate,
components: options.components,
});
return form;
}
/**
* 读取源单并创建一份新草稿。
*/
export async function copyBillAsDraft(
async function resolveLatestVersionedSpecId(
client: KyInstance,
corpId: string,
currentSpecId: unknown
): Promise<string | undefined> {
const raw = typeof currentSpecId === "string"
? currentSpecId.trim()
: currentSpecId && typeof currentSpecId === "object"
? String((currentSpecId as { id?: unknown }).id ?? "").trim()
: "";
if (!raw) return undefined;
const cleanId = raw.replace(/:[0-9a-f]{32,64}$/i, "");
try {
const list = await listBillTemplates(client, corpId);
const hit = list.groups
.flatMap((group) => group.specifications)
.find((item) => item.id === cleanId || item.versionedId === raw);
return hit?.versionedId || raw;
} catch {
return raw;
}
}
/** 预演或创建前的公共准备工作:读取源单、升级模板版本、转换载荷并执行一致性校验。 */
export async function prepareBillCopy(
client: KyInstance,
corpId: string,
target: string,
options: CopyBillOptions = {}
): Promise<CopyBillResult> {
): Promise<PreparedBillCopy> {
const raw = await getRawBillFlow(client, corpId, target);
const flow = raw && typeof raw.flowId === "object"
? (raw.flowId as Record<string, unknown>)
@@ -122,17 +241,63 @@ export async function copyBillAsDraft(
throw new NotFoundError(`在企业 [${corpId}] 下未找到单号或 ID 为 [${target}] 的单据,无法复制`);
}
const form = buildBillCopyForm(sourceForm, options);
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form));
const value = await createBillFlow(client, corpId, form);
const validationOptions = await loadBillValidationOptions(client, corpId, sourceForm);
const flowFormType = typeof flow.formType === "string" ? flow.formType : undefined;
const formType = resolveBillFormType(sourceForm, {
specType: options.formType ?? validationOptions.formType,
flowFormType,
});
const upgradedSpecId = options.specificationId ?? (await resolveLatestVersionedSpecId(client, corpId, sourceForm.specificationId));
const form = buildBillCopyForm(sourceForm, {
...options,
formType,
specificationId: upgradedSpecId,
components: validationOptions.components,
});
assertBillDraftValid(form, { ...validationOptions, formType });
const formRecord = form as Record<string, unknown>;
const tripCount = countDataLinkItems(formRecord, validationOptions.components);
const period = formRecord.feeDatePeriod as { start?: number; end?: number } | undefined;
return {
sourceCode: String((sourceForm as Record<string, unknown>).code ?? target),
sourceTitle: String(sourceForm.title ?? ""),
formType,
detailCount: form.details?.length ?? 0,
expenseMoney: String(form.expenseMoney?.standard ?? "0"),
amount: resolveCopyAmount(form, formType),
tripCount,
dataLinkIdsReset: tripCount > 0,
...(period ? { feeDatePeriod: { start: period.start, end: period.end } } : {}),
form,
};
}
/**
* 读取源单并创建一份新草稿。
*/
export async function copyBillAsDraft(
client: KyInstance,
corpId: string,
target: string,
options: CopyBillOptions = {}
): Promise<CopyBillResult> {
const prepared = await prepareBillCopy(client, corpId, target, options);
const value = await createBillFlow(client, corpId, prepared.form);
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,
title: String(formSnapshot.title ?? prepared.form.title ?? ""),
formType: prepared.formType,
detailCount: prepared.detailCount,
expenseMoney: prepared.expenseMoney,
amount: prepared.amount,
tripCount: prepared.tripCount,
form: prepared.form,
};
}
+62
View File
@@ -146,3 +146,65 @@ describe("assertBillDraftValid", () => {
}
});
});
describe("申请单 (requisition) 与 dataLinkEdits 校验", () => {
function makeTravelRequisition(): BillDraftForm {
return {
title: "申请差旅建设行程(谢子豪)",
specificationId: "spec-req",
submitterId: "corp:staff-1",
requisitionDate: Date.UTC(2026, 11, 1),
feeDatePeriod: {
start: Date.parse("2026-12-04T00:00:00+08:00"),
end: Date.parse("2026-12-05T23:59:59.999+08:00"),
},
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
u_行程规划: [
{
dataLinkId: null,
dataLinkTemplateId: "s-IaWFum-QeI00",
dataLinkForm: {
E_88080aea9796fb433000_name: "杭州市区 - 苏州市区",
E_88080aea9796fb433000_行程开始日期: "2026-12-04",
E_88080aea9796fb433000_行程结束日期: "2026-12-05",
},
},
],
};
}
it("无 details 的合法差旅申请单通过校验,且放行 hide=true 的模板必填字段", () => {
const form = makeTravelRequisition();
const issues = validateBillDraft(form, {
formType: "requisition",
components: [
{ field: "title", optional: false },
{ field: "u_深度现场项目", label: "深度现场项目", optional: false, hide: true },
{ field: "u_行程规划", label: "行程规划", type: "dataLinkEdits", optional: false },
],
});
expect(issues).toEqual([]);
});
it("自动根据字段特征路由申请单,不报 NO_DETAILS", () => {
const form = makeTravelRequisition();
expect(validateBillDraft(form)).toEqual([]);
});
it("拦截缺少 dataLinkId 键的行程记录(防止审批后无法生成 TRIP)", () => {
const form = makeTravelRequisition();
const trips = form.u_行程规划 as Array<Record<string, unknown>>;
delete trips[0].dataLinkId;
const issues = validateBillDraft(form, { formType: "requisition" });
expect(issues.map((item) => item.code)).toContain("DATALINK_ID_KEY_MISSING");
});
it("拦截结束日期早于开始日期的 feeDatePeriod", () => {
const form = makeTravelRequisition();
form.feeDatePeriod = {
start: Date.parse("2026-12-05T00:00:00+08:00"),
end: Date.parse("2026-12-04T23:59:59.999+08:00"),
};
expect(codes(form)).toContain("FEE_DATE_PERIOD_INVALID");
});
});
+253 -205
View File
@@ -1,6 +1,7 @@
import type { KyInstance } from "ky";
import { getFormSpecification } from "./api.js";
import { NotFoundError, ValidationError } from "../../core/errors.js";
import { collectDataLinkEditFields, resolveBillFormType } from "./form-helpers.js";
/**
* 单据草稿的派生字段一致性校验。
@@ -85,11 +86,16 @@ export interface ValidationIssue {
export interface BillValidationComponent {
field?: string;
label?: string;
type?: string;
optional?: boolean;
hide?: boolean;
hidden?: boolean;
maxLength?: number;
}
export interface ValidateOptions {
/** 单据业务类型(如 expense / requisition),未提供时按表单字段特征路由 */
formType?: string;
/** 实际模板字段;未提供时仅检查通用结构与已有金额。 */
components?: BillValidationComponent[];
detailComponents?: BillValidationComponent[][];
@@ -144,13 +150,16 @@ export function validateBillDraft(
return [issue("EMPTY_FORM", "form", "单据表单为空")];
}
// 1. 必填表头
const formType = resolveBillFormType(form, { specType: options.formType });
// 1. 必填表头(跳过模板显式隐藏字段)
const checkComponents = (value: Record<string, unknown>, components: BillValidationComponent[], prefix = "") => {
for (const component of components) {
if (!component.field) continue;
const content = value[component.field];
const field = prefix + component.field;
if (component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) {
const isHidden = component.hide === true || component.hidden === true;
if (!isHidden && component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) {
issues.push(issue("MISSING_FIELD", field, `缺少必填字段:${component.label || component.field}`));
}
if (typeof content === "string" && typeof component.maxLength === "number" && content.length > component.maxLength) {
@@ -160,239 +169,276 @@ export function validateBillDraft(
};
checkComponents(form, [{ field: "specificationId", optional: false }, ...(options.components ?? [])]);
// 2. 描述长度由实际模板的 maxLength 决定,不假设所有模板均为 800。
// 3. 明细数量
const details = Array.isArray(form.details) ? form.details : [];
if (details.length === 0) {
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
return issues;
// 2. dataLinkEdits(如行程规划)与申请单通用字段校验
for (const dlField of collectDataLinkEditFields(form as Record<string, unknown>, options.components)) {
const list = (form as Record<string, unknown>)[dlField];
if (!Array.isArray(list)) continue;
list.forEach((item, index) => {
if (item !== null && typeof item === "object" && !Array.isArray(item)) {
if (!Object.prototype.hasOwnProperty.call(item, "dataLinkId")) {
issues.push(
issue(
"DATALINK_ID_KEY_MISSING",
`${dlField}[${index}].dataLinkId`,
`${dlField} 第 ${index + 1} 条缺少 dataLinkId 键(新建/复制草稿必须显式设为 null,否则审批通过后无法生成行程实例)`
)
);
}
}
});
}
// 4. 本位币(以表头报销金额为准)
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode
|| details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode;
if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) {
issues.push(issue("CURRENCY_MISMATCH", "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 ?? {};
checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`);
const position = index + 1;
const label = `明细 #${ft.detailNo ?? position}`;
if (ft.detailStatus === "draft") {
const period = (form as Record<string, unknown>).feeDatePeriod;
if (period !== undefined && period !== null) {
const periodObj = typeof period === "object" && !Array.isArray(period) ? (period as Record<string, unknown>) : undefined;
const periodStart = periodObj ? toNumber(periodObj.start) : undefined;
const periodEnd = periodObj ? toNumber(periodObj.end) : undefined;
if (periodStart === undefined || periodEnd === undefined || periodEnd < periodStart) {
issues.push(
issue(
"DETAIL_DRAFT_STATUS",
`details[${index}].feeTypeForm.detailStatus`,
`${label} 仍处于草稿状态(detailStatus=draft),提交前必须保存该明细`
)
issue("FEE_DATE_PERIOD_INVALID", "feeDatePeriod", "差旅起止日期(feeDatePeriod)缺失有效 start/end 或结束早于开始")
);
}
}
if (typeof ft.detailNo === "number") {
const previous = seenDetailNos.get(ft.detailNo);
if (previous !== undefined) {
const reqMoneyRaw = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
const reqMoney = moneyStandard(reqMoneyRaw);
if (reqMoneyRaw !== undefined && reqMoney === undefined) {
issues.push(issue("REQUISITION_MONEY_INVALID", "requisitionMoney", "申请预估金额缺失或不是合法数字"));
}
// 3. 明细数量(报销单强制要求至少一条;申请单等非报销单允许无 details)
const details = Array.isArray(form.details) ? form.details : [];
if (details.length === 0) {
if (formType === "expense") {
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
return issues;
}
} else {
// 4. 本位币(以表头报销金额为准)
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode
|| details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode;
if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) {
issues.push(issue("CURRENCY_MISMATCH", "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 ?? {};
checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`);
const position = index + 1;
const label = `明细 #${ft.detailNo ?? position}`;
if (ft.detailStatus === "draft") {
issues.push(
issue(
"DUPLICATE_DETAIL_NO",
`details[${index}].feeTypeForm.detailNo`,
`明细序号 ${ft.detailNo} 重复(第 ${previous + 1} 条与第 ${position} 条)`
"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 {
seenDetailNos.set(ft.detailNo, index);
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 拦截)`
)
);
}
}
}
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) {
// 外币明细: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.foreignStrCode`,
`${label} 有外资金额但缺少 foreignStrCode`
)
);
} else if (billCurrency && amount.foreignStrCode === billCurrency) {
issues.push(
issue(
"FOREIGN_SAME_CURRENCY",
`details[${index}].feeTypeForm.amount`,
`${label} 的外币币种与本位币相同(${billCurrency}),不应同时设置外币字段`,
"warning"
`${label} 的外币金额与汇率必须成对出现`
)
);
}
} else if (foreign !== undefined || rate !== undefined) {
issues.push(
issue(
"FOREIGN_FIELDS_INCOMPLETE",
`details[${index}].feeTypeForm.amount`,
`${label} 的外币金额与汇率必须成对出现`
)
);
}
// 明细发票总额
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
issues.push(
issue(
"DETAIL_INVOICE_TOTAL_INVALID",
`details[${index}].feeTypeForm.u_发票总金额`,
`${label} 的发票总金额缺失或不是合法数字`
)
);
} else {
detailInvoiceSum += detailInvoiceTotal ?? 0;
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
// 明细发票总额
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
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"
"DETAIL_INVOICE_TOTAL_INVALID",
`details[${index}].feeTypeForm.u_发票总金额`,
`${label} 的发票总金额缺失或不是合法数字`
)
);
} else {
seenInvoiceIds.set(invoiceId, index);
detailInvoiceSum += detailInvoiceTotal ?? 0;
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} 不一致`
)
);
}
}
}
});
// 6. 表头派生金额
const expenseMoney = moneyStandard(form.expenseMoney);
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
issues.push(
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
);
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
issues.push(
issue(
"EXPENSE_TOTAL_MISMATCH",
"expenseMoney.standard",
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
)
);
}
// 发票去重
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);
}
}
});
const payMoney = moneyStandard(form.payMoney);
if (form.payMoney !== undefined && payMoney === undefined) {
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
} else if (payMoney !== undefined && expenseMoney !== undefined) {
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
const expectedPay = expenseMoney - writtenOff;
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
// 6. 表头派生金额
const expenseMoney = moneyStandard(form.expenseMoney);
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
issues.push(
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
);
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
issues.push(
issue(
"PAY_TOTAL_MISMATCH",
"payMoney.standard",
`支付金额 ${payMoney} 与报销金额 ${expenseMoney} - 核销借款 ${writtenOff} = ${expectedPay.toFixed(2)} 不一致`
"EXPENSE_TOTAL_MISMATCH",
"expenseMoney.standard",
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
)
);
}
}
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
issues.push(
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
);
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
issues.push(
issue(
"INVOICE_TOTAL_MISMATCH",
"u_发票总金额.standard",
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
)
);
}
const payMoney = moneyStandard(form.payMoney);
if (form.payMoney !== undefined && payMoney === undefined) {
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
} else if (payMoney !== undefined && 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)} 不一致`
)
);
}
}
if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) {
issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法"));
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
issues.push(
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
);
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
issues.push(
issue(
"INVOICE_TOTAL_MISMATCH",
"u_发票总金额.standard",
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
)
);
}
if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) {
issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法"));
}
}
// 7. 日期
@@ -438,7 +484,7 @@ export async function loadBillValidationOptions(
client: KyInstance,
corpId: string,
form: BillDraftForm,
specification?: { components: BillValidationComponent[] }
specification?: { type?: string; components: BillValidationComponent[] }
): Promise<ValidateOptions> {
const resolveId = (reference: unknown): string => {
const value = typeof reference === "string"
@@ -449,18 +495,20 @@ export async function loadBillValidationOptions(
}
return value.trim();
};
const load = async (id: string): Promise<BillValidationComponent[]> => {
const loadSpec = async (id: string) => {
const spec = await getFormSpecification(client, corpId, id);
if (!spec) throw new NotFoundError(`未找到单据或费用类型规格: ${id}`);
return spec.components as BillValidationComponent[];
return spec;
};
const headerId = resolveId(form.specificationId);
const components = specification?.components ?? await load(headerId);
const loadedHeader = specification ? undefined : await loadSpec(headerId);
const components = (specification?.components ?? loadedHeader!.components) as BillValidationComponent[];
const formType = specification?.type ?? loadedHeader?.type;
const cache = new Map<string, Promise<BillValidationComponent[]>>();
const detailComponents = await Promise.all((form.details ?? []).map((detail) => {
const id = resolveId(detail.specificationId);
if (!cache.has(id)) cache.set(id, load(id));
if (!cache.has(id)) cache.set(id, loadSpec(id).then((spec) => spec.components as BillValidationComponent[]));
return cache.get(id)!;
}));
return { components, detailComponents };
return { components, detailComponents, formType };
}
+276
View File
@@ -0,0 +1,276 @@
import { ValidationError } from "../../core/errors.js";
import type { BillDraftForm, BillMoney, BillValidationComponent } from "./draft-validation.js";
const CST_OFFSET_MS = 8 * 60 * 60 * 1000;
const DAY_MS = 24 * 60 * 60 * 1000;
const HISTORICAL_FLOW_FIELDS = [
"id",
"code",
"submitDate",
"flowEndTime",
"preApprovedNodeName",
"preNodeApprovedTime",
"rejectionNum",
"printCount",
"printState",
"voucherNo",
"voucherStatus",
"voucherCreateTime",
"onlyOwnerPrint",
"ownerAndApproverPrintNodeFlag",
] as const;
export interface DataLinkEditItem {
dataLinkId?: string | null;
dataLinkForm?: Record<string, unknown>;
dataLinkTemplateId?: string;
[key: string]: unknown;
}
export interface CommonAndRequisitionEditOptions {
title?: string;
reason?: string;
amount?: string;
startDate?: string;
endDate?: string;
components?: BillValidationComponent[];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/** 判断字段值是否为 dataLinkEdits(如行程规划)条目数组。 */
export function isDataLinkEditArray(value: unknown): value is DataLinkEditItem[] {
if (!Array.isArray(value) || value.length === 0) return false;
return value.every(
(item) =>
isRecord(item) &&
("dataLinkForm" in item || typeof item.dataLinkTemplateId === "string")
);
}
/**
* 统一路由单据业务类型(expense / requisition / ...)。
* 优先级:模板规格类型 > 流程 formType / form.type > 表单字段特征 > 兜底 expense。
*/
export function resolveBillFormType(
form: BillDraftForm | Record<string, unknown> | undefined,
options?: { specType?: string; flowFormType?: string }
): string {
const specType = options?.specType?.trim();
if (specType) return specType;
const flowFormType = options?.flowFormType?.trim();
if (flowFormType) return flowFormType;
const explicitType = typeof form?.type === "string" ? form.type.trim() : "";
if (explicitType) return explicitType;
if (!form) return "expense";
if (
Array.isArray(form.details) ||
form.expenseMoney !== undefined ||
form.payMoney !== undefined
) {
return "expense";
}
if (
form.requisitionMoney !== undefined ||
form.requisitionDate !== undefined ||
form.feeDatePeriod !== undefined ||
Object.values(form).some((value) => isDataLinkEditArray(value))
) {
return "requisition";
}
return "expense";
}
/** 合并模板声明的 dataLinkEdits 字段与表单中实际存在的同类数组字段(去重)。 */
export function collectDataLinkEditFields(
form: Record<string, unknown>,
components?: BillValidationComponent[]
): string[] {
const fields = new Set<string>();
for (const component of components ?? []) {
if (component.field && component.type === "dataLinkEdits") {
fields.add(component.field);
}
}
for (const [key, value] of Object.entries(form)) {
if (isDataLinkEditArray(value)) {
fields.add(key);
}
}
return Array.from(fields);
}
function parseStrictCstDate(dateStr: string, label: string): { year: number; month: number; day: number; startMs: number } {
const trimmed = dateStr.trim();
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(trimmed);
if (!match) {
throw new ValidationError(`${label} 格式无效(需 YYYY-MM-DD):${dateStr}`);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const probe = new Date(Date.UTC(year, month - 1, day));
if (
probe.getUTCFullYear() !== year ||
probe.getUTCMonth() !== month - 1 ||
probe.getUTCDate() !== day
) {
throw new ValidationError(`${label} 不是合法日历日期:${dateStr}`);
}
const startMs = Date.UTC(year, month - 1, day) - CST_OFFSET_MS;
return { year, month, day, startMs };
}
/** 按东八区 (+08:00) 解析起止日期,返回毫秒边界与含首尾天数。 */
export function parseCstDateRange(
startDate: string,
endDate: string
): { startDate: string; endDate: string; startMs: number; endMs: number; days: number } {
const start = parseStrictCstDate(startDate, "开始日期");
const end = parseStrictCstDate(endDate, "结束日期");
const endMs = end.startMs + DAY_MS - 1;
if (endMs < start.startMs) {
throw new ValidationError(`结束日期 ${endDate.trim()} 不能早于开始日期 ${startDate.trim()}`);
}
const days = Math.round((end.startMs - start.startMs) / DAY_MS) + 1;
return {
startDate: startDate.trim(),
endDate: endDate.trim(),
startMs: start.startMs,
endMs,
days,
};
}
/** 返回当前东八区 (+08:00) 当天 00:00:00 的毫秒时间戳。 */
export function todayStartCstMs(nowMs: number = Date.now()): number {
const cst = new Date(nowMs + CST_OFFSET_MS);
return Date.UTC(cst.getUTCFullYear(), cst.getUTCMonth(), cst.getUTCDate()) - CST_OFFSET_MS;
}
/** 构造保留源货币元信息的本位币金额对象。 */
export function buildCnyMoney(standard: string, source?: BillMoney): BillMoney {
const base: BillMoney = isRecord(source) ? { ...source } : {};
return {
standardUnit: "元",
standardScale: 2,
standardSymbol: "¥",
standardNumCode: "156",
standardStrCode: "CNY",
...base,
standard,
};
}
/** 清理复制单据时的历史流转与只读字段。 */
export function stripHistoricalFlowFields(form: Record<string, unknown>): void {
for (const field of HISTORICAL_FLOW_FIELDS) {
delete form[field];
}
}
/**
* 重置表单中所有 dataLinkEdits(如行程规划)条目的 dataLinkId 为显式 null。
* 合思服务端审批通过后创建行程实例依赖该键显式存在且值为 null,绝不可 delete。
*/
export function resetDataLinkEditsForNewDraft(
form: Record<string, unknown>,
components?: BillValidationComponent[]
): number {
let count = 0;
for (const field of collectDataLinkEditFields(form, components)) {
const list = form[field];
if (!Array.isArray(list)) continue;
form[field] = list.map((item) => {
if (!isRecord(item)) return item;
count += 1;
const cloned = structuredClone(item) as DataLinkEditItem;
cloned.dataLinkId = null;
return cloned;
});
}
return count;
}
function hasFieldOrDeclaration(
form: Record<string, unknown>,
field: string,
components?: BillValidationComponent[]
): boolean {
return field in form || Boolean(components?.some((item) => item.field === field));
}
/** 对通用单据与差旅申请单应用标题、事由、金额与起止日期变更。 */
export function applyCommonAndRequisitionEdits(
form: Record<string, unknown>,
options: CommonAndRequisitionEditOptions
): void {
if (options.title?.trim()) {
form.title = options.title.trim();
}
if (options.reason !== undefined) {
form.description = options.reason;
}
if (options.amount !== undefined) {
const trimmed = options.amount.trim();
const num = Number(trimmed);
if (!trimmed || !Number.isFinite(num) || num <= 0) {
throw new ValidationError(`金额不合法(需大于 0 的数字):${options.amount}`);
}
form.requisitionMoney = buildCnyMoney(trimmed, form.requisitionMoney as BillMoney | undefined);
if (hasFieldOrDeclaration(form, "u_申请额度", options.components)) {
form["u_申请额度"] = buildCnyMoney(
num.toFixed(2),
form["u_申请额度"] as BillMoney | undefined
);
}
}
const hasStart = options.startDate !== undefined;
const hasEnd = options.endDate !== undefined;
if (hasStart !== hasEnd) {
throw new ValidationError("请同时指定 --start-date 和 --end-date(格式 YYYY-MM-DD)");
}
if (hasStart && hasEnd) {
const range = parseCstDateRange(options.startDate!, options.endDate!);
form.feeDatePeriod = { start: range.startMs, end: range.endMs };
if (hasFieldOrDeclaration(form, "u_差旅天数", options.components)) {
form["u_差旅天数"] = String(range.days);
}
for (const field of collectDataLinkEditFields(form, options.components)) {
const list = form[field];
if (!Array.isArray(list)) continue;
for (const item of list) {
if (!isRecord(item)) continue;
if (!Object.prototype.hasOwnProperty.call(item, "dataLinkId")) {
item.dataLinkId = null;
}
const dlf = item.dataLinkForm;
if (!isRecord(dlf)) continue;
for (const key of Object.keys(dlf)) {
if (key.endsWith("_入住日期") || key.endsWith("_行程日期")) {
dlf[key] = range.startMs;
} else if (key.endsWith("_离店日期")) {
dlf[key] = range.endMs;
} else if (key.endsWith("_行程开始日期")) {
dlf[key] = range.startDate;
} else if (key.endsWith("_行程结束日期")) {
dlf[key] = range.endDate;
}
}
}
}
}
}
+25 -5
View File
@@ -1,7 +1,9 @@
import type { KyInstance } from "ky";
import { NotFoundError, ValidationError } from "../../core/errors.js";
import { computeBillApprovalPlan, getFormSpecification, getRawBillFlow, submitBillFlow } from "./api.js";
import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js";
import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm } from "./draft-validation.js";
import { resolveBillFormType } from "./form-helpers.js";
import type { BillPlanNode } from "./types.js";
/**
* 纯接口提交单据草稿。
@@ -11,7 +13,8 @@ import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validat
* 2. `POST /api/flow/v1/flows/$<flowId>?pushMessageCode=debug`
* body: { name: "freeflow.submit", formType, form, nodes }
*
* 未指派审批人的节点必须由调用方通过 `--approver` 指定,绝不自动编造。
* 未指派审批人的普通必填节点必须由调用方通过 `--approver` 指定,绝不自动编造;
* ebot、自动跳过(skippedType != NO_SKIPPED)与条件/延迟计算节点原样回传。
*/
export interface SubmitBillOptions {
@@ -26,6 +29,20 @@ export interface SubmitBillResult {
response: unknown;
}
function nodeRequiresApprover(node: BillPlanNode): boolean {
if (node.type === "ebot") return false;
if (typeof node.skippedType === "string" && node.skippedType.trim() !== "" && node.skippedType !== "NO_SKIPPED") {
return false;
}
if (typeof node.conditionalType === "string" && node.conditionalType.trim() !== "") {
return false;
}
if (typeof node.laterCalcReason === "string" && node.laterCalcReason.trim() !== "") {
return false;
}
return true;
}
export async function submitBillDraft(
client: KyInstance,
corpId: string,
@@ -50,14 +67,17 @@ export async function submitBillDraft(
const spec = specificationId
? await getFormSpecification(client, corpId, String(specificationId))
: undefined;
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form, spec));
assertBillDraftValid(form as BillDraftForm, await loadBillValidationOptions(client, corpId, form as BillDraftForm, spec));
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 formType = resolveBillFormType(form as BillDraftForm, {
specType: spec?.type,
flowFormType: typeof flow.formType === "string" ? flow.formType : undefined,
});
const nodes = await computeBillApprovalPlan(client, corpId, flowId, flowPlanConfigId, form, formType);
if (nodes.length === 0) {
throw new ValidationError("审批计划为空,无法提交");
@@ -65,7 +85,7 @@ export async function submitBillDraft(
const unassigned: string[] = [];
for (const node of nodes) {
if (node.type === "ebot") continue;
if (!nodeRequiresApprover(node)) continue;
const hasApprover =
Boolean(node.approverId) || (Array.isArray(node.approverIds) && node.approverIds.length > 0);
if (hasApprover) continue;
+4
View File
@@ -49,6 +49,7 @@ export const FormSpecificationComponentSchema = z
optional: z.boolean().optional().default(true),
editable: z.boolean().optional().default(true),
hidden: z.boolean().optional().default(false),
hide: z.boolean().optional(),
isLinkageAssignment: z.boolean().optional().default(false),
assignmentRule: z.string().nullable().optional(),
priorityList: z.array(FormPriorityItemSchema).nullable().optional(),
@@ -92,6 +93,9 @@ export interface BillPlanNode {
type?: string;
approverId?: unknown;
approverIds?: unknown[];
skippedType?: string | null;
conditionalType?: string | null;
laterCalcReason?: string | null;
[key: string]: unknown;
}
+156
View File
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
import { createBillDraft, prepareBillDraft } from "./create.js";
import { buildBillCopyForm, copyBillAsDraft } from "./copy.js";
import { submitBillDraft } from "./submit.js";
import { editBillDraft } from "./write.js";
import { loadBillValidationOptions, validateBillDraft, type BillDraftForm } from "./draft-validation.js";
import { AuthenticationError } from "../../core/errors.js";
@@ -218,4 +219,159 @@ describe("bill API write contracts", () => {
headerMismatch.payMoney!.standardStrCode = "USD";
expect(validateBillDraft(headerMismatch).map(issue => issue.field)).toContain("payMoney.standardStrCode");
});
test("申请单复制与编辑保持 dataLinkId: null,并按 requisition 路由提交含条件/跳过节点的计划", async () => {
const reqSource: BillDraftForm = {
id: "ID_REQ",
code: "S26003502",
title: "旧差旅申请",
description: "旧事由",
specificationId: `reqSpec:${"b".repeat(32)}`,
submitterId: "staff",
requisitionDate: 1784563200000,
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
u_差旅天数: "2",
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
u_行程规划: [
{
dataLinkId: "OLD_DL_1",
dataLinkTemplateId: "tpl-trip",
dataLinkForm: { E_x_行程开始日期: "2026-07-24", E_x_行程结束日期: "2026-07-25" },
},
],
};
const writes: Array<{ url: string; json: any }> = [];
const plans: any[] = [];
const reqClient = {
get: (url: string) => ({
json: async () => {
if (url.includes("specifications/")) {
return {
items: [
{
id: "reqSpec",
name: "4.1日常差旅申请单",
type: "requisition",
configs: [{ ability: "flow", flowPlanConfigId: "plan-req" }],
components: [
{ field: "title", optional: false },
{ field: "u_深度现场项目", optional: false, hide: true },
{ field: "u_行程规划", type: "dataLinkEdits", optional: false },
],
},
],
};
}
if (url.includes("withSpecificationVersioned")) {
return {
items: [
{
name: "个人报销",
specifications: [{ id: `reqSpec:${"c".repeat(32)}`, originalId: "reqSpec", name: "4.1日常差旅申请单", type: "requisition", active: true }],
},
],
};
}
throw new Error(`Unexpected GET ${url}`);
},
}),
post: (url: string, payload: { json: any }) => ({
json: async () => {
if (url.endsWith("/flows/searchByCode")) {
return { items: [{ id: "ID01REQ", form: reqSource }] };
}
if (url.includes("/flows/flowId/")) {
const isDraft = url.includes("ID01DRAFT");
return {
value: {
id: isDraft ? "ID01DRAFT" : "ID01REQ",
state: isDraft ? "draft" : "paid",
formType: "requisition",
form: reqSource,
},
};
}
if (url.endsWith("/plans/computed")) {
plans.push(payload.json);
return {
value: {
nodes: [
{ id: "", name: "费用标准检查", type: "ebot" },
{ id: "", name: "所属部门主管", type: "normal", approverId: "staff-boss" },
{ id: "", name: "SVP加签", type: "normal", approverId: null, conditionalType: "RULE", laterCalcReason: "超标时审批" },
{ id: "", name: "出纳支付", type: "normal", approverId: null, skippedType: "NO_ABILITY" },
],
},
};
}
if (url.includes("/backlogs/") || url.endsWith("/flows/my") || url.endsWith("/flows/approved") || url.endsWith("/carbonCopy/search")) {
return { items: [] };
}
writes.push({ url, json: payload.json });
return { flow: { id: "ID01DRAFT", form: { ...payload.json.form, code: "S26005900" } } };
},
}),
} as unknown as KyInstance;
const copied = await copyBillAsDraft(reqClient, "corp", "S26003502", {
title: "新差旅申请",
reason: "新事由",
startDate: "2026-12-04",
endDate: "2026-12-05",
});
expect(copied.formType).toBe("requisition");
expect(copied.tripCount).toBe(1);
expect(writes[0].json.form.specificationId).toBe(`reqSpec:${"c".repeat(32)}`);
expect(writes[0].json.form.expenseMoney).toBeUndefined();
expect(writes[0].json.form.u_行程规划[0]).toHaveProperty("dataLinkId", null);
// 模拟待编辑草稿中行程缺失 dataLinkId 会被拦截,正常草稿允许 editBillDraft
(reqSource.u_行程规划 as Array<Record<string, unknown>>)[0].dataLinkId = null;
await editBillDraft(reqClient, "corp", "ID01DRAFT", { title: "修改后标题", reason: "修改后事由", amount: "1200" });
expect(writes[1].url).toContain("flows/$ID01DRAFT");
expect(writes[1].json.name).toBe("freeflow.edit");
expect(writes[1].json.form.requisitionMoney.standard).toBe("1200");
// submitBillDraft 应识别 formType=requisition,并放行 ebot / RULE 条件节点 / NO_ABILITY 跳过节点
await submitBillDraft(reqClient, "corp", "ID01DRAFT");
expect(plans[0].formType).toBe("requisition");
expect(writes[2].json.name).toBe("freeflow.submit");
expect(writes[2].json.formType).toBe("requisition");
expect(writes[2].json.nodes).toHaveLength(4);
});
test("submitBillDraft 仍拦截没有 conditionalType/skippedType 的普通未指派节点,以及非 draft 草稿 edit", async () => {
const { client, writes } = fixture();
await expect(
editBillDraft(
{
post: (url: string) => ({
json: async () =>
url.includes("/flows/flowId/")
? { value: { id: "ID01PAID", state: "paid", form: form() } }
: { items: [] },
}),
} as unknown as KyInstance,
"corp",
"ID01PAID",
{ title: "x" }
)
).rejects.toThrow("仅允许编辑 draft 草稿");
const unassignedClient = {
...client,
post: (url: string, payload: { json: any }) => {
if (url.endsWith("/plans/computed")) {
return {
json: async () => ({
value: { nodes: [{ id: "n1", name: "部门主管", type: "normal", approverId: null, skippedType: "NO_SKIPPED" }] },
}),
};
}
return (client as any).post(url, payload);
},
} as unknown as KyInstance;
await expect(submitBillDraft(unassignedClient, "corp", "f")).rejects.toThrow("未指派审批人");
expect(writes).toEqual([]);
});
});
+166 -3
View File
@@ -1,5 +1,18 @@
import type { KyInstance } from "ky";
import { deleteBillFlow } from "./api.js";
import { NotFoundError, ValidationError } from "../../core/errors.js";
import { deleteBillFlow, getRawBillFlow, updateBillFlow } from "./api.js";
import {
assertBillDraftValid,
loadBillValidationOptions,
type BillDraftForm,
type BillMoney,
type BillValidationComponent,
} from "./draft-validation.js";
import {
applyCommonAndRequisitionEdits,
collectDataLinkEditFields,
resolveBillFormType,
} from "./form-helpers.js";
/**
* 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$<flowId>` + `name` 区分)。
@@ -8,10 +21,160 @@ import { deleteBillFlow } from "./api.js";
* - `freeflow.edit` —— 保存草稿
* - `freeflow.submit` —— 提交送审(需先计算审批计划并把 nodes 带回)
* - `freeflow.delete` —— 删除草稿
*
* 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。
*/
export interface EditBillOptions {
title?: string;
reason?: string;
amount?: string;
startDate?: string;
endDate?: string;
components?: BillValidationComponent[];
}
export interface PreparedBillEdit {
flowId: string;
code: string;
formType: string;
beforeTitle: string;
afterTitle: string;
beforeDescription: string;
afterDescription: string;
amount: string;
tripCount: number;
feeDatePeriod?: { start?: number; end?: number };
form: BillDraftForm;
}
export interface EditBillResult {
flowId: string;
code: string;
title: string;
description: string;
formType: string;
amount: string;
tripCount: number;
form: BillDraftForm;
}
function resolveDisplayAmount(form: BillDraftForm, formType: string): string {
if (formType === "expense") {
return String(form.expenseMoney?.standard ?? "0");
}
const reqMoney = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
const quotaMoney = (form as Record<string, unknown>)["u_申请额度"] as BillMoney | undefined;
return String(reqMoney?.standard ?? quotaMoney?.standard ?? "0");
}
function countTrips(form: Record<string, unknown>, components?: BillValidationComponent[]): number {
let total = 0;
for (const field of collectDataLinkEditFields(form, components)) {
const list = form[field];
if (Array.isArray(list)) total += list.length;
}
return total;
}
/** 纯函数:基于现有草稿 form 构造更新后的草稿 form。 */
export function buildBillEditForm(
source: BillDraftForm,
options: EditBillOptions
): BillDraftForm {
const hasAnyChange =
options.title !== undefined ||
options.reason !== undefined ||
options.amount !== undefined ||
options.startDate !== undefined ||
options.endDate !== undefined;
if (!hasAnyChange) {
throw new ValidationError("请至少指定一项要修改的字段(--title / --reason / --amount / --start-date & --end-date)");
}
const form = structuredClone(source) as BillDraftForm;
const formType = resolveBillFormType(form);
if (options.amount !== undefined && formType === "expense") {
throw new ValidationError("报销单暂不支持通过 --amount 直接修改表头金额,请修改费用明细后保存");
}
applyCommonAndRequisitionEdits(form as Record<string, unknown>, options);
return form;
}
/** 读取并校验待编辑草稿(仅允许 draft 状态),用于预演与正式写入共享。 */
export async function prepareBillEdit(
client: KyInstance,
corpId: string,
target: string,
options: EditBillOptions
): Promise<PreparedBillEdit> {
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 flowId = String(flow.id ?? "");
if (!flowId) throw new NotFoundError("单据缺少流程 ID");
if (flow.state !== "draft") {
throw new ValidationError(`单据当前状态为 ${String(flow.state ?? "unknown")},仅允许编辑 draft 草稿`);
}
const validationOptions = await loadBillValidationOptions(client, corpId, sourceForm);
const flowFormType = typeof flow.formType === "string" ? flow.formType : undefined;
const formType = resolveBillFormType(sourceForm, {
specType: validationOptions.formType,
flowFormType,
});
const form = buildBillEditForm(sourceForm, {
...options,
components: validationOptions.components,
});
assertBillDraftValid(form, { ...validationOptions, formType });
const formRecord = form as Record<string, unknown>;
const period = formRecord.feeDatePeriod as { start?: number; end?: number } | undefined;
return {
flowId,
code: String(formRecord.code ?? target),
formType,
beforeTitle: String(sourceForm.title ?? ""),
afterTitle: String(form.title ?? ""),
beforeDescription: String(sourceForm.description ?? ""),
afterDescription: String(form.description ?? ""),
amount: resolveDisplayAmount(form, formType),
tripCount: countTrips(formRecord, validationOptions.components),
...(period ? { feeDatePeriod: { start: period.start, end: period.end } } : {}),
form,
};
}
/** 更新并保存草稿单据(`freeflow.edit`)。仅允许修改 draft 状态单据。 */
export async function editBillDraft(
client: KyInstance,
corpId: string,
target: string,
options: EditBillOptions
): Promise<EditBillResult> {
const prepared = await prepareBillEdit(client, corpId, target, options);
const value = await updateBillFlow(client, corpId, prepared.flowId, prepared.form);
const snapshot = (value.form ?? {}) as Record<string, unknown>;
return {
flowId: String(value.id ?? prepared.flowId),
code: String(snapshot.code ?? prepared.code),
title: String(snapshot.title ?? prepared.afterTitle),
description: String(snapshot.description ?? prepared.afterDescription),
formType: prepared.formType,
amount: prepared.amount,
tripCount: prepared.tripCount,
form: prepared.form,
};
}
/**
* 删除草稿单据及其费用明细(`freeflow.delete`)。
* 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。
@@ -125,9 +125,9 @@ function buildWorkflowTaskBase(type: string, options: Partial<AddTaskOptions> =
return {
name,
type: "stop",
label: options.label || "终止流程",
desc: options.desc || "如果满足条件终止流程",
groupName: "control",
label: options.label || "终止节点",
desc: options.desc,
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "active",
+3 -3
View File
@@ -51,7 +51,7 @@ bun install --frozen-lockfile
bun run build:plugin
```
`.mcp.json` 保持使用 `${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js`,由 Bun 1.3.14+ 启动。清理 `dist/` 后需要重新构建;普通 `bun test` 会在临时目录自行构建测试插件,不依赖预先存在的 bundle。
插件清单 `mcp.json` 保持使用 `${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js`,由 Bun 1.3.14+ 启动;仓库根目录的 `.mcp.json` 是 Claude Code 项目级配置,使用 `bun src/server.ts` 运行当前源码,不包含插件变量。清理 `dist/` 后需要重新构建插件 bundle;普通 `bun test` 会在临时目录自行构建测试插件,不依赖预先存在的 bundle。
完整插件包通过以下命令生成(需要系统 `tar`):
@@ -59,7 +59,7 @@ bun run build:plugin
bun run package:plugin
```
输出为 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,只包含 `.zcode-plugin/plugin.json`、`.mcp.json`、`skills/` 和新构建的 `dist/mcp/server.js`,不会复用仓库本地的旧 bundle。归档根目录即插件根目录,不包含企业凭据、本地笔记、源码或 `node_modules/`。解压后的插件仍需 Bun 1.3.14+,无需再次安装项目依赖。
输出为 `dist/bin/hose-use-plugin-v<版本>.tar.gz`,只包含 `.zcode-plugin/plugin.json`、`mcp.json`、`skills/` 和新构建的 `dist/mcp/server.js`,不会复用仓库本地的旧 bundle。归档根目录即插件根目录,不包含企业凭据、本地笔记、源码或 `node_modules/`。解压后的插件仍需 Bun 1.3.14+,无需再次安装项目依赖。
从 Release 下载插件包和同版本的 `checksums.txt`,核对对应资产的 SHA-256 后解压到独立目录,将该目录作为本地插件根目录加载。MCP 默认关闭,按插件配置启用后连接。
@@ -79,7 +79,7 @@ Skill 初始化明确执行 `skill install --yes`;失败会报告二进制已
- PR/main CI:冻结依赖安装、版本一致性、类型检查、全套测试、独立二进制和插件 bundle 的构建及 MCP 协议验证,以及完整插件包构建。测试会解包临时插件,核对包内清单和 Skill,并在独立目录验证离线脚本与 MCP 协议。
- 独立二进制:`bun run build:binary`;`bun run scripts/build/verify-binary.ts dist/bin/hose-use` 在空工作目录和没有 Bun 的 PATH 下验证版本、单工具发现、真实调用与错误返回。
- 插件 bundle:`bun run build:plugin`;`.mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
- 插件 bundle:`bun run build:plugin`;`mcp.json` 指定 Bun 1.3.14+,与共享 CLI 的 `bun:sqlite` 依赖一致;`bun run scripts/build/verify-binary.ts dist/mcp/server.js --plugin` 验证实际产物。
- Release:构建前检查 tag 版本、实际 HEAD 和 main 祖先关系;手动触发也必须输入 tag。正式构建显式使用 `--release`,两个发布源都上传校验清单,后台镜像上传失败会使任务失败。
Gitea 同时最多传输两个资产,每个资产最多尝试三次;已有文件经 SHA-256 验证一致时直接保留。镜像传输中断后,可在 main 上手动运行 Release workflow,传入原 tag 并启用 `mirror_only`:该模式下载并核对 GitHub 已发布资产(含插件包),只修复 Gitea,不重建或替换 GitHub 产物,也不移动 tag。