diff --git a/.gitignore b/.gitignore index 9c047f2..b4c185b 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ exports/ # Local drafts for repo-gh & AI Agents .drafts/* !.drafts/.gitkeep + +# Local API captures may contain tenant business data +/specs/hose-close-api/_tmp-captured/ diff --git a/README.md b/README.md index 5887177..35bf2d2 100644 --- a/README.md +++ b/README.md @@ -129,12 +129,12 @@ hose-use mcp # 启动 MCP Server (默认暴露 | `.agents/` | 本仓库的开发规则与技能发现配置,见 [.agents/README.md](./.agents/README.md);与产品分发用的 `skills/` 职责不同。 | | `.github/` | CI 与 Release 工作流,负责校验、构建和发布。 | | `.zcode-plugin/` | 受版本管理的 [IDE 插件清单](./.zcode-plugin/plugin.json),声明 Skill 路径、MCP 配置与用户开关。 | -| `specs/` | API 与工作流规范:`openapi/` 是包装层 YAML 源文件,`openapi.json` 是其打包结果,`openapi.raw.json` 是独立的下游接口规范,`workflow-schema.json` 是从 Zod 导出的工作流结构。生成入口见下文。 | +| `specs/` | specifications(规范)的缩写,存放 API 与工作流规范:`openapi/` 是包装层 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)。 | -| `docs/` | 跨模块参考与审阅记录。`modules/platform.md` 及部分域 README 仍含旧多工具 MCP 描述和旧代码路径,当前架构以 [AGENTS.md](./AGENTS.md) 与实现为准;`reviews/` 保留历史审阅及验证证据。 | +| `docs/` | 跨模块参考与审阅记录;Platform 模块说明和各域 README 提供当前 CLI 与服务导航,架构总纲见 [AGENTS.md](./AGENTS.md);`reviews/` 保留历史审阅及验证证据。 | | `enterprises/` | 仅跟踪配置示例与 [目录说明](./enterprises/README.md)。实际企业配置默认放在 `~/.config/hose-use/enterprises/`,仓库内其他企业 JSON 被忽略。 | | `.git/` 或 `.git` 文件 | Git 元数据;独立工作树中通常是指向共享仓库的文件。 | -| `.zcode/`(本地) | 已忽略的工具工作目录,现有主目录中保存 `plans/`;与 `.zcode-plugin/` 插件清单无关,不参与构建。 | +| `.zcode/`(本地) | 按需生成且已忽略的工具工作目录,可保存 `plans/`;与 `.zcode-plugin/` 插件清单无关,不参与构建。 | | `node_modules/`(本地) | `bun install` 安装的依赖,已忽略,可按 `bun.lock` 重建。 | | `exports/`(本地) | 已忽略的导出结果目录;文件是否仍需保留取决于具体业务,不属于源码或构建输入。 | @@ -143,7 +143,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) 声明本地数据与产物的忽略边界。 -- `ARCH-REVIEW.local.md`、`ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。 +- `ROADMAP.local.md` 等 `*.local.md` 是已忽略的本地笔记,不是构建依赖或正式文档入口;`.DS_Store` 是已忽略的 macOS Finder 元数据,可清理。 规范生成关系与命令: @@ -177,33 +177,6 @@ src/ 详细导航:[CLI](./src/cli/README.cli.md)、[Core](./src/core/README.core.md)、[业务域](./src/domains/README.domains.md)、[HTTP](./src/http/README.http.md)、[构建与分发](./src/packaging/README.packaging.md)。 -## 已迁移功能 - -以下为历史能力迁移清单,括号中保留旧工具标识;当前命令见上方 CLI 速查,MCP 统一通过 `hose_cli` 调用。 - -### Platform -- [x] 自建应用列表 (`platform_list`) -- [x] EASO 四步认证 -- [x] Piper 三步认证 -- [x] 工作流列表 (`platform_workflow_list`) -- [x] 工作流统计 (`platform_workflow_stats`) -- [x] 工作流配额 (`platform_workflow_charge`) -- [x] 工作流详情 (`platform_workflow_detail`) -- [x] 工作流启停 (`platform_workflow_toggle`) -- [x] 工作流运行任务 (`platform_workflow_jobs`) -- [x] 工作流 DSL 配置 (`platform_workflow_dsl`) -- [x] 企业员工列表 (`platform_workflow_staffs`) -- [x] 工作流 Webhook (`platform_workflow_webhook`) -- [x] 工作流采样数据 (`platform_workflow_sample`) -- [x] 跨应用汇总工作流 (`platform_workflow_list_all`) -- [x] 按节点类型递归查找工作流 (`platform_workflow_find_by_task`) -- [x] 工作流节点 JSON Schema 约束 - -### Core -- [x] 多企业切换 -- [x] Token 自动刷新(内存 + 持久化) -- [x] 动态域名配置 - ## 废弃功能 - [ ] HAB 智能审核(Agent/Rule)— 业务废弃 - [ ] AI 审批配置 — 业务废弃 diff --git a/docs/modules/platform.md b/docs/modules/platform.md index f12f53b..c4c8430 100644 --- a/docs/modules/platform.md +++ b/docs/modules/platform.md @@ -2,21 +2,24 @@ ## 整体架构 -当前 Platform 域是 TypeScript / Bun MCP Server 的一部分,代码位于: +Platform 与 DataLink 是共享 CLI、MCP、HTTP 和脚本集成的业务域。MCP 仅注册 `hose_cli`,入口统一经 `runCli` 分发;业务域不注册协议工具。代码位于: ```text src/domains/platform/ ├── types.ts # Zod schema 与类型定义 ├── api.ts # HTTP 传输层(EKB / EASO / Piper 接口封装) -└── tools.ts # MCP tool 注册 + 服务层聚合函数 +├── services.ts # 业务编排与服务门面 +└── workflow/ # 节点、脚本、分析、草稿状态、监听与告警 src/domains/datalink/ ├── types.ts # 应用、业务对象、字段、记录与权限模型 ├── api.ts # DataLink HTTP 接口封装 ├── services.ts # 应用/对象解析与过滤辅助 -└── tools.ts # DataLink MCP tools +└── fields.ts # 读写共用的唯一字段解析 -src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发 +src/cli/commands/ # 参数解析与展示,经域 services 调用业务 +src/server.ts # 单工具 hose_cli -> runCli +src/http/ # HTTP -> runCli ``` ## 三个 Client @@ -24,10 +27,10 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发 | Client | 域名 | 用途 | |---|---|---| | `EkbClient` | `app.ekuaibao.com` | 拉自建应用列表 | -| `EasoClient` | `unity.ekuaibao.com` | 工作流列表 / 统计 / 配额 / 详情 / 启停等 | -| `PiperClient` | `piper.ekuaibao.com` | 工作流详情(节点配置) | +| `EasoClient` | `unity.ekuaibao.com` | 统一认证与 EASO 资源 | +| `PiperClient` | `piper.ekuaibao.com` | 工作流列表、详情、配置保存与 Job 执行 | -> **已知现状**:`src/core/auth/piper.ts` 已实现了 Piper 认证链路,但当前 `src/server.ts` 中所有 Platform 工具统一使用 EASO client 派发。Piper 相关接口目前通过 EASO client 调用,后续如需严格区分 Piper 路径,需要在 `server.ts` 中单独派发。 +客户端装配统一位于 `src/core/http/`:主站使用 `session-client.ts`,Unity/EASO 使用 `unity-client.ts`,Piper 使用 `script-engine-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。 ## 认证链路 @@ -44,52 +47,37 @@ src/server.ts # MCP Server 入口,负责 tool 注册与客户端派发 2. 主站认证 → EASO JWT(`aud: EASO`,与 UNITY JWT 不同) 3. 请求携带:`Authorization: Bearer ` + `platformid: ` Header -## MCP Tools +## CLI 与域服务导航 -### DataLink 应用与业务对象 +MCP 调用方式统一为 `hose_cli` 的 `command` 参数传入下列命令。 -| Tool | 说明 | 后端 | +| CLI 命令 | 说明 | 后端 | |---|---|---| -| `datalink_platform_list` | 列出当前企业账号可见的启用自建应用 | EKB | -| `datalink_platform_get` | 获取应用详情及管理员、人员、角色、部门权限 | EKB | -| `datalink_entity_list` | 获取应用下业务对象、字段、操作和可见性配置 | EKB | -| `datalink_record_search` | 分页检索业务对象记录,支持 `filterBy` | EKB | -| `datalink_import_jobs` | 查看对象导入任务及最近导入结果 | EKB | +| `platform list/get` | 启用自建应用与详情、管理权限 | EKB | +| `platform entities/schema` | 业务对象、字段与可见性配置 | EKB | +| `platform records` | 分页检索业务记录,支持服务端过滤与文件流导出 | EKB | +| `platform imports` | 对象导入任务和结果 | EKB | +| `workflow list/find` | 跨应用查询与按节点类型查找 | EKB + Piper | +| `workflow get` | 工作流详情和节点配置 | Piper | +| `workflow save` | 按完整快照保存并校验版本;返回部分成功阶段 | Piper | +| `workflow refresh-chooses` | 主保存后的元数据刷新恢复,不重新提交快照 | Piper | +| `workflow history/logs/job` | 历史快照、运行记录和执行树 | Piper | +| `workflow patch` | 修改本地快照,生成草稿文件 | 本地 | +| `workflow check` | 扫描错误管道并持久化去重提醒 | EKB + Piper + 本地 | +| `workflow toggle/publish` | 切换启停状态 | Piper | -CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、`schema`、`records`、`permissions` 和 `imports`。 - -| Tool | 说明 | 后端 | -|---|---|---| -| `platform_list` | 列出企业下所有启用的自建应用 | EKB | -| `platform_workflow_list` | 列出指定自建应用下的工作流 | EASO | -| `platform_workflow_stats` | 获取指定自建应用的工作流统计 | EASO | -| `platform_workflow_charge` | 查询企业工作流用量配额 | EASO | -| `platform_workflow_detail` | 获取工作流详情(含节点配置) | EASO / Piper | -| `platform_workflow_toggle` | 启用/停用工作流 | EASO / Piper | -| `workflow save` (CLI) | 按完整快照保存工作流草稿并校验版本 | Piper | -| `workflow history` (CLI) | 读取工作流服务端版本快照历史 | Piper | -| `workflow patch` (CLI) | 在本地完整快照上修改节点路径,生成新草稿文件 | 本地 | -| `workflow logs` (CLI) | 查询指定工作流运行日志 | Piper | -| `workflow check` (CLI) | 扫描错误管道并持久化去重提醒 | 本地 + EASO | -| `workflow publish` (CLI) | 将已保存的工作流状态切换为启用 | Piper | -| `platform_workflow_jobs` | 查询工作流运行中的任务 | EASO / Piper | -| `platform_workflow_dsl` | 获取工作流 DSL 配置列表 | EASO / Piper | -| `platform_workflow_staffs` | 获取企业员工列表 | EASO / Piper | -| `platform_workflow_webhook` | 获取工作流 Webhook 信息 | EASO / Piper | -| `platform_workflow_sample` | 获取工作流测试/采样数据 | EASO / Piper | -| `platform_workflow_list_all` | 跨所有启用自建应用汇总工作流 | EASO | -| `platform_workflow_find_by_task` | 按节点类型递归查找工作流 | EASO | +统计、配额、DSL、员工与采样等底层能力由 `src/domains/platform/services.ts` 暴露,不存在同名的独立 MCP 工具。完整命令语义见 [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) 和 [DataLink 说明](../../src/domains/datalink/README.datalink.md)。 ## 服务层聚合能力 -`src/domains/platform/tools.ts` 中实现了两个服务函数: +`src/domains/platform/services.ts` 提供聚合服务函数: | 函数 | 说明 | |---|---| | `listAllWorkflows(clients, options)` | 遍历所有启用自建应用,汇总工作流列表 | | `findWorkflowsByTaskType(clients, taskType, options)` | 基于 `listAllWorkflows`,递归扫描每个工作流的 `tasks` 树,返回包含指定节点类型的流程 | -`platform_workflow_find_by_task` 支持 `includeDetail` 参数: +`findWorkflowsByTaskType` 的服务选项支持 `includeDetail`: - `false`(默认):直接基于 `listWorkflows` 返回的 `tasks` 做匹配。 - `true`:先调用 `getWorkflowDetail` 获取完整节点后再匹配。 @@ -97,7 +85,7 @@ CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、 `src/domains/platform/types.ts` 定义了递归、按节点类型区分的 Zod schema: -- `WorkflowTaskSchema`:13 路 discriminated union,覆盖 `webhook`、`condition`、`every`、`stop`、`http`、`flow-detail`、`code`、`code-js2`、`ekuaibao-datalink-filter`、`ekuaibao-datalink-create`、`data-convert`、`flow-create-task` 以及兜底 `unknown`。 +- `WorkflowTaskSchema`:按节点类型区分并递归建模,覆盖 `webhook`、`condition`、`every`、`stop`、`http`、`flow-detail`、`code`、`code-js2`、`ekuaibao-datalink-filter`、`ekuaibao-datalink-create`、`data-convert`、`flow-create-task` 以及兜底 `unknown`。 - 控制节点(`condition` / `every`)支持递归嵌套 `tasks`。 - `combineFilters` 为递归过滤组结构。 diff --git a/docs/reviews/2026-10-28-local-progress-integration.md b/docs/reviews/2026-10-28-local-progress-integration.md index a37a1b0..43c6033 100644 --- a/docs/reviews/2026-10-28-local-progress-integration.md +++ b/docs/reviews/2026-10-28-local-progress-integration.md @@ -33,7 +33,7 @@ ## 保留与未覆盖 - 原 `fix/review-20261023` 分支和 c758 工作区保留;本次选择性整合,因此原提交不会因本次 PR 自动成为主分支祖先。 -- 主目录 `specs/hose/` 中的接口盘点、schema 及临时抓包作为待整理资料保留。文档自行标注部分接口未进行一对一抓包校验,临时请求/响应不作为本次修复的发布资产;`.mimosa/` 属于工具会话状态及快照,不作为功能源码提交。 +- 主目录 `specs/hose/`(现已迁移至 [`specs/hose-close-api/`](../../specs/hose-close-api/README.md))中的接口盘点、schema 及临时抓包作为待整理资料保留。文档自行标注部分接口未进行一对一抓包校验,临时请求/响应不作为本次修复的发布资产;`.mimosa/` 属于工具会话状态及快照,不作为功能源码提交。 - 不回退已合并的工作流、MVEL、发票取消与插件分发修复;不重新跟踪 `dist/`,不打版本 tag,不发布新版。 - 本地校验不替代服务端完整业务校验;真实模板兼容性、核销关联复制的服务端限制和业务写入端到端验证仍需独立测试。无重试写入或自动修改业务输入。 - 重点复查:复制保留核销关联并计算净支付的业务选择,以及以前可直接复制/提交的错误表单现在会在本地被拒绝。规格读取失败也会阻止复制或送审。 diff --git a/docs/reviews/2026-10-29-domain-contract-fixes.md b/docs/reviews/2026-10-29-domain-contract-fixes.md new file mode 100644 index 0000000..3c3de7e --- /dev/null +++ b/docs/reviews/2026-10-29-domain-contract-fixes.md @@ -0,0 +1,87 @@ +# 2026-10-29 业务域与架构审查整改报告 + +## 交付范围 + +在用户确认四阶段整改方案后,以 `bb70362` 为基线实施。本轮解决已确认的 7 项问题,保留既有业务层公开函数签名和公共 SDK 初始化结构。离线整改完成后,按用户追加授权在「沈玥妍测试企业」进行真实服务验收,并补齐验收发现的两处轻量修复;交付通过 PR 合入主分支,不发布版本或替换全局安装。 + +分阶段本地提交:A 为 `9916936`,B 为 `51fb54d`,C 为 `55d31e2`;D 为 `6249fee`,包含 SDK 示例、文档、架构验证和本报告。真实服务验收补丁另行提交。 + +## 实际修改与前后行为 + +| 原问题 | 修改位置与原因 | 修改后的行为 | +|---|---|---| +| 协助登录同名员工直接取第一人 | [services.ts](../../src/domains/assist-platform/services.ts)、[enter.ts](../../src/cli/commands/assist-platform/enter.ts)、[命令元数据](../../src/cli/command-metadata.ts) | 姓名优先精确匹配,只允许唯一启用员工,重复行按员工 ID 去重;歧义发生时不换票。新增 `--staff-id` 并贯通预演、换票和保存;管理员模式与员工选项冲突时拒绝 | +| DataLink 读取拒绝歧义而写入取首项 | [fields.ts](../../src/domains/datalink/fields.ts)、[services.ts](../../src/domains/datalink/services.ts)、[api.ts](../../src/domains/datalink/api.ts) | 筛选、`--set` 和 JSON 安全合并共用物理键优先、标签/模糊匹配唯一的解析。两个字段都叫“金额”时拒绝写入,明确 `E__` 可继续使用。未知原始字段与 `--raw` 保持兼容;未声明的系统键不被误匹配到 `inactive` 等业务标签 | +| 单据创建弱于复制/提交校验 | [create.ts](../../src/domains/bill/create.ts)、[draft-validation.ts](../../src/domains/bill/draft-validation.ts) | 创建准备流程复用现有校验器,并使用已读取的真实表头/明细规格;缺少规格、明细必填项或超过模板文本上限时,预演和执行都在创建请求前拒绝 | +| HTTP 成功被当成写入成功 | [bill/api.ts](../../src/domains/bill/api.ts)、[copy.ts](../../src/domains/bill/copy.ts)、[submit.ts](../../src/domains/bill/submit.ts)、[templates.ts](../../src/domains/bill/templates.ts)、[write.ts](../../src/domains/bill/write.ts)、[platform/api.ts](../../src/domains/platform/api.ts) | 单据 7 处 Session HTTP 调用收口到传输层,检查已知业务错误和有效流程 ID;保留 `flow/value/裸对象` 成功包装。审批计划失败不继续送审。Piper chooses/删除检查业务码,同时兼容空成功响应 | +| 工作流保存没有部分成功语义 | [save-error.ts](../../src/domains/platform/workflow/save-error.ts)、[services.ts](../../src/domains/platform/services.ts)、[draft.ts](../../src/cli/commands/workflow/draft.ts)、[errors.ts](../../src/core/errors.ts)、[runner.ts](../../src/cli/runner.ts) | 主 PUT 成功、chooses 失败时保留服务端版本,SDK 抛出 `WorkflowSavePartialError`;JSON 错误可携带 `details`。`save --in-place` 仍同步版本并返回非零、`status: partial`、`remoteSaved: true` 与恢复命令。主 PUT 失败不更新本地文件 | +| 重放没有最终鉴权检查 | [factory.ts](../../src/core/http/factory.ts) | 首次续期后仅重放一次;重放响应再次检查 HTTP 401 与 `error-type`,包括 HTTP 200 携带鉴权错误头的情况。持续失败抛出鉴权异常,不发起第三次请求;普通 HTTP 错误保留 Ky 语义 | +| SDK 示例与实际导出不符 | [README.datalink.md](../../src/domains/datalink/README.datalink.md)、[sdk-example.test.ts](../../scripts/sdk-example.test.ts) | 示例显式选择企业、获取客户端、传入企业参数并处理应用/对象未命中;测试直接提取 Markdown 示例,与真实 SDK 导出一起编译,不连接企业服务 | + +## 工作流部分成功的恢复 + +```bash +hose-use workflow refresh-chooses --platform-id= --corp= --dry-run +hose-use workflow refresh-chooses --platform-id= --corp= --yes +``` + +该命令只调用 chooses 刷新,不重新提交整个工作流。回归验证了“一次主保存 + 一次失败刷新 + 一次定向恢复”的请求序列。不要把 `remoteSaved: true` 当作可以安全重发主保存的失败。 + +## 架构与文档 + +- [architecture-boundaries.test.ts](../../src/cli/architecture-boundaries.test.ts) 从正则提取改为 TypeScript AST,覆盖相对路径、项目别名、再导出、字面量动态导入与类型导入,并统一路径分隔符;新增单据 Session HTTP 只能留在传输模块的检查。 +- [模块导航](../../docs/modules/platform.md)、[Platform README](../../src/domains/platform/README.platform.md)、[DataLink README](../../src/domains/datalink/README.datalink.md) 和 [域总说明](../../src/domains/README.domains.md) 修正了不存在的 `tools.ts`、旧多工具 MCP 和旧 Piper 认证路径描述。 +- 产品 Skill 补充了明确员工 ID 与部分保存恢复指引;CLI/Core/Workflow 域说明同步了新增契约。根 README 更新了清理后的目录说明。 + +## 相对方案的具体实现选择 + +1. 增加纯函数 `datalink/fields.ts`,使传输层与业务层共享解析规则,避免 API 反向导入 services 形成依赖环。 +2. 用 `WorkflowSavePartialError` 与可选 `EkbError.details` 表达部分成功,普通错误输出保持原结构;新增 `refresh-chooses` 落实定向恢复,不引入自动重发或回滚。 +3. SDK 只修正文档和增加编译验证,没有更改现有 `initCorpRuntime` 返回结构,也没有把配置/客户端装配扩展成跨模块重构。 +4. 收尾回归补充了系统字段的匹配优先级,防止统一解析时让 `active` 被模糊匹配为业务标签 `inactive`。 + +以上均服务于已确认的问题与兼容范围,没有新增业务能力重构。 + +## 实际验证 + +| 阶段 | 全量 `bun test` | `bun run check` | +|---|---|---| +| A:唯一员工与字段 | 902 通过 / 0 失败 | 通过;首轮发现测试 fetch 类型转换缺少 Bun 的 `preconnect` 类型,修正转换后通过 | +| B:单据契约 | 911 通过 / 0 失败 | 通过 | +| C:保存与重放 | 922 通过 / 0 失败 | 通过 | +| 最终:文档、示例和边界 | **926 通过 / 0 失败,119 文件,4379 次断言** | 通过 | +| 真实验收补丁后 | **929 通过 / 0 失败,120 文件,4392 次断言** | 通过 | + +- 相对整改前 892 项,新增 37 项测试。验证涵盖歧义时无换票/写请求、精确 ID/物理键正例、单据错误响应、计划失败不送审、部分保存和恢复、认证重放次数/请求体、身份查询企业范围、复制时不注入字段,以及 README SDK 示例编译。 +- 最终 `bun run check:version` 通过,版本保持 `0.8.21`;`git diff --check` 通过;实际 CLI 帮助包含 `refresh-chooses`。 +- 全量测试使用临时配置、账号、Token/协助会话文件、企业目录和 SQLite 路径;网络测试均为假接口或测试内回环服务。测试流程包含既有插件重新打包与源码/插件冒烟验证。 +- 本地验证日志保存在 Git 忽略目录 `.drafts/review-20261029/`:离线整改日志为 `phase-d-final/`,真实验收补丁的最终全量日志为 `live-final/tests.log`、`live-final/typecheck.log`。原始审查复现材料保留,不覆盖历史结果。 + +## 指定测试企业真实验收与补丁 + +业务写入均使用当前源码 CLI,显式指定「沈玥妍测试企业」并采用无状态企业选择;原始响应和临时脚本仅保存在 Git 忽略目录 `.drafts/live-smoke-20261029/`,不提交租户载荷或凭证。 + +| 验收项 | 实际结果 | +|---|---| +| 模板及写前校验 | 读取 58 个模板;缺少收款人、租户必填字段及超长标题均在创建前拒绝;使用可用差旅模板完成正例 | +| 草稿生命周期 | 0.01 元草稿创建、复制预演、真实复制(不保留附件)、校验、删除预演和真实删除全部通过;未提交审批 | +| 工作流正常保存 | 在测试应用创建一个始终停用的独立工作流;保存成功并同步版本,旧版本草稿再次保存被拒绝,定向刷新预演和执行通过 | +| 工作流部分成功恢复 | 真实主 PUT 成功后,仅在本地注入一次 chooses 失败响应;返回非零、`partial`、`remoteSaved: true`,本地版本同步;返回的恢复命令真实执行成功,主保存仅一次。此失败响应是注入场景,不是服务端自然故障 | +| 清理 | 删除全部 4 张本轮创建的草稿(含前两次失败复制留下的源草稿)及独立工作流;原有 15 个工作流的 ID、状态、更新时间与基线一致 | +| 身份查询范围 | 修复后真实执行 `corps whoami --corp=...`,结果只包含指定测试企业 | + +验收暴露的问题与实际修复: + +1. [whoami.ts](../../src/cli/commands/corps/whoami.ts) 原来忽略显式 `--corp`,首次身份核验读取了本地名录中的 27 个企业身份,超出了本次测试范围;已向用户说明并停止该路径,未在其他企业执行审批或业务数据写入。现按已解析企业过滤,无效企业拒绝回退全量,不带参数仍保留全量视图。新增 [范围回归](../../src/cli/commands/corps/whoami-scope.test.ts),覆盖指定、无参数、无效和离线模式。 +2. [copy.ts](../../src/domains/bill/copy.ts) 原来无条件添加 `u_发票总金额`、发票及附件字段,真实通用模板先后拒绝了自定义属性和附件属性。现只清空源单已有的对应字段;[传输契约回归](../../src/domains/bill/write-contract.test.ts) 验证请求不再注入这些属性,真实创建到复制、删除的闭环通过。 +3. [SDK 示例测试](../../scripts/sdk-example.test.ts) 统一虚拟源文件路径比较,兼容不同路径分隔符;本地编译通过,未单独运行 Windows 环境。 + +这些补丁未扩大既定业务功能,修复了真实验收中发现的查询范围和模板兼容问题。 + +## 未覆盖及重点复查 + +- 真实验收覆盖上述指定测试企业和模板;未执行送审、审批、付款、协助员工换票或工作流发布/运行。员工歧义、字段歧义、持续鉴权失败等场景由隔离回归覆盖,其他租户响应变体与权限未逐一验收。 +- 重点复查行为收紧:过去会选第一人的同名请求、会选首字段的歧义赋值、缺失必填字段的创建,以及缺少有效 ID 的写入响应,现在均会拒绝。 +- 使用者应处理新增的工作流部分成功状态与异常;它仍是非零退出,但 `remoteSaved: true` 表示主数据已经提交。若未指定 `--in-place`,需要调用者保留返回版本或重新读取远端。 +- 公共 SDK 仍复用 CLI helper;此次保持兼容,仅修正示例。全面提取独立 SDK 运行时不在本轮方案中。 +- 架构静态检查不等于对任意动态模块加载、所有网络别名和业务语义的完备证明。没有扩展成全仓库重写,也没有删除原有历史审查记录。 diff --git a/scripts/sdk-example.test.ts b/scripts/sdk-example.test.ts new file mode 100644 index 0000000..c0b407c --- /dev/null +++ b/scripts/sdk-example.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import ts from "typescript"; + +test("DataLink 公共 SDK 的 README 示例与实际导出一同编译", () => { + const root = resolve(import.meta.dir, ".."); + const readme = readFileSync(resolve(root, "src/domains/datalink/README.datalink.md"), "utf8"); + const code = readme.split("## 公共 SDK")[1]?.match(/```typescript\n([\s\S]*?)\n```/)?.[1]; + expect(code).toBeDefined(); + const file = resolve(root, "src/__sdk-readme-example__.ts"); + const source = code!.replace('"hose-use/sdk"', '"./sdk.js"'); + const options: ts.CompilerOptions = { noEmit: true, strict: true, skipLibCheck: true, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, target: ts.ScriptTarget.ESNext, types: ["bun"] }; + const host = ts.createCompilerHost(options); + const original = host.getSourceFile; + host.getSourceFile = (name, ...args) => resolve(name) === file ? ts.createSourceFile(file, source, ts.ScriptTarget.ESNext, true) : original(name, ...args); + const diagnostics = ts.getPreEmitDiagnostics(ts.createProgram([file], options, host)); + expect(diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, "\n"))).toEqual([]); +}, 15000); diff --git a/skills/hose-use/references/assist-platform.md b/skills/hose-use/references/assist-platform.md index 902e506..32f0716 100644 --- a/skills/hose-use/references/assist-platform.md +++ b/skills/hose-use/references/assist-platform.md @@ -4,6 +4,8 @@ 合思协助平台是面向实施、运维与服务团队的专属运营系统(管理 34 万+ 企业租户库),与终端企业 SaaS 门户(`app.ekuaibao.com`)互为独立站点。通过本模块,Agent 可完成从扫码登录、多租户全量库检索、协助工单提取、指定员工身份免密换票,到自动将目标企业一键持久化落盘至本地名录的全流程。 +使用员工身份时,`enter --staff <姓名>` 必须匹配唯一启用员工;同名时改用 `--staff-id <员工ID>`,不会自动选择第一人。`--admin` 不能与员工选项组合。 + 支持顶层命令:`hose-use assist-platform`(别名:`hose-use assist-center`, `hose-use ap`)。 --- diff --git a/skills/hose-use/references/workflow.md b/skills/hose-use/references/workflow.md index 3a49762..7c2a726 100644 --- a/skills/hose-use/references/workflow.md +++ b/skills/hose-use/references/workflow.md @@ -1,5 +1,7 @@ # 应用管理、自建应用与工作流指南 (App, Platform & Workflow Guide) +保存返回 `remoteSaved: true` / `status: "partial"`,或错误 `details.remoteSaved: true` 时,主保存已经完成。保留返回的新版本,仅用 `workflow refresh-chooses --platform-id= --yes` 恢复元数据刷新;不要重复提交完整快照。`save --in-place` 会在部分成功时同步本地版本,退出码仍非零。 + 本参考专卷详细说明合思桌面端【应用管理】、企业后台【自建应用】(DataLink 数据建模与底层记录)以及任务节点工作流(Workflow)的查询与使用。 > **核心概念辨析(严禁混淆)**: diff --git a/specs/hose-close-api/README.md b/specs/hose-close-api/README.md new file mode 100644 index 0000000..d344930 --- /dev/null +++ b/specs/hose-close-api/README.md @@ -0,0 +1,100 @@ +# 合思内部接口规范(hose-close-api) + +本目录只做一件事:**从当前代码契约中盘点已经在用的合思/易快报接口**,记录 method、path、域名、请求参数/body、响应结构和来源。 + +- Git 管理本目录的接口清单、JSON Schema 和维护说明。`hose-close-api` 以网页内部接口及相关认证链路为主,也记录代码使用的 OpenAPI。 +- `_tmp-captured/` 只保留在本地,已被 Git 忽略;其中可能含租户模板、工作流与业务 ID,不随仓库分发。文中的抓包引用是本地验证线索,新克隆中可能不存在。 +- 本包不是官方 OpenAPI。`code-derived` 表示只从 `src/` 推导,没有 1:1 抓包验证。 +- 历史参考:`specs/openapi.raw.json`(未修改)。其中部分响应包装写法已过时,不能直接当契约使用。 + +## 目录结构 + +```text +specs/hose-close-api/ +├── README.md # 本文件:范围、来源、约定、覆盖统计 +├── endpoints.md # 按域分组的正式接口清单(66 个代码接口 + 8 个 legacy 参考) +├── schemas/ # 代码契约对应的 JSON Schema +│ ├── form-specification.schema.json +│ ├── workflow-detail.schema.json +│ ├── workflow-snapshot.schema.json +│ ├── workflow-chooses.schema.json +│ └── workflow-job-execution.schema.json +└── _tmp-captured/ # 本地临时抓包,Git 忽略,不随仓库分发 +``` + +> `_tmp-captured/` 中的付款单模板保存、工作流保存/chooses/快照、Job 执行和最新页面请求清单是本地临时资料;本次整理保留其内容,仅迁移目录位置。 + +## 覆盖统计 + +以下为 2026-10-28 整理快照,来源行号用于定位当时实现,后续代码变动可能使行号偏移。 + +| 域 | 代码接口数 | 主要来源 | +|---|---:|---| +| auth / corps | 19 | `src/core/auth/login.ts`、`openapi-v1.ts`、`link-import.ts`、`src/core/http/*` | +| platform / workflow | 30 | `src/domains/platform/api.ts` | +| bill / specifications | 5 | `src/domains/bill/api.ts`、`templates.ts`、`src/domains/feetype/api.ts` | +| assist-platform | 12 | `src/domains/assist-platform/api.ts` | +| **合计** | **66** | | + +另有 8 个仅存在于 `specs/openapi.raw.json` 的历史接口,作为 legacy 参考单列,不计入 66 个代码接口。 + +## 来源 + +- `src/domains/platform/api.ts` + `src/domains/platform/types.ts` +- `src/domains/bill/api.ts` + `src/domains/bill/types.ts` + `src/domains/bill/templates.ts` +- `src/domains/feetype/api.ts` +- `src/domains/assist-platform/api.ts` +- `src/core/auth/login.ts`、`src/core/auth/openapi-v1.ts`、`src/core/auth/link-import.ts` +- `src/core/http/openapi-client.ts`、`unity-client.ts`、`script-engine-client.ts`、`assist-platform-client.ts`、`session-client.ts` +- 历史参考:`specs/openapi.raw.json` + +## 域名约定 + +| 代号 | 基地址 | 用途 | +|---|---|---| +| `BC` | `https://business-center.ekuaibao.com` | 账号登录、企业列表、企业切换、换发 hose token | +| `IDP` | `https://idp.hosecloud.com` | 用授权码换主站 access_token | +| `EKB` | `https://app.ekuaibao.com`(按企业集群可能是 `wx2` 等) | 主站业务、模板、OpenAPI、自建应用列表 | +| `EASO` | `https://unity.ekuaibao.com` | EASO 平台、协助平台网关 | +| `PIPER` | `https://piper.ekuaibao.com` | 工作流(pipeline)与 Job 执行 | +| `ASSIST` | `https://unity.ekuaibao.com/api` | 协助平台客户端前缀 | +| `GW` | `https://d9jxeccs5j.sealosgzg.site` | 灰度节点开通网关(非合思域名) | + +## 响应包装约定 + +- **Piper / EASO 业务接口**:常见 `{ "code": 200, "msg": "...", "data": ... }`。`code` 是数字;`src/domains/platform/api.ts` 把非 200 的 `code` 当错误。 +- **主站列表接口**:常见裸 `{ "items": [...] }`、`{ "value": ... }` 或直接数组。 +- **快照接口**:`inputs` / `outputs` 在响应里是 JSON 编码字符串,不是数组;`WorkflowSnapshotSchema` 兼容字符串和数组。 +- **Job 执行接口**:`/execution`、`/execution/level/failed` 的 `data` 可能是数组,也可能是 `{number,size,totalPages,totalItems,items}` 分页对象。 +- **协助平台**:`assist-platform-client.ts` 使用 `prefix: "https://unity.ekuaibao.com/api"`;代码中部分 path 又以 `api/` 开头,ky 会直接拼接。`endpoints.md` 保留代码字面量,实际 URL 以运行时为准。 + +## 关键字段约定 + +单据模板组件的字段 key 是 **`field`**,不是 `key`/`name`。代码侧 `src/domains/bill/types.ts` 的 `FormSpecificationComponentSchema` 也以 `field` 为准。 + +```json +{ + "field": "u_单据编号", + "label": "关联发票核销单号", + "type": "text", + "optional": true, + "maxLength": 140 +} +``` + +本次抓包确认:付款单模板新增字段的 `field` 是 `u_单据编号`,`label` 是 `关联发票核销单号`。相关原始请求见本地 `_tmp-captured/`。 + +## 维护方式 + +1. 只从实际代码调用点新增或修正正式接口;不要凭截图或推测补字段。 +2. 每个条目在 `endpoints.md` 标注 `src/...:line` 来源。 +3. 响应结构优先引用 `schemas/`;没有 schema 的写关键字段和包装形态。 +4. 新抓包先放本地 `_tmp-captured/`;核实后只将接口契约与匿名示例提升为正式条目,不直接提交租户数据。 +5. 不提交凭证、Cookie、token、企业名、员工姓名、手机号。 + +## 已知缺口 + +- 代码中没有 `PUT /api/form/v2/specifications/{id}/$false`(模板保存)、`POST /api/form/v2/specifications/search/all`、`GET /api/form/v2/specificationGroups`、`GET /api/form/v2/requisition/expenseLink/{id}`、`POST /api/v1/requisition/autoAssociate/config/list`;这些只出现在本次抓包,见 `_tmp-captured/`。 +- 代码中没有 assist-platform 的抓包,全部按代码契约记录。 +- 主站响应包装存在 `items` / `value` / 裸对象多种形态,部分接口未做 1:1 抓包校验。 +- `specs/openapi.raw.json` 中 `code` 写成 `"SUCCESS"` 等旧格式,与当前代码按数字判断不一致,仅作历史参考。 diff --git a/specs/hose-close-api/endpoints.md b/specs/hose-close-api/endpoints.md new file mode 100644 index 0000000..98889b1 --- /dev/null +++ b/specs/hose-close-api/endpoints.md @@ -0,0 +1,185 @@ +# 正式接口清单 + +只收录当前代码契约中存在的接口。域名代号见 [README.md](./README.md)。`来源` 精确到文件与行号;`抓包` 中的“否”表示本包没有 1:1 原始抓包,不代表接口不可用。 + +- 代码接口:66 个 +- legacy 参考:8 个(仅存在于 `specs/openapi.raw.json`,不计入 66) +- 抓包参考:本地 `_tmp-captured/`,Git 忽略,不随仓库分发;来源与覆盖统计见 [README](./README.md) + +## 1. auth / corps(19) + +| # | Method | Path | 请求 | 响应 | 来源 | 抓包 | +|---|---|---|---|---|---|---| +| A01 | GET | `BC /cloud-auth/public/auth/public-key` | 无 | `{data:{base64}}` | `src/core/auth/login.ts:47` | 否 | +| A02 | POST | `BC /cloud-auth/public/auth/login-by-password` | `{deviceType,username,password}`;password 为 RSA 加密密文 | `{data:,errorCode?,errorMessage?}` | `src/core/auth/login.ts:104` | 否 | +| A03 | POST | `BC /cloud-auth/public/auth/send-verification-code` | `{bizType:"LOGIN",account:"86-",channelType:"SMS",...captchaParams}` | `{data:{codeId},errorCode?,errorMessage?}` | `src/core/auth/login.ts:139` | 否 | +| A04 | POST | `BC /cloud-auth/public/auth/login-by-code` | `{username,code,codeId,deviceType}` | `{data:,errorCode?,errorMessage?}` | `src/core/auth/login.ts:162` | 否 | +| A05 | GET | `BC /cloud-auth/public/auth/list-corporations` | Header `cloud-auth-token` | `{data:{items:[CorporationItem],externalItems:[]},errorCode?,errorMessage?}`;Item 字段见下 | `src/core/auth/login.ts:242` | 否 | +| A06 | POST | `BC /cloud-auth/public/auth/switch-corporation` | Header `cloud-auth-token`;body `{corporationId,userId,cluster}` | `{data:{accessToken:},errorCode?,errorMessage?}` | `src/core/auth/login.ts:269` | 否 | +| A07 | POST | `IDP /api/idp/public/oauth2/token` | `{clientId:"whispered-app",grantType:"authorization_code",code:,withIdToken:false}` | `{access_token,token_type,expires_in,refresh_token?,id_token?}` | `src/core/auth/login.ts:288` | 否 | +| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:}` | `src/core/http/unity-client.ts:70` | 否 | +| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 | +| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/script-engine-client.ts:68` | 否 | +| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer `、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-client.ts:119` | 否 | +| A12 | GET | `EKB /api/account/v2/session` | Headers `accesstoken`、`corpid`、可选 `staffid` | `{value:{id,userId,loginStaffId,corporationId,platform,isAssistPlatform,isShortTermToken,assistId,operationUserId,operationUserName,privilege,deviceType,loginAccountType,loginTime,expTime}}` | `src/core/auth/link-import.ts:329` | 否 | +| A13 | POST | `EKB /api/openapi/v1/auth/getAccessToken` | `{appKey,appSecurity}` | `{value:{accessToken,corporationId,expireTime,errorCode?,errorMessage?}}`;也兼容顶层 `accessToken`/`token` | `src/core/auth/openapi-v1.ts:133` | 否 | +| A14 | POST | `EKB /api/openapi/v1.1/provisional/getProvisionalAuth` | Query `{accessToken}`;body `{uid,pageType:"home",expireDate}` | `{value:{message:}}`,从 URL 的 `accessToken` 参数取临时会话 token | `src/core/auth/openapi-v1.ts:199` | 否 | +| A15 | GET | `EKB /api/innerapi/v1/key` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{items:[{id,name,appKey,appSecurity}]}` | `src/core/auth/openapi-v1.ts:240` | 否 | +| A16 | GET | `EKB /api/openapi/v1/roleDefGroups` | Query `{accessToken}` | `{items:[{id,name,enName,roleDefs:[{id,name,enName,sourceType,sourceTypeValue}]}]}` | `src/core/auth/openapi-v1.ts:388` | 否 | +| A17 | GET | `EKB /api/openapi/v1/roledefs/${roledefId}` | Query `{accessToken,staffBy,pathType:"name"}` | `{value:{id,name,count,contents:[{staffs:[]}]}}` | `src/core/auth/openapi-v1.ts:434` | 否 | +| A18 | POST | `EKB /api/openapi/v1/staffs/getStaffIds` | Query `{accessToken}`;body `{type:"STAFFID",conditionIds:[...]}` | `{items:[StaffDetail]}` | `src/core/auth/openapi-v1.ts:473` | 否 | +| A19 | POST | `EKB /api/openapi/v2/auth/token` | `{appKey,appSecurity}` | `{value}` 或 `{token}` 或 `{accessToken}` | `src/core/http/openapi-client.ts:50` | 否 | + +`CorporationItem` 代码字段(`src/core/auth/types.ts:37`): + +```text +corporationId, corporationName, corporationEnName?, cluster, clientId?, +staffId, userId, sourceChannel?, baseUrl?, external?, needAuth? +``` + +## 2. platform / workflow(30) + +工作流接口通过 Piper 客户端调用(`src/core/http/script-engine-client.ts`): +`Authorization: Bearer `、`platformid: `、可选 `hoseaccesstoken`。 +`listPlatforms` 例外,它走主站 `ekbClient`。 + +| # | Method | Path | 请求 | 响应 | 来源 | 抓包 | +|---|---|---|---|---|---|---| +| P01 | GET | `EKB /api/v2/datalink/platform/search` | Query `{scope:"enable",corpId}` | `{items:[Platform]}` | `src/domains/platform/api.ts:82`、`src/domains/datalink/api.ts:55` | 否 | +| P02 | GET | `PIPER /api/easo/pipelines/logs` | Query `{platformId,number,pageSize}` | `{code,msg,data:{pipelineNum,runningNum,allRunCount,errorCount,number,size,totalPages,totalItems,pipelineList:[Workflow]}}` | `src/domains/platform/api.ts:98` | legacy | +| P03 | GET | `PIPER /api/easo/stats` | Query `{platformId}` | `{code,msg,data:{total,completed,failed,started,pipelineOpenCount,pipelineCloseCount,pipelineAllCount}}` | `src/domains/platform/api.ts:112` | 否 | +| P04 | GET | `PIPER /api/easo/charge` | 无 | `{code,msg,data:{corporationId,status,orderType,total,used,remaining}}` | `src/domains/platform/api.ts:121` | 否 | +| P05 | GET | `PIPER /api/easo/pipelines/{pipelineId}` | 无 | `{code,msg,data:WorkflowDetail}`;结构见 `schemas/workflow-detail.schema.json` | `src/domains/platform/api.ts:131` | legacy | +| P06 | PUT | `PIPER /api/easo/pipelines/{id}` | body 为完整 `WorkflowDetail`;Web 保存会带 `inputs:[{key:"$platformId",value:}]` | `{code:200,msg:"修改成功",data:WorkflowDetail}`;响应 `data` 不含 `inputs` | `src/domains/platform/api.ts:141`、`src/domains/platform/services.ts:68` | 见 `_tmp-captured` | +| P07 | PUT | `PIPER /api/easo/pipelines/{id}/chooses` | 无 body | `{code,msg,data:[{key,label,displayName,choose}]}`;`choose` 为递归选择器树 | `src/domains/platform/api.ts:155`、`services.ts:79` | 见 `_tmp-captured` | +| P08 | PUT | `PIPER /api/easo/pipelines/{id}/copy` | body 为 `WorkflowDetail`(复制后的详情) | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/api.ts:163` | 否 | +| P09 | POST | `PIPER /api/easo/pipelines` | body 为工作流对象 | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/api.ts:173` | 否 | +| P10 | DELETE | `PIPER /api/easo/pipelines/{id}` | 无 | 读取并丢弃响应文本;代码视为成功 | `src/domains/platform/api.ts:183` | 否 | +| P11 | GET | `PIPER /api/easo/pipelines/{id}/snapshots` | Query `{number,pageSize}` | `{code,msg,data:{number,size,totalPages,totalItems,items:[WorkflowSnapshot]}}` | `src/domains/platform/api.ts:194` | 否 | +| P12 | GET | `PIPER /api/easo/pipelines/snapshot/{snapshotId}` | 无 | `{code,msg,data:WorkflowSnapshot}`;`inputs`/`outputs` 为 JSON 字符串 | `src/domains/platform/api.ts:207` | 见 `_tmp-captured` | +| P13 | GET | `PIPER /api/easo/snapshots/{snapshotId}` | 无 | 同 P12;P12 失败后的 fallback | `src/domains/platform/api.ts:208` | 否 | +| P14 | GET | `PIPER /api/easo/pipelines/{pipelineId}/snapshots/{snapshotId}` | 无 | 同 P12;P12/P13 失败后的 fallback | `src/domains/platform/api.ts:209` | 否 | +| P15 | GET | `PIPER /api/easo/pipelines/{id}/log` | Query `{state,number,pageSize,startTime?,endTime?}` | `{code,msg,data:{number,size,totalPages,totalItems,items,jobList,executeCount,successCount,errorCount}}` | `src/domains/platform/api.ts:234` | 否 | +| P16 | PUT | `PIPER /api/easo/pipelines/state/{pipelineId}` | Query `{state:"0"|"1"}` | 2xx 即成功;响应体忽略 | `src/domains/platform/api.ts:253` | legacy | +| P17 | GET | `PIPER /api/easo/jobs/running` | Query `{pipelineId,runType:"DEBUG"|"PROD"}` | `{code,msg,data:WorkflowJob|WorkflowJob[]}` | `src/domains/platform/api.ts:266` | legacy | +| P18 | GET | `PIPER /api/easo/jobs/{jobId}` | 无 | `{code,msg,data:JobDetail}`;Job 字段见 `schemas/workflow-job-execution.schema.json` | `src/domains/platform/api.ts:285` | 见 `_tmp-captured`(CLI 聚合) | +| P19 | GET | `PIPER /api/easo/jobs/{jobId}/execution` | Query `{number,pageSize}` | `{code,msg,data:TaskExecution[]|ExecutionPage}` | `src/domains/platform/api.ts:294` | 见 `_tmp-captured`(CLI 聚合) | +| P20 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level/failed` | 无 | `{code,msg,data:ExecutionPage|TaskExecution[]}` | `src/domains/platform/api.ts:311` | 见 `_tmp-captured`(CLI 聚合) | +| P21 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level` | Query `{parentId,number,pageSize}` | `{code,msg,data:ExecutionPage}` | `src/domains/platform/api.ts:333` | 否 | +| P22 | GET | `PIPER /api/easo/executions/{executionId}/logs` | 无 | `{code,msg,data:ExecutionLog[]|{items:[ExecutionLog]}}` | `src/domains/platform/api.ts:347` | 否 | +| P23 | GET | `PIPER /api/easo/dsl/all` | 无 | `{data:NodeDef[]}` 或 `{data:{action:[],control:[],trigger:[]}}`;NodeDef 见下 | `src/domains/platform/api.ts:363`、`:381` | legacy | +| P24 | GET | `PIPER /api/easo/common/staffs` | Query `{external:"true"|"false"}` | `{code,msg,data:[{id,name,email?,department?}]}` | `src/domains/platform/api.ts:400` | legacy | +| P25 | GET | `PIPER /api/webhook/{pipelineId}` | 无 | `{code,msg,data:{id,pipelineId,url,active}}` | `src/domains/platform/api.ts:412` | legacy | +| P26 | POST | `PIPER /api/easo/pipelines/{id}/sampleData` | 无 body(`sampleWorkflowData`)或 `{type:"webhook"}`(`getWorkflowSampleData`) | 无 body 时:采样对象;带 type 时:`{records:[{id,corporationId?,pipelineId?,taskName?,actived?,dataJson,createTime,updateTime?}],total?,size?,current?}` | `src/domains/platform/api.ts:422`、`:472` | legacy | +| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/api.ts:433` | 否 | +| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:|{id}|{jobId}}` | `src/domains/platform/api.ts:448` | 否 | +| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/api.ts:486` | 否 | +| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/api.ts:511` | 否 | + +`Platform` 代码字段(`src/domains/platform/types.ts:5`): + +```text +id, name, nameSpell, enName?, code, corporationId, active, type, groupType, +platformType, source, adminIds, desc?, importMethod, createTime, updateTime +``` + +`Workflow` 列表项(`types.ts:231`): + +```text +id, pipelineName, state, runningCount, errorCount, updateTime, updateUser?, +tasks[], desc?, customDesc? +``` + +`NodeDef`(`types.ts:467`): + +```text +id?, name, type, groupName?, icon?, iconColor?, remark?, platform?, version?, $json? +``` + +## 3. bill / specifications(5) + +| # | Method | Path | 请求 | 响应 | 来源 | 抓包 | +|---|---|---|---|---|---|---| +| B01 | GET | `EKB /api/form/v2/specifications/[{specificationId}]` | Query `{corpId,_t}`;Headers `cache-control:no-cache`、`pragma:no-cache`;ID 会剥离末尾 `:` | `{items:[Spec]}` 或 `{value:Spec}` 或裸 `Spec`,代码取第一个/第一个值;Spec 见 `schemas/form-specification.schema.json` | `src/domains/bill/api.ts:609` | 见 `_tmp-captured`(响应载荷) | +| B02 | GET | `EKB /api/form/v2/specificationGroups/withSpecificationVersioned` | Query `{corpId,_t}`;Headers no-cache | `{items:[{name,active?,specifications:[{id,originalId?,name,type?,active?}]}]}` 或 `{value:{items:[...]}}` | `src/domains/bill/templates.ts:105` | 见 `_tmp-captured`(请求清单) | +| B03 | GET | `EKB /api/form/v2/specifications/feeType/[{id}]` | Query `{id,corpId}` | `{items:[FeeTypeSpecificationItem]}`;代码取 `items[0]` | `src/domains/feetype/api.ts:112` | 否 | +| B04 | GET | `EKB /api/form/v2/specifications/default/$feeType_expense` | Query `{type:"feeType_expense",corpId}` | `{components:[FeeTypeComponent]}` | `src/domains/feetype/api.ts:141` | 否 | +| B05 | GET | `EKB /api/form/v2/specifications/default/$feeType_requisition` | Query `{type:"feeType_requisition",corpId}` | `{components:[FeeTypeComponent]}` | `src/domains/feetype/api.ts:161` | 否 | + +### 模板组件字段 + +组件使用 `field` 作为 key(`src/domains/bill/types.ts:42`): + +```json +{ + "field": "u_单据编号", + "label": "关联发票核销单号", + "type": "text", + "optional": true, + "maxLength": 140 +} +``` + +`FormSpecificationComponentSchema` 还包含: + +```text +id?, name?, field?, label, type, optional, editable, hidden, isLinkageAssignment, +assignmentRule?, priorityList?/priority?, entityId?/referenceData?, dimensionId? +``` + +## 4. assist-platform(12) + +客户端前缀:`https://unity.ekuaibao.com/api`;Headers `token`、`content-type: application/json;charset=UTF-8`、可选 Cookie `hose-access-token`。 +下表 Path 保留代码字面量。部分 path 以 `api/` 开头,ky 会与前缀直接拼接,实际 URL 以运行时为准。 + +| # | Method | Path | 请求 | 响应 | 来源 | 抓包 | +|---|---|---|---|---|---|---| +| S01 | POST | `ASSIST corporation/search` | `{limit:{start,count},filterBy?}`;filterBy 形如 `(id == "x" \|\| name.containsIgnoreCase("x"))` | `{count,items:[AssistPlatformCorporation]}` | `src/domains/assist-platform/api.ts:54` | 否 | +| S02 | GET | `ASSIST corporation/${corpId}/getCorporationDetail` | 无 | `{items:[CorporationDetail]}` | `src/domains/assist-platform/api.ts:84` | 否 | +| S03 | POST | `ASSIST assistPlatform/${corpId}/search` | `{query:{}}` | `{items:[Ticket]}` | `src/domains/assist-platform/api.ts:115` | 否 | +| S04 | POST | `ASSIST assistPlatform/getStaff` | `{corporationId,name}` | `{total?,items:[Staff]}` | `src/domains/assist-platform/api.ts:172` | 否 | +| S05 | POST | `ASSIST assistPlatform/getToken` | `{ticketId,corporationId,isAdmin,staffId?}` | `{value:{token,loginUrl,baseUrl?}}` | `src/domains/assist-platform/api.ts:233` | 否 | +| S06 | POST | `ASSIST assistPlatform/create` | `{corporationId,applyMessage,assistTime}` | `{value:{id,corporationId,applyMessage,assistTime,userName?,responsibleUserName?,status}}` | `src/domains/assist-platform/api.ts:293` | 否 | +| S07 | PUT | `ASSIST api/assistPlatform/${ticketId}/updateStatus` | Query `{corpId}`;body `{id,status}` | `{value:{id,corporationId,status,active,startTime,endTime,applyMessage,userName?,responsibleUserName?}}` | `src/domains/assist-platform/api.ts:359` | 否 | +| S08 | POST | `ASSIST assistPlatform/transfer` | `{assistId,recipient,remarks}` | `{errorCode?,errorMessage?,value?}` | `src/domains/assist-platform/api.ts:567` | 否 | +| S09 | POST | `ASSIST userRole/search` | `{filterBy:"(active==true)",orderBy:[{value:"createTime",order:"DESC"}],limit:{start:0,count:1000},select:"userId(id, name,code),roleIds(id, name),`...`",permissions:[...]}` | `{items:[{id,userId:{id,name,code?},roleIds:[{id,name}]}]}` | `src/domains/assist-platform/api.ts:507` | 否 | +| S10 | GET | `ASSIST api/v1/organization/staffs/me` | Query `{corpId}` | `{value:{staff:{...},permissions:[string]}}` | `src/domains/assist-platform/api.ts:411` | 否 | +| S11 | GET | `ASSIST api/v1/organization/staffs/${staffId}/roles` | Query `{corpId}` | `{items:[{roleDefId?,roleDefName?,roleDefCode?}]}` | `src/domains/assist-platform/api.ts:440` | 否 | +| S12 | GET | `ASSIST api/v1/organization/departments/${deptId}` | Query `{corpId}` | `{value:{name}}` | `src/domains/assist-platform/api.ts:479` | 否 | + +工单字段兼容:代码同时读 `id/ticketId/authCode`、`applicant/applyUserName/userName`、`principal/operationUserName/responsibleUserName`、`state/status`、`matter/applyMessage`、`duration/hours/assistTime`(`src/domains/assist-platform/api.ts:120`)。 + +## 5. legacy 参考(8,不计入 66) + +以下只存在于 `specs/openapi.raw.json`,当前 `src/` 未调用;字段可能过时,仅供对照。 + +| # | Method | Path | 请求 | 响应 | +|---|---|---|---|---| +| L01 | POST | `EKB /api/common/security/getPublicKey` | 无 | `{value:{publicKey,modulus,exponent}}` | +| L02 | POST | `EKB /api/common/login/verifyPhone` | `{phone,password,countryCode?}` | `{value:{accessToken,user:{id,name,phone}}}` | +| L03 | GET | `EKB /api/common/user/corporations` | 无 | `{items:[CorporationItem]}` | +| L04 | POST | `EKB /api/common/user/corporations/{corpId}/switch` | 路径 `corpId` | `{value:{activeCorpId,staffId}}` | +| L05 | POST | `EKB /api/open/oauth2/auth` | 无 | `{code}` | +| L06 | POST | `EKB /api/open/oauth2/token` | `{code,appKey,appSecret,grant_type}` | `{access_token,refresh_token,expires_in}` | +| L07 | GET | `EKB /api/open/oauth2/user_info` | 无 | `{openId,corpId,name}` | +| L08 | POST | `EKB /api/open/oauth2/token/refresh` | `{refresh_token,grant_type}` | `{access_token,refresh_token,expires_in}` | + +## 6. 代码未覆盖、仅在抓包中出现的接口 + +这些不在 66 个正式代码接口内,原始格式由主智能体放在 `_tmp-captured/`: + +| Method | Path | 说明 | +|---|---|---| +| PUT | `EKB /api/form/v2/specifications/{specificationId}/$false` | 付款单模板保存;组件用 `field=u_单据编号`、`label=关联发票核销单号` | +| POST | `EKB /api/form/v2/specifications/search/all` | 模板搜索 | +| GET | `EKB /api/form/v2/specificationGroups` | 模板分组列表 | +| GET | `EKB /api/form/v2/requisition/expenseLink/{id}` | 关联单据/发票入口 | +| POST | `EKB /api/v1/requisition/autoAssociate/config/list` | 单据自动关联配置 | + +## 7. 未抓包 / 缺失 + +- 66 个代码接口中,只有 P06、P07、P12、P18、P19、P20 和 B01/B02 有本次抓包参考;其余为 code-derived。 +- 新建工作流 `POST /pipelines`、复制 `PUT /copy`、删除 `DELETE`、启停 `PUT /state`、`debugSource`、`sampleData`、`POST /jobs`、`EKL_ENUM` 均无原始抓包。 +- `GET /pipelines/{id}`、`/pipelines/logs`、`/snapshots`、`/log`、`/dsl/all` 等只在 `specs/openapi.raw.json` 有历史抓包,未做 1:1 复核。 +- assist-platform 12 个接口全部无抓包。 +- auth 19 个代码接口全部无抓包;legacy 8 个只有历史参考。 diff --git a/specs/hose-close-api/schemas/form-specification.schema.json b/specs/hose-close-api/schemas/form-specification.schema.json new file mode 100644 index 0000000..afb7020 --- /dev/null +++ b/specs/hose-close-api/schemas/form-specification.schema.json @@ -0,0 +1,136 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hose-use.local/specs/hose-close-api/schemas/form-specification.schema.json", + "title": "Form specification", + "description": "单据模板(specification)对象。以 src/domains/bill/types.ts 的 FormSpecificationSchema 为主,结合 _tmp-captured 中的响应载荷校准。字段 key 统一使用 field。", + "x-source": [ + "code-derived: src/domains/bill/types.ts:42", + "reference: _tmp-captured/raw/GET-api-form-v2-specifications-id-payment.json", + "reference: _tmp-captured/raw/GET-api-form-v2-specifications-id-invoice.json" + ], + "type": "object", + "required": ["id", "name", "type", "components"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string", "description": "模板名称,例如 付款单 / 发票核销单。" }, + "enName": { "type": "string" }, + "type": { "type": "string", "description": "单据类型,例如 expense、requisition。", "examples": ["expense", "requisition"] }, + "active": { "type": "boolean" }, + "systemPreset": { "type": "boolean" }, + "specificationGroupId": { "type": "string" }, + "appId": { "type": "string" }, + "color": { "type": "string" }, + "icon": { "type": "string" }, + "visibility": { "$ref": "#/$defs/Visibility" }, + "state": { "type": "string", "description": "抓包观察值:PUBLISHED。" }, + "configs": { + "type": "array", + "description": "按 ability 区分的模板能力配置。", + "items": { + "type": "object", + "required": ["ability"], + "properties": { "ability": { "type": "string" } }, + "additionalProperties": true + } + }, + "components": { + "type": "array", + "description": "模板字段组件列表。field 是字段 key,不是 key/name。", + "items": { "$ref": "#/$defs/Component" } + }, + "rules": { "type": "array", "items": { "type": "object" } }, + "pri": { "type": "number" }, + "mustUpdateTemplate": { "type": "boolean" }, + "description": { "type": "string" }, + "budgetPermitAllowEdit": { "type": "boolean" }, + "forbidSubmit": { "type": "boolean" }, + "usageMode": { "type": "string" }, + "pipeline": { "type": "number" }, + "grayver": { "type": "string" }, + "dbVersion": { "type": "number" }, + "threadId": { "type": "string" }, + "version": { "type": "number" }, + "createTime": { "type": "number", "description": "毫秒时间戳。" }, + "updateTime": { "type": "number", "description": "毫秒时间戳。" }, + "nameSpell": { "type": "string" }, + "code": { "type": "string" }, + "corporationId": { "type": "string" }, + "sourceCorporationId": { "type": ["string", "null"] }, + "dataCorporationId": { "type": ["string", "null"] }, + "editorId": { "type": "string" }, + "flowPlanConfigId": { "type": ["string", "null"] }, + "warnings": { "type": "array", "items": { "type": "string" } } + }, + "additionalProperties": true, + "$defs": { + "Component": { + "type": "object", + "description": "模板字段组件。示例:{\"field\":\"u_单据编号\",\"label\":\"关联发票核销单号\",\"type\":\"text\",\"optional\":true,\"maxLength\":140}。separator 类型没有 field。", + "required": ["type"], + "properties": { + "field": { "type": "string", "description": "字段 key,例如 u_单据编号、u_所属供应商、title、details。不是 key,也不是 name。" }, + "label": { "type": "string" }, + "cnLabel": { "type": "string" }, + "enLabel": { "type": ["string", "null"] }, + "type": { + "type": "string", + "description": "组件类型。观察值:text、textarea、select、date、money、dataLink、payeeInfo、details、requisitionDetails、separator。", + "examples": ["text", "textarea", "select", "date", "money", "dataLink", "payeeInfo", "details", "requisitionDetails", "separator"] + }, + "optional": { "type": "boolean" }, + "editable": { "type": "boolean" }, + "readonly": { "type": "boolean" }, + "hidden": { "type": "boolean" }, + "hide": { "type": "boolean" }, + "isLinkageAssignment": { "type": "boolean" }, + "assignmentRule": { "type": ["string", "null"] }, + "priority": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { "type": "string" }, + "value": { "type": "number" } + }, + "additionalProperties": true + } + }, + "defaultValue": { "type": "object", "additionalProperties": true }, + "placeholder": { "type": "string" }, + "cnPlaceholder": { "type": ["string", "null"] }, + "enPlaceholder": { "type": ["string", "null"] }, + "maxLength": { "type": "number" }, + "minLength": { "type": "number" }, + "showInDetails": { "type": "boolean" }, + "selectRange": { "type": "string" }, + "multiple": { "type": "boolean" }, + "dependence": { "type": ["object", "null"] }, + "onlyBelongDepartment": { "type": "boolean" }, + "allowExternalStaff": { "type": "boolean" }, + "inheritedFieldDependency": { "type": "boolean" }, + "hideVisibility": { "$ref": "#/$defs/Visibility" }, + "hideBlacklistVisibility": { "$ref": "#/$defs/Visibility" }, + "configs": { "type": "array", "items": { "type": "object" } }, + "referenceData": { "type": "string", "description": "dataLink 引用的业务对象实体 ID。" }, + "filterId": { "type": ["string", "null"] }, + "subTypeId": { "type": ["string", "null"] }, + "isMcFiled": { "type": "boolean" }, + "defaultField": { "type": "boolean" }, + "copyable": { "type": "boolean" }, + "exceedConfigs": { "type": ["object", "null"] } + }, + "additionalProperties": true + }, + "Visibility": { + "type": "object", + "properties": { + "fullVisible": { "type": "boolean" }, + "staffs": { "type": "array", "items": { "type": "string" } }, + "roles": { "type": "array", "items": { "type": "string" } }, + "departments": { "type": "array", "items": { "type": "string" } }, + "departmentsIncludeChildren": { "type": "boolean" } + }, + "additionalProperties": true + } + } +} diff --git a/specs/hose-close-api/schemas/workflow-chooses.schema.json b/specs/hose-close-api/schemas/workflow-chooses.schema.json new file mode 100644 index 0000000..181bc02 --- /dev/null +++ b/specs/hose-close-api/schemas/workflow-chooses.schema.json @@ -0,0 +1,49 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hose-use.local/specs/hose-close-api/schemas/workflow-chooses.schema.json", + "title": "Workflow chooses response", + "description": "PUT /api/easo/pipelines/{id}/chooses 的响应 data。请求无 body;服务端按当前 pipeline 每个任务节点重新生成 choose 选择器树。", + "x-source": [ + "code-derived: src/domains/platform/api.ts:151", + "reference: _tmp-captured/raw/PUT-api-easo-pipelines-id-chooses.json" + ], + "type": "array", + "items": { + "type": "object", + "required": ["key", "label", "choose"], + "properties": { + "key": { "type": "string", "description": "任务节点 name。" }, + "label": { "type": "string", "description": "节点类型显示名。" }, + "displayName": { "type": ["string", "null"] }, + "choose": { "$ref": "#/$defs/ChooseNode" } + }, + "additionalProperties": true + }, + "$defs": { + "ChooseNode": { + "type": "object", + "description": "选择器节点。可以是空对象 {}。", + "properties": { + "tags": { "type": "array", "items": { "type": "string" } }, + "items": { "type": "array", "items": { "$ref": "#/$defs/ChooseItem" } }, + "rawType": { "type": "string" }, + "type": { "type": "string" } + }, + "additionalProperties": true + }, + "ChooseItem": { + "type": "object", + "required": ["label", "code"], + "properties": { + "label": { "type": "string" }, + "code": { "type": "string", "description": "字段路径/表达式,例如 $status、$this、0、E_xxx_name、yyyy-MM-dd。" }, + "rawType": { "type": "string" }, + "type": { "type": "string" }, + "thirdId": { "type": "string" }, + "extra": { "type": "string" }, + "subChoose": { "$ref": "#/$defs/ChooseNode" } + }, + "additionalProperties": true + } + } +} diff --git a/specs/hose-close-api/schemas/workflow-detail.schema.json b/specs/hose-close-api/schemas/workflow-detail.schema.json new file mode 100644 index 0000000..8b5cea4 --- /dev/null +++ b/specs/hose-close-api/schemas/workflow-detail.schema.json @@ -0,0 +1,104 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hose-use.local/specs/hose-close-api/schemas/workflow-detail.schema.json", + "title": "Workflow detail (EASO/Piper pipeline)", + "description": "工作流详情。GET /api/easo/pipelines/{id} 与 PUT /api/easo/pipelines/{id} 使用。PUT 请求体带 inputs,抓包中的响应 data 不返回 inputs。", + "x-source": [ + "code-derived: src/domains/platform/types.ts:273 (WorkflowDetailSchema)", + "reference: _tmp-captured/raw/PUT-api-easo-pipelines-id.json" + ], + "type": "object", + "required": ["id", "tasks"], + "properties": { + "id": { "type": "string" }, + "label": { "type": "string", "description": "工作流名称。" }, + "desc": { "type": ["string", "null"] }, + "customDesc": { "type": ["string", "null"] }, + "state": { "type": "number", "description": "0 停用,1 启用。" }, + "debugState": { "type": "number" }, + "runTimes": { "type": "number" }, + "errorTimes": { "type": "number" }, + "staffName": { "type": ["string", "null"] }, + "updateTime": { "type": "string" }, + "updateUser": { "type": ["string", "null"] }, + "dataLimit": { "type": "number" }, + "version": { "type": "string", "description": "产品版本号,例如 26.10.1。" }, + "source": { "type": "number" }, + "queueJobs": { "type": "boolean" }, + "tasksVersion": { "type": "number", "description": "任务版本号,保存节点时递增。" }, + "platformId": { "type": "string", "description": "copy 等场景可能出现。" }, + "tasks": { "type": "array", "items": { "$ref": "#/$defs/Task" } }, + "alarm": { + "oneOf": [ + { "$ref": "#/$defs/Alarm" }, + { "type": "string", "description": "Zod 兼容 JSON 字符串。" }, + { "type": "null" } + ] + }, + "inputs": { + "type": "array", + "description": "PUT 请求体中出现,例如 [{key:'$platformId',value:''}]。", + "items": { "$ref": "#/$defs/KeyValue" } + }, + "$snapshot": { + "type": "array", + "description": "文本/表达式内嵌选择器快照补丁,value 是 JSON 字符串。", + "items": { + "type": "object", + "required": ["key", "value"], + "properties": { + "key": { "type": "string" }, + "value": { "type": "string" } + }, + "additionalProperties": true + } + } + }, + "additionalProperties": true, + "$defs": { + "KeyValue": { + "type": "object", + "required": ["key"], + "properties": { + "key": { "type": "string" }, + "value": {} + }, + "additionalProperties": true + }, + "Alarm": { + "type": "object", + "properties": { + "alarmUser": { "type": "array", "items": {} }, + "alarmType": { "type": "array", "items": { "type": "string" } }, + "active": { "type": "boolean" }, + "alarmScope": { "type": "string" } + }, + "additionalProperties": true + }, + "Task": { + "type": "object", + "description": "递归任务节点。未列出的类型专属字段按 additionalProperties 保留。", + "required": ["name", "type", "label", "groupName", "orderIndex", "levelIndex", "status"], + "properties": { + "name": { "type": "string", "description": "节点唯一名,例如 trigger_1、action_rv232l。" }, + "type": { + "type": "string", + "description": "节点类型。代码覆盖:clock、condition、every、stop、http、flow-detail、code、code-js2、ekuaibao-datalink-filter、ekuaibao-datalink-create、data-convert、flow-create-task、task-dynamic-delay、webhook 等。" + }, + "label": { "type": "string" }, + "displayName": { "type": "string" }, + "desc": { "type": ["string", "null"] }, + "groupName": { "type": "string", "description": "trigger / action / control。" }, + "orderIndex": { "type": "number" }, + "levelIndex": { "type": "array", "items": { "type": "number" } }, + "status": { "type": "string" }, + "tasks": { + "type": "array", + "description": "condition/every 等控制节点的子节点。", + "items": { "$ref": "#/$defs/Task" } + } + }, + "additionalProperties": true + } + } +} diff --git a/specs/hose-close-api/schemas/workflow-job-execution.schema.json b/specs/hose-close-api/schemas/workflow-job-execution.schema.json new file mode 100644 index 0000000..0c46ab0 --- /dev/null +++ b/specs/hose-close-api/schemas/workflow-job-execution.schema.json @@ -0,0 +1,116 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hose-use.local/specs/hose-close-api/schemas/workflow-job-execution.schema.json", + "title": "Workflow job execution", + "description": "Piper 任务实例与节点执行数据。/execution 与 /execution/level/failed 的 data 可能是数组,也可能是分页对象 {number,size,totalPages,totalItems,items}。", + "x-source": [ + "code-derived: src/domains/platform/types.ts:360", + "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution.json", + "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution-completed.json" + ], + "type": "object", + "properties": { + "job": { "$ref": "#/$defs/Job" }, + "executionTree": { "type": "array", "items": { "$ref": "#/$defs/TaskExecution" } }, + "failedExecutions": { "type": "array", "items": { "$ref": "#/$defs/TaskExecution" } }, + "workflow": { "type": "object", "additionalProperties": true }, + "conditionDiagnoses": { "type": "array", "items": { "type": "object", "additionalProperties": true } }, + "timeline": { "type": "array", "items": { "type": "object", "additionalProperties": true } } + }, + "additionalProperties": true, + "$defs": { + "Job": { + "type": "object", + "required": ["id", "pipelineId", "status"], + "properties": { + "id": { "type": "string" }, + "pipelineId": { "type": "string" }, + "label": { "type": "string" }, + "status": { "type": "string", "description": "例如 FAILED、COMPLETED。" }, + "runType": { "type": "string", "description": "DEBUG / PROD。" }, + "startTime": { "type": ["number", "string", "null"] }, + "endTime": { "type": ["number", "string", "null"] }, + "createTime": { "type": ["number", "string", "null"] }, + "inputs": { "type": "object", "additionalProperties": true }, + "outputs": { "type": "object", "additionalProperties": true }, + "corporationId": { "type": "string" }, + "currentTask": { "type": "number" }, + "priority": { "type": "number" }, + "webhooks": { "type": "array", "items": {} }, + "parentTaskExecutionId": { "type": ["string", "null"] }, + "isQueuedJob": { "type": "boolean" }, + "initialQueuedJobsAhead": { "type": "number" } + }, + "additionalProperties": true + }, + "TaskExecution": { + "type": "object", + "description": "单个节点的一次执行。不同节点类型会带各自配置字段,未列出字段按 additionalProperties 保留。", + "required": ["id", "jobId", "pipelineId", "name", "type", "status"], + "properties": { + "id": { "type": "string" }, + "parentId": { "type": ["string", "null"] }, + "jobId": { "type": "string" }, + "pipelineId": { "type": "string" }, + "name": { "type": "string" }, + "displayName": { "type": ["string", "null"] }, + "label": { "type": ["string", "null"] }, + "type": { "type": "string" }, + "orderIndex": { "type": "number" }, + "levelIndex": { "type": "array", "items": { "type": "number" } }, + "status": { "type": "string" }, + "executionTime": { "type": "number" }, + "startTime": { "type": ["number", "string", "null"] }, + "endTime": { "type": ["number", "string", "null"] }, + "createTime": { "type": ["number", "string", "null"] }, + "currentLoopPath": { "type": ["string", "null"] }, + "output": { "type": ["object", "array", "string", "number", "boolean", "null"] }, + "error": { "$ref": "#/$defs/ExecutionError" }, + "form": { "type": ["object", "array", "null"] }, + "details": { "type": ["object", "null"] }, + "executionLogs": { "type": "array", "items": {} } + }, + "additionalProperties": true + }, + "ExecutionError": { + "type": "object", + "required": ["message", "stackTrace"], + "properties": { + "message": { "type": "string" }, + "stackTrace": { "type": "array", "items": { "type": "string" } } + }, + "additionalProperties": true + }, + "ExecutionPage": { + "type": "object", + "required": ["items"], + "properties": { + "number": { "type": "number" }, + "size": { "type": "number" }, + "totalPages": { "type": "number" }, + "totalItems": { "type": "number" }, + "items": { + "type": "array", + "items": { + "oneOf": [ + { "$ref": "#/$defs/TaskExecution" }, + { "type": "array", "items": { "$ref": "#/$defs/TaskExecution" } } + ] + } + } + }, + "additionalProperties": true + }, + "ExecutionLog": { + "type": "object", + "required": ["message"], + "properties": { + "id": { "type": ["string", "number"] }, + "level": { "type": "string" }, + "message": { "type": "string" }, + "createAt": { "type": ["string", "number"] } + }, + "additionalProperties": true + } + } +} diff --git a/specs/hose-close-api/schemas/workflow-snapshot.schema.json b/specs/hose-close-api/schemas/workflow-snapshot.schema.json new file mode 100644 index 0000000..0301817 --- /dev/null +++ b/specs/hose-close-api/schemas/workflow-snapshot.schema.json @@ -0,0 +1,46 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hose-use.local/specs/hose-close-api/schemas/workflow-snapshot.schema.json", + "title": "Workflow snapshot", + "description": "工作流快照。前端使用 GET /api/easo/pipelines/snapshot/{snapshotId};代码还兼容 /api/easo/snapshots/{id} 与 /api/easo/pipelines/{pipelineId}/snapshots/{id}。", + "x-source": [ + "code-derived: src/domains/platform/types.ts:307 (WorkflowSnapshotSchema)", + "reference: _tmp-captured/raw/GET-api-easo-pipelines-snapshot-id.json" + ], + "type": "object", + "required": ["id", "pipelineId"], + "properties": { + "id": { "type": "string" }, + "pipelineId": { "type": "string" }, + "corporationId": { "type": "string" }, + "platformId": { "type": "string" }, + "triggerKey": { "type": "string", "description": "触发类型,例如 clock。" }, + "label": { "type": "string" }, + "tasks": { + "type": ["array", "null"], + "description": "快照时刻的任务节点树,结构同 WorkflowDetail.tasks。", + "items": { "type": "object", "additionalProperties": true } + }, + "inputs": { + "oneOf": [ + { "type": "string", "description": "JSON 编码字符串。" }, + { "type": "array", "items": {} } + ] + }, + "outputs": { + "oneOf": [ + { "type": "string", "description": "JSON 编码字符串。" }, + { "type": "array", "items": {} } + ] + }, + "retry": { "type": "number" }, + "state": { "type": "number" }, + "debugState": { "type": "number" }, + "staffId": { "type": ["string", "null"] }, + "staffName": { "type": ["string", "null"] }, + "createTime": { "type": "string" }, + "updateTime": { "type": "string" }, + "version": { "type": "string" } + }, + "additionalProperties": true +} diff --git a/src/cli/README.cli.md b/src/cli/README.cli.md index 81323c6..2345481 100644 --- a/src/cli/README.cli.md +++ b/src/cli/README.cli.md @@ -11,6 +11,7 @@ - `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。 完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。 - `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。 + 带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。 - `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。 - `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。 - `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。 @@ -35,3 +36,5 @@ `hose-use mcp [serve]` 在当前进程启动服务,不派生 Bun 或访问源码脚本;MCP 调用继续只通过 `hose_cli` 分发,流式终端回调不会被注入协议通道。 `update --dry-run` 返回源码或二进制更新计划,不请求发布源、不执行 git/依赖安装、不替换二进制或同步技能;`update check` 和发布历史查询保留只读查询行为。 + +`corps whoami --corp=` 只在线核验指定企业,不再遍历全部本地名录;不带 `--corp` 时保留全企业视图,`--offline` 仍不发起网络请求。 diff --git a/src/cli/architecture-boundaries.test.ts b/src/cli/architecture-boundaries.test.ts index 75a99e2..091682e 100644 --- a/src/cli/architecture-boundaries.test.ts +++ b/src/cli/architecture-boundaries.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { readdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join, relative, resolve } from "node:path"; +import ts from "typescript"; const SRC_ROOT = join(import.meta.dir, ".."); @@ -20,25 +21,59 @@ function collectTsFiles(dir: string, includeTests = false): string[] { function extractImportSpecifiers(source: string): string[] { const specifiers: string[] = []; - const staticImportRe = /(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g; - const dynamicImportRe = /import\(\s*["']([^"']+)["']\s*\)/g; - - for (const match of source.matchAll(staticImportRe)) { - if (match[1]) specifiers.push(match[1]); - } - for (const match of source.matchAll(dynamicImportRe)) { - if (match[1]) specifiers.push(match[1]); - } + const ast = ts.createSourceFile("boundary.ts", source, ts.ScriptTarget.Latest, true); + const visit = (node: ts.Node) => { + if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text); + if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) specifiers.push(node.arguments[0].text); + if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) specifiers.push(node.argument.literal.text); + ts.forEachChild(node, visit); + }; + visit(ast); return specifiers; } function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null { - if (!specifier.startsWith(".")) return null; - const abs = resolve(dirname(fromFile), specifier).replace(/\.[jt]s$/, ""); - return relative(SRC_ROOT, abs); + const path = specifier.startsWith(".") ? resolve(dirname(fromFile), specifier) + : specifier.startsWith("@core/") ? join(SRC_ROOT, "core", specifier.slice(6)) + : specifier.startsWith("@domains/") ? join(SRC_ROOT, "domains", specifier.slice(9)) : undefined; + return path ? relative(SRC_ROOT, path.replace(/\.[jt]s$/, "")).replaceAll("\\", "/") : null; } describe("Architecture Layering Boundaries", () => { + test("dependency extraction covers aliases, re-exports and literal dynamic/type imports", () => { + const imports = extractImportSpecifiers(` + import { x } from "@core/errors.js"; + export { y } from "@domains/bill/api.js"; + const z = import("../domains/bill/api.js"); + type T = import("@domains/bill/types.js").FormSpecification; + const text = 'import("not-a-real-import")'; + `); + expect(imports).toEqual(["@core/errors.js", "@domains/bill/api.js", "../domains/bill/api.js", "@domains/bill/types.js"]); + expect(resolveImportRelativeToSrc(join(SRC_ROOT, "cli", "example.ts"), imports[1])).toBe("domains/bill/api"); + }); + + test("bill Session HTTP calls stay in the transport module", () => { + const violations: string[] = []; + for (const file of collectTsFiles(join(SRC_ROOT, "domains", "bill"))) { + if (file.endsWith("api.ts")) continue; + const source = readFileSync(file, "utf8"); + const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true); + const visit = (node: ts.Node) => { + if (ts.isCallExpression(node)) { + const expr = node.expression; + const receiver = ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr) ? expr.expression.getText(ast) : ""; + const method = ts.isPropertyAccessExpression(expr) ? expr.name.text + : ts.isElementAccessExpression(expr) && ts.isStringLiteral(expr.argumentExpression) ? expr.argumentExpression.text : ""; + if (/client|^ky$/i.test(receiver) && ["get", "post", "put", "patch", "delete"].includes(method)) { + violations.push(`${relative(SRC_ROOT, file)}:${ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1}`); + } + } + ts.forEachChild(node, visit); + }; + visit(ast); + } + expect(violations).toEqual([]); + }); test("workflow imports use the module directories after the platform migration", () => { const legacy = /domains\/platform\/(?:analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$/; const violations: string[] = []; diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index aef52bc..f416d74 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -214,6 +214,7 @@ export const COMMAND_METADATA: Record = { "save": "保存草稿到远端", "toggle": "切换启停状态", "publish": "发布并启用工作流", + "refresh-chooses": "只刷新工作流选择器元数据,用于主保存后的失败恢复", "history": "查看版本历史", "logs": "查看运行日志", "check": "检查错误管道", @@ -831,7 +832,7 @@ export const COMMAND_METADATA: Record = { "forward": "transfer" }, flags: { - ...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"), + ...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"), ...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean") } } diff --git a/src/cli/commands/assist-platform.test.ts b/src/cli/commands/assist-platform.test.ts index d888380..03c9df0 100644 --- a/src/cli/commands/assist-platform.test.ts +++ b/src/cli/commands/assist-platform.test.ts @@ -1,8 +1,9 @@ -import { describe, expect, it, beforeEach } from "bun:test"; +import { describe, expect, it, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleAssistPlatformCommand } from "./assist-platform/index.js"; +import { parseArgs } from "../parser.js"; import { saveAssistPlatformSession, clearAssistPlatformSession, @@ -28,14 +29,33 @@ function createMockRuntime(enterprisesDir: string): CliRuntime { } describe("CLI Commands - assist-platform (合思协助平台)", () => { + it("enter 的 staff-id 通过完整解析并选择员工模式预览", async () => { + const parsed = parseArgs(["assist-platform", "enter", "corp", "--staff-id", "staff-two", "--dry-run", "--json"]); + const result = await handleAssistPlatformCommand(parsed, { jsonMode: true } as CliRuntime); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).changes).toMatchObject({ staffId: "staff-two", isAdmin: false }); + }); + + it("enter 不允许管理员模式覆盖显式员工 ID", async () => { + const parsed = parseArgs(["assist-platform", "enter", "corp", "--staff-id", "staff-two", "--admin", "--dry-run"]); + await expect(handleAssistPlatformCommand(parsed, {} as CliRuntime)).rejects.toThrow("不能与"); + }); let tempDir: string; + let previousStateDir: string | undefined; beforeEach(() => { + previousStateDir = process.env.HOSE_STATE_DIR; tempDir = mkdtempSync(join(tmpdir(), "hose-assist-test-")); process.env.HOSE_STATE_DIR = tempDir; clearAssistPlatformSession(); }); + afterEach(() => { + if (previousStateDir === undefined) delete process.env.HOSE_STATE_DIR; + else process.env.HOSE_STATE_DIR = previousStateDir; + rmSync(tempDir, { recursive: true, force: true }); + }); + it("assist-platform help 输出完整使用指南与子命令", async () => { const runtime = createMockRuntime(tempDir); const parsed: CliParsedArgs = { diff --git a/src/cli/commands/assist-platform/enter.ts b/src/cli/commands/assist-platform/enter.ts index 435d53b..83ac96c 100644 --- a/src/cli/commands/assist-platform/enter.ts +++ b/src/cli/commands/assist-platform/enter.ts @@ -60,16 +60,18 @@ export async function handleEnter( if (!corpId) { return { stdout: "", - stderr: "用法: hose-use assist-platform enter <企业ID> [--admin] [--staff <姓名>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n", + stderr: "用法: hose-use assist-platform enter <企业ID> [--admin | --staff <姓名> | --staff-id ] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n", exitCode: 1, }; } const ticketId = stringOption(parsed.options, ["ticket", "ticket-id", "auth-code"]); const staffName = stringOption(parsed.options, ["staff", "user", "name"]); + const staffId = stringOption(parsed.options, ["staff-id", "staffId"]); const forceAdmin = booleanOption(parsed.options, ["admin"]); - // 如果显式指定了 staffName 且未显式指定 --admin,则为用户模式;否则默认为管理员模式 - const isAdmin = forceAdmin || !staffName; + if (forceAdmin && (staffName || staffId)) throw new BusinessError("--admin 不能与 --staff / --staff-id 同时使用"); + // 如果显式指定了 staffName/staffId 且未显式指定 --admin,则为用户模式;否则默认为管理员模式 + const isAdmin = forceAdmin || !(staffName || staffId); const shouldSave = booleanOption(parsed.options, ["save", "import", "persist"]); const shouldSwitch = booleanOption(parsed.options, ["switch", "current"]); @@ -88,6 +90,7 @@ export async function handleEnter( corpId, isAdmin, staffName: staffName || null, + staffId: staffId || null, ticketId: ticketId || "自动选择最新有效工单", save: shouldSave || shouldSwitch, switchCurrent: shouldSwitch, @@ -105,6 +108,7 @@ export async function handleEnter( ticketId, isAdmin, staffName, + staffId, }); if (runtime.jsonMode) { @@ -133,14 +137,14 @@ export async function handleEnter( `====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` + `${warningText}\n操作提示:\n` + ` - 在浏览器中打开以上链接可直接进入协助调试工作台\n` + - ` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`, + ` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff-id "${sessionRes.staffId}"`} --save --yes\n`, stderr: "", exitCode: 0, }; } // 2. 要求持久化落盘 / 切换为工作企业 - const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`; + const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : staffId ? `--staff-id "${staffId}"` : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`; requireMutationConfirmation( parsed, runtime, @@ -153,6 +157,7 @@ export async function handleEnter( ticketId, isAdmin, staffName, + staffId, saveName, overwrite: overwrite ?? true, }); diff --git a/src/cli/commands/assist-platform/index.ts b/src/cli/commands/assist-platform/index.ts index 052b71d..9a6e240 100644 --- a/src/cli/commands/assist-platform/index.ts +++ b/src/cli/commands/assist-platform/index.ts @@ -96,6 +96,7 @@ function printHelp(): CliResult { --token, -t 显式指定当前操作使用的协助平台 Token --admin 指定使用企业管理员模式换取免密链接(默认) --staff <员工姓名> 指定使用特定员工身份换取免密链接 + --staff-id <员工ID> 显式指定唯一员工,避免同名歧义 --save 一键将换取的免密会话持久化落盘至本地企业列表(自动提取 OpenAPI 密钥) --switch 配合 --save,导入后自动切换为当前激活工作企业 --json 输出结构化 JSON 格式结果 diff --git a/src/cli/commands/bill/create.test.ts b/src/cli/commands/bill/create.test.ts index 8292f0a..ce448ce 100644 --- a/src/cli/commands/bill/create.test.ts +++ b/src/cli/commands/bill/create.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import { handleCreate } from "./create.js"; import { parseArgs } from "../../parser.js"; +import { cliErrorResult } from "../../runner.js"; test("create dry-run resolves the same available fee as execution and never posts", async () => { const writes: any[] = []; @@ -21,3 +22,17 @@ test("create dry-run resolves the same available fee as execution and never post await expect(handleCreate(context([...base, "--fee-type", "不存在", "--dry-run"]))).rejects.toThrow("费用类型"); expect(writes).toHaveLength(1); }); + +test("创建收到业务错误时由 CLI 错误边界返回非零,不输出创建成功", async () => { + const client = { + get: (url: string) => ({ json: async () => url.includes("specifications/") + ? { items: [{ id: "spec", name: "模板", components: [{ field: "title" }] }] } + : url.includes("staffs/me") ? { value: { staff: { id: "staff", defaultDepartment: "dept" } } } + : { items: [{ id: "fee", name: "费用", expenseSpecificationId: "detail" }] } }), + post: () => ({ json: async () => ({ errorCode: "REJECTED", errorMessage: "服务端拒绝创建" }) }), + }; + const context = { parsed: parseArgs(["bill", "create", "--template", `spec:${"a".repeat(32)}`, "--yes", "--json"]), runtime: { jsonMode: true }, corpId: "corp", getClient: async () => client, requireWriteConfirmation: async () => {} } as any; + const result = await handleCreate(context).catch(error => cliErrorResult(error, true)); + expect(result.exitCode).not.toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ error: true, message: "服务端拒绝创建" }); +}); diff --git a/src/cli/commands/corps/whoami-scope.test.ts b/src/cli/commands/corps/whoami-scope.test.ts new file mode 100644 index 0000000..5a5cb5c --- /dev/null +++ b/src/cli/commands/corps/whoami-scope.test.ts @@ -0,0 +1,54 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { handleWhoami } from "./whoami.js"; +import { saveCorpConfig } from "../../../core/config/loader.js"; +import { CorpConfigSchema } from "../../../core/config/types.js"; +import { CorpContext } from "../../../core/config/manager.js"; +import { parseArgs } from "../../parser.js"; +import type { CliRuntime } from "../../types.js"; + +const originalFetch = globalThis.fetch; +const originalEnv = { ...process.env }; +const directories: string[] = []; +afterEach(() => { + globalThis.fetch = originalFetch; + process.env = { ...originalEnv }; + for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "hose-whoami-scope-")); + directories.push(dir); + process.env.HOSE_ENTERPRISES_DIR = dir; + process.env.HOSE_USER_ENTERPRISES_DIR = dir; + process.env.HOSE_CONFIG_FILE = join(dir, "config.json"); + const corps = ["one", "two"].map(id => CorpConfigSchema.parse({ id, name: id, source: "manual", baseUrl: "https://tenant.invalid", credentials: { accessToken: "fake", corpId: id, staffId: `staff-${id}` } })); + for (const corp of corps) saveCorpConfig(corp, dir); + const requests: string[] = []; + globalThis.fetch = (async (input: Request) => { + requests.push(new URL(input.url).searchParams.get("corpId")!); + return Response.json({ value: { staff: { name: "Test Staff" } } }); + }) as unknown as typeof fetch; + const runtime: CliRuntime = { corpContext: new CorpContext(corps, { stateful: false }), selectedCorp: corps[0]!, jsonMode: true }; + return { runtime, requests }; +} + +test("显式企业只查询该企业;不带企业时保留全企业身份查看", async () => { + const f = fixture(); + const selected = await handleWhoami(parseArgs(["corps", "whoami", "--corp=one", "--json"]), f.runtime); + expect(f.requests).toEqual(["one"]); + expect(JSON.parse(selected.stdout).corporations.map((c: { id: string }) => c.id)).toEqual(["one"]); + f.requests.length = 0; + await handleWhoami(parseArgs(["corps", "whoami", "--json"]), f.runtime); + expect(f.requests.sort()).toEqual(["one", "two"]); +}); + +test("无效企业不退回全量查询;离线模式不请求网络", async () => { + const f = fixture(); + await expect(handleWhoami(parseArgs(["corps", "whoami", "--corp=missing"]), { ...f.runtime, selectedCorp: null })).rejects.toThrow("未找到企业"); + const result = await handleWhoami(parseArgs(["corps", "whoami", "--corp=one", "--offline", "--json"]), f.runtime); + expect(JSON.parse(result.stdout).corporations).toHaveLength(1); + expect(f.requests).toEqual([]); +}); diff --git a/src/cli/commands/corps/whoami.ts b/src/cli/commands/corps/whoami.ts index 97ef44e..67244cb 100644 --- a/src/cli/commands/corps/whoami.ts +++ b/src/cli/commands/corps/whoami.ts @@ -1,6 +1,7 @@ import { loadCorpConfigs } from "../../../core/config/loader.js"; import { createSessionClient } from "../../../core/http/session-client.js"; -import { booleanOption } from "../../parser.js"; +import { booleanOption, stringOption } from "../../parser.js"; +import { NotFoundError } from "../../../core/errors.js"; import { formatSourceLabel, printJson, printTable } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; @@ -46,7 +47,10 @@ async function mapLimit(items: T[], limit: number, fn: (item: T) => Promis export async function handleWhoami(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const offline = booleanOption(parsed.options, ["offline", "cached"]); - const corps = runtime.corpContext.listCorps(); + const allCorps = runtime.corpContext.listCorps(); + const explicitCorp = stringOption(parsed.options, ["corp"]); + if (explicitCorp && !runtime.selectedCorp) throw new NotFoundError(`未找到企业: ${explicitCorp}`); + const corps = explicitCorp ? allCorps.filter((corp) => corp.id === runtime.selectedCorp!.id) : allCorps; const configs = new Map(); for (const config of loadCorpConfigs()) { configs.set(config.id, config); diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 0ac5616..9ca205d 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1523,7 +1523,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { }, put: (url: string, opts: any) => { if (url.endsWith("/chooses")) { - return { json: async () => ({ code: 200, data: [] }) }; + return Response.json({ code: 200, data: [] }); } if (url.includes("api/easo/pipelines/pipe_node_test")) { savedWorkflowPayload = opts.json; diff --git a/src/cli/commands/workflow/draft.ts b/src/cli/commands/workflow/draft.ts index 157b579..c0a5614 100644 --- a/src/cli/commands/workflow/draft.ts +++ b/src/cli/commands/workflow/draft.ts @@ -1,5 +1,7 @@ import { readFileSync, writeFileSync } from "node:fs"; -import { getWorkflowDetail, listAllWorkflows, updateWorkflow } from "../../../domains/platform/services.js"; +import { EkbError } from "../../../core/errors.js"; +import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/services.js"; +import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js"; import { WorkflowDetailSchema } from "../../../domains/platform/types.js"; import { applyWorkflowPathPatch, @@ -137,8 +139,14 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr const payload = state.workflow.inputs?.length ? state.workflow : { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] }; - const saved = await updateWorkflow(piperClient, payload); + let partialError: WorkflowSavePartialError | undefined; + const saved = await updateWorkflow(piperClient, payload).catch((error: unknown) => { + if (!(error instanceof WorkflowSavePartialError)) throw error; + partialError = error; + return error.savedWorkflow; + }); state = commitWorkflowSave(state, saved); + if (partialError) state = { ...state, status: "partial", error: partialError.message }; let fileSynced = false; let fileSyncWarning = ""; if (syncFile) { @@ -155,8 +163,11 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`; } } + const quoteArg = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; + const nextAction = `hose-use workflow refresh-chooses ${quoteArg(pipelineId)} --platform-id=${quoteArg(platformId)} --corp=${quoteArg(runtime.selectedCorp!.id)} --yes`; const result = { - success: true, + success: !partialError, + ...(partialError ? { remoteSaved: true, failedStep: "chooses", nextAction, message: partialError.message } : {}), pipelineId, status: state.status, version: saved.version, @@ -165,7 +176,12 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr fileSynced, ...(fileSyncWarning ? { fileSyncWarning } : {}), }; - if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: 0 }; + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: partialError ? 1 : 0 }; + if (partialError) return { + stdout: `⚠️ ${partialError.message}\n${fileSynced ? "已同步本地文件版本。\n" : ""}恢复命令: ${nextAction}\n`, + stderr: fileSyncWarning, + exitCode: 1, + }; return { stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`, stderr: fileSyncWarning, @@ -173,10 +189,23 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr }; } catch (error) { state = failWorkflowSave(state, error); + if (error instanceof EkbError) throw error; throw new Error(`工作流保存失败(${state.status}): ${state.error}`); } } +export async function handleRefreshChooses(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); + if (!pipelineId) throw new Error("请提供工作流 ID: hose-use workflow refresh-chooses --yes"); + requireMutationConfirmation(parsed, runtime, "刷新工作流元数据", `hose-use workflow refresh-chooses ${pipelineId} --yes`); + if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "刷新工作流元数据", pipelineId, { retryStep: "chooses", saveWorkflow: false }); + const clients = await createClientsForCorp(runtime.selectedCorp!); + const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId); + const client = await createPiperClientForCorp(runtime.selectedCorp!, platformId); + await refreshWorkflowChooses(client, pipelineId); + return { stdout: runtime.jsonMode ? printJson({ success: true, pipelineId, metadataRefreshed: true }, runtime.outputOptions) : `工作流 [${pipelineId}] 元数据刷新成功,未重新提交快照。\n`, stderr: "", exitCode: 0 }; +} + async function resolveWorkflowPlatformId( parsed: CliParsedArgs, clients: Awaited>, diff --git a/src/cli/commands/workflow/index.ts b/src/cli/commands/workflow/index.ts index 04e1ff8..5956d5d 100644 --- a/src/cli/commands/workflow/index.ts +++ b/src/cli/commands/workflow/index.ts @@ -1,7 +1,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { handleList, handleGet, handleFind } from "./list.js"; import { handleToggle, handlePublish } from "./lifecycle.js"; -import { handlePatch, handleSave } from "./draft.js"; +import { handlePatch, handleSave, handleRefreshChooses } from "./draft.js"; import { handleHistory, handleLogs } from "./history.js"; import { handleJob } from "./job.js"; import { handleCheck } from "./check.js"; @@ -52,6 +52,8 @@ export async function handleWorkflowCommand( case "save": case "update": return handleSave(parsed, runtime); + case "refresh-chooses": + return handleRefreshChooses(parsed, runtime); case "patch": return handlePatch(parsed, runtime); case "history": @@ -122,7 +124,7 @@ export async function handleWorkflowCommand( default: return { stdout: "", - stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`, + stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`, exitCode: 1, }; } diff --git a/src/cli/commands/workflow/save-partial.test.ts b/src/cli/commands/workflow/save-partial.test.ts new file mode 100644 index 0000000..77fe256 --- /dev/null +++ b/src/cli/commands/workflow/save-partial.test.ts @@ -0,0 +1,77 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import ky from "ky"; +import * as helpers from "../../helpers.js"; +import { parseArgs } from "../../parser.js"; +import { cliErrorResult } from "../../runner.js"; +import { normalizeCliArgs, tokenizeCommand } from "../../../server.js"; +import { handleWorkflowCommand } from "./index.js"; +import { WorkflowDetailSchema } from "../../../domains/platform/types.js"; +import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js"; +import type { CliRuntime } from "../../types.js"; + +const spies: Array<{ mockRestore(): void }> = []; +const directories: string[] = []; +afterEach(() => { + for (const spy of spies.splice(0)) spy.mockRestore(); + for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture(mainFails = false) { + const dir = mkdtempSync(join(tmpdir(), "hose-save-partial-")); + directories.push(dir); + const file = join(dir, "workflow.json"); + const workflow = WorkflowDetailSchema.parse({ id: "p", label: "本地名称", version: "v1", tasksVersion: 1, localNote: "keep" }); + writeFileSync(file, JSON.stringify(workflow)); + const requests: Array<{ method: string; path: string }> = []; + let failRefresh = true; + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async (input, init) => { + const req = input instanceof Request ? input : new Request(input.toString(), init); + const path = new URL(req.url).pathname; + requests.push({ method: req.method, path }); + if (req.method === "GET") return Response.json({ code: 200, data: workflow }); + if (path.endsWith("/chooses")) return Response.json(failRefresh ? { code: 500, msg: "刷新失败" } : { code: 200, data: [] }); + return Response.json(mainFails ? { code: 500, msg: "保存失败" } : { code: 200, data: { ...workflow, label: "远端名称", version: "v2", tasksVersion: 2 } }); + } }); + const corp = { id: "corp", name: "测试企业", baseUrl: "https://tenant.invalid", source: "manual", credentials: { corpId: "corp", staffId: "staff", accessToken: "fake" } } as const; + const runtime = { selectedCorp: corp, corpContext: {}, jsonMode: true } as CliRuntime; + spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ corp, sessionClient: client, ekbClient: client, unityClient: client, easoClient: client })); + spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(client)); + return { file, workflow, runtime, requests, restoreRefresh: () => { failRefresh = false; } }; +} + +test("部分保存返回非零与新版本,同步本地版本后可只重试 chooses", async () => { + const f = fixture(); + const result = await handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes", "--json"]), f.runtime); + expect(result.exitCode).toBe(1); + const partial = JSON.parse(result.stdout); + expect(partial).toMatchObject({ success: false, remoteSaved: true, failedStep: "chooses", status: "partial", version: "v2", tasksVersion: 2, fileSynced: true }); + expect(JSON.parse(readFileSync(f.file, "utf8"))).toMatchObject({ label: "本地名称", localNote: "keep", version: "v2", tasksVersion: 2 }); + f.restoreRefresh(); + const retry = await handleWorkflowCommand(parseArgs(normalizeCliArgs(tokenizeCommand(partial.nextAction))), f.runtime); + expect(retry.exitCode).toBe(0); + expect(f.requests.filter(r => r.method === "PUT").map(r => r.path)).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]); +}); + +test("主保存失败不更新本地版本,也不发送 chooses", async () => { + const f = fixture(true); + await expect(handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes"]), f.runtime)).rejects.toThrow("保存失败"); + expect(JSON.parse(readFileSync(f.file, "utf8")).tasksVersion).toBe(1); + expect(f.requests.some(r => r.path.endsWith("/chooses"))).toBe(false); +}); + +test("定向刷新支持无网络预演,且仍要求写确认", async () => { + const f = fixture(); + const preview = await handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p", "--dry-run", "--json"]), f.runtime); + expect(JSON.parse(preview.stdout)).toMatchObject({ dryRun: true, changes: { saveWorkflow: false } }); + await expect(handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p"]), f.runtime)).rejects.toThrow("--yes"); + expect(f.requests).toEqual([]); +}); + +test("其他保存入口的部分成功异常通过统一 JSON 错误边界保留元数据", () => { + const result = cliErrorResult(new WorkflowSavePartialError(WorkflowDetailSchema.parse({ id: "p", tasksVersion: 2 }), new Error("refresh failed")), true); + expect(result.exitCode).not.toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ error: true, details: { remoteSaved: true, failedStep: "chooses", saved: { pipelineId: "p", tasksVersion: 2 } } }); +}); diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 952c759..3cfbccb 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -6,6 +6,7 @@ import { classifyCliError } from "./errors.js"; import { initCorpRuntime } from "./helpers.js"; import { findCommandByArea, isStandingCommand } from "./registry.js"; import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js"; +import { EkbError } from "../core/errors.js"; let runQueue = Promise.resolve(undefined); @@ -109,7 +110,7 @@ export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult { const message = redactSensitiveText(error instanceof Error ? error.message : String(error)); const classification = classifyCliError(error); return { - stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "", + stdout: jsonMode ? redactSensitiveText(JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}), ...(error instanceof EkbError && error.details ? { details: error.details } : {}) }, null, 2)) : "", stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`, exitCode: classification.exitCode, }; diff --git a/src/core/README.core.md b/src/core/README.core.md index 0bfb473..6dd2646 100644 --- a/src/core/README.core.md +++ b/src/core/README.core.md @@ -60,3 +60,5 @@ src/core/ - 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。 子域客户端在 401 后使缓存失效、重新换票,并从新缓存读取请求头重放原请求一次;同一客户端无需重建。持续鉴权失败停止重试,POST 请求体在重放时保持一致。 + +重放响应仍检查 HTTP 401 与 `error-type` 鉴权错误头(包括 HTTP 200 携带错误头的情况);再次失败抛出 `AuthenticationError`,不再第三次请求。非鉴权 HTTP 错误保持 Ky 的错误语义。 diff --git a/src/core/errors.ts b/src/core/errors.ts index 87b5983..9d6084f 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -2,7 +2,8 @@ export class EkbError extends Error { constructor( message: string, public readonly code: string, - public readonly status?: number + public readonly status?: number, + public readonly details?: Record ) { super(message); this.name = "EkbError"; diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index b876f59..f457ba8 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -1,4 +1,10 @@ import ky, { KyInstance, type BeforeRequestState } from "ky"; +import { AuthenticationError } from "../errors.js"; + +function isAuthenticationFailure(response: Response): boolean { + const errorType = response.headers.get("error-type"); + return response.status === 401 || errorType === "UnauthenticatedException" || errorType === "UnauthorizedException"; +} export interface CreateClientOptions { prefixUrl: string; @@ -45,11 +51,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance { afterResponse: [ async ({ request, response }) => { if (!response) return response; - const errorType = response.headers.get("error-type"); - const isAuthError = - response.status === 401 || - errorType === "UnauthenticatedException" || - errorType === "UnauthorizedException"; + const isAuthError = isAuthenticationFailure(response); if (isAuthError && options.onUnauthorized && options.retryUnauthorized !== false) { const replay = replays.get(request); @@ -66,7 +68,17 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance { } } // Ky's Request.clone type omits Bun's extra Headers methods; the runtime object is unchanged. - return ky(replay as unknown as Request, { retry: 0, timeout: options.timeout ?? 30000 }); + return ky(replay as unknown as Request, { + retry: 0, + timeout: options.timeout ?? 30000, + // 只执行最终鉴权检查,不再续期;非鉴权 HTTP 错误仍由 Ky 处理。 + hooks: { afterResponse: [({ response: replayResponse }) => { + if (isAuthenticationFailure(replayResponse)) { + throw options.onAuthFailure?.(replayResponse) ?? new AuthenticationError("认证续期后仍失败,请重新登录"); + } + return replayResponse; + }] }, + }); } if (isAuthError && options.onAuthFailure) { throw options.onAuthFailure(response); diff --git a/src/core/http/replay-contract.test.ts b/src/core/http/replay-contract.test.ts new file mode 100644 index 0000000..4411ef2 --- /dev/null +++ b/src/core/http/replay-contract.test.ts @@ -0,0 +1,45 @@ +import { afterEach, expect, test } from "bun:test"; +import { HTTPError } from "ky"; +import { createAuthClient } from "./factory.js"; +import { AuthenticationError } from "../errors.js"; + +const originalFetch = globalThis.fetch; +afterEach(() => { globalThis.fetch = originalFetch; }); + +for (const finalStatus of [200, 401]) { + test(`续期后 HTTP ${finalStatus} 的鉴权错误仍拒绝,且不第三次请求`, async () => { + const bodies: string[] = []; + let refreshes = 0; + globalThis.fetch = (async (input: Request) => { + bodies.push(await input.text()); + return bodies.length === 1 ? new Response("expired", { status: 401 }) + : Response.json({ error: true }, { status: finalStatus, headers: { "error-type": "UnauthenticatedException" } }); + }) as unknown as typeof fetch; + const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({ token: "fake" }), onUnauthorized: () => { refreshes++; } }); + await expect(client.post("action", { json: { amount: 42 } }).json()).rejects.toBeInstanceOf(AuthenticationError); + expect(refreshes).toBe(1); + expect(bodies).toEqual(['{"amount":42}', '{"amount":42}']); + }); +} + +test("重放保留正常成功和非鉴权 HTTP 错误的 Ky 语义", async () => { + for (const status of [200, 503]) { + let requests = 0; + globalThis.fetch = (async () => ++requests === 1 ? new Response("", { status: 401 }) : Response.json({ ok: true }, { status })) as unknown as typeof fetch; + const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({}), onUnauthorized: () => {} }); + const result = client.get("action").json(); + if (status === 200) expect(await result).toEqual({ ok: true }); + else await expect(result).rejects.toBeInstanceOf(HTTPError); + expect(requests).toBe(2); + } +}); + +test("最终鉴权失败仍调用调用方提供的错误构造器", async () => { + let requests = 0; + let failures = 0; + globalThis.fetch = (async () => { requests++; return new Response("", { status: 401 }); }) as unknown as typeof fetch; + const client = createAuthClient({ prefixUrl: "https://tenant.invalid", getHeaders: () => ({}), onUnauthorized: () => {}, onAuthFailure: () => { failures++; return new AuthenticationError("重新登录"); } }); + await expect(client.get("action")).rejects.toThrow("重新登录"); + expect(requests).toBe(2); + expect(failures).toBe(1); +}); diff --git a/src/domains/README.domains.md b/src/domains/README.domains.md index 6487708..391ba16 100644 --- a/src/domains/README.domains.md +++ b/src/domains/README.domains.md @@ -6,9 +6,9 @@ | 域 | 内部形态 | 说明 | 详细文档 | |---|---|---|---| -| `platform/` | `api / tools / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) | -| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) | -| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) | +| `platform/` | `api / services / workflow/{analysis,branch,nodes,script,state,watch,alert} / types` | 自建应用(DataLink Platform)与工作流(EASO/Piper)、静态分析、草稿乐观锁状态机与错误指纹告警 | [README.platform.md](./platform/README.platform.md) | +| `datalink/` | `api / services / fields / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) | +| `bill/` | `api / tools / create / copy / submit / templates / write / draft-validation / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) | | `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) | | `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) | | `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) | diff --git a/src/domains/assist-platform/README.assist-platform.md b/src/domains/assist-platform/README.assist-platform.md index 2a66ffa..964643d 100644 --- a/src/domains/assist-platform/README.assist-platform.md +++ b/src/domains/assist-platform/README.assist-platform.md @@ -29,6 +29,8 @@ ## 会话生成、导入与身份完整度 +- `enter --staff <姓名>` 优先精确姓名且必须定位到唯一启用员工,重复行按员工 ID 去重;多个候选会在换票前拒绝。可用 `--staff-id <员工ID>` 明确目标并跳过姓名搜索;`--admin` 不能与员工选项组合。 + - `assist-platform enter --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。 - `--save --yes` 导入后同步注册当前企业上下文;`--switch` 仅在实际切换成功后输出 `switched: true`。失败时说明配置已保存并提示重试切换。 - 生成成功的文本与 JSON 明确交付会话 Token 和可用免密链接,使用 CLI 受控凭证输出机制;捕获的诊断日志和错误继续统一脱敏。 diff --git a/src/domains/assist-platform/services.ts b/src/domains/assist-platform/services.ts index b1bc6ab..94a0118 100644 --- a/src/domains/assist-platform/services.ts +++ b/src/domains/assist-platform/services.ts @@ -285,7 +285,14 @@ export async function generateAssistSession( `在企业 [${corpId}] 中未找到名为 "${resolvedStaffName}" 的员工` ); } - const targetStaff = staffList[0]; + const activeStaff = staffList.filter((staff) => staff.active !== false && staff.id); + const exact = activeStaff.filter((staff) => staff.name === resolvedStaffName); + const candidates = [...new Map((exact.length ? exact : activeStaff).map((staff) => [staff.id, staff])).values()]; + if (candidates.length > 1) { + throw new BusinessError(`匹配到多个员工 [${resolvedStaffName}],请使用 --staff-id 指定唯一员工 ID`); + } + const targetStaff = candidates[0]; + if (!targetStaff) throw new NotFoundError(`在企业 [${corpId}] 中未找到可用员工 [${resolvedStaffName}]`); resolvedStaffId = targetStaff.id; resolvedStaffName = targetStaff.name; } diff --git a/src/domains/assist-platform/session-target.test.ts b/src/domains/assist-platform/session-target.test.ts new file mode 100644 index 0000000..22321d7 --- /dev/null +++ b/src/domains/assist-platform/session-target.test.ts @@ -0,0 +1,46 @@ +import { afterEach, expect, test } from "bun:test"; +import ky from "ky"; +import { generateAssistSession } from "./services.js"; + +const originalFetch = globalThis.fetch; +afterEach(() => { globalThis.fetch = originalFetch; }); + +function fixture(staff: Array<{ id: string; name: string; active?: boolean }>) { + const requests: Array<{ path: string; body: Record }> = []; + // Identity probing is separate from the assist client; keep it offline too. + globalThis.fetch = (async () => Response.json({})) as unknown as typeof fetch; + const client = ky.create({ prefix: "https://assist.invalid/api", retry: 0, fetch: async (input, init) => { + const request = input instanceof Request ? input : new Request(input.toString(), init); + const body = await request.json() as Record; + requests.push({ path: new URL(request.url).pathname, body }); + return request.url.endsWith("/getStaff") + ? Response.json({ items: staff }) + : Response.json({ value: { token: "fake", loginUrl: "https://tenant.invalid/login", baseUrl: "https://tenant.invalid" } }); + } }); + return { client, requests }; +} + +test("同名不同员工不会请求任意一人的免密凭证", async () => { + const { client, requests } = fixture([{ id: "one", name: "同名" }, { id: "two", name: "同名" }]); + await expect(generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "同名" })).rejects.toThrow("--staff-id"); + expect(requests.map(r => r.path)).toEqual(["/api/assistPlatform/getStaff"]); +}); + +test("重复查询行按员工 ID 去重;唯一精确姓名优先于模糊候选", async () => { + const { client, requests } = fixture([{ id: "one", name: "张三" }, { id: "one", name: "张三" }, { id: "two", name: "张三丰" }]); + await generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "张三" }); + expect(requests.at(-1)?.body.staffId).toBe("one"); +}); + +test("停用员工不会被选为换票目标", async () => { + const { client, requests } = fixture([{ id: "one", name: "张三", active: false }]); + await expect(generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "张三" })).rejects.toThrow("未找到可用员工"); + expect(requests).toHaveLength(1); +}); + +test("显式员工 ID 跳过姓名搜索并按该 ID 换票", async () => { + const { client, requests } = fixture([]); + await generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffId: "two" }); + expect(requests).toHaveLength(1); + expect(requests[0].body).toEqual({ ticketId: "ticket", corporationId: "corp", isAdmin: false, staffId: "two" }); +}); diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index db72778..faf50f2 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -9,7 +9,7 @@ src/domains/bill/ ├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API ├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排 ├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿 -├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文) +├── write.ts # 草稿写动作门面:freeflow.delete 等(传输统一在 api.ts) ├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态) ├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用) ├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细) @@ -65,6 +65,7 @@ src/domains/bill/ 10. **纯接口复制 (`copyBillAsDraft`)**: - 读取服务端最新的 `flow.form`; - 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`; + - 只重置源单实际包含的发票字段,不向通用模板注入 `u_发票总金额` 等租户自定义属性。 - 重算报销/支付金额,附件默认保留; - `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。 11. **草稿删除 (`deleteBillDraft`)**: @@ -77,9 +78,11 @@ src/domains/bill/ - 默认只返回启用中的模板,`--all` 才会尝试带出停用项(服务端未返回停用项时两者一致)。 13. **按模板创建草稿 (`createBillDraft`)**: + - 与复制/提交共用实际规格校验;明细规格不存在、必填项缺失或文本超过模板上限时,预演和执行均拒绝创建。 - 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细; - 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。 14. **提交送审 (`submitBillDraft`)**: + - 创建、复制、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。 - 先 `POST /api/v1/flow/plans/computed` 计算审批计划; - 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造; - 再 `POST /api/flow/v1/flows/$`(`name: freeflow.submit`,携带 `nodes`)。 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index d695ba8..515c017 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -1,5 +1,6 @@ import { KyInstance } from "ky"; import { z } from "zod"; +import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js"; import { RawBillSearchResponseSchema, RawBillBatchGetResponseSchema, @@ -9,6 +10,9 @@ import { type RawBillItem, type EntityMeta, type FormSpecification, + type BillTemplateRawGroup, + type BillPlanNode, + type BillFlowWriteResult, } from "./types.js"; function quoted(value: string): string { @@ -628,6 +632,7 @@ export async function getFormSpecification( value?: unknown; id?: string; }; + assertBillResponse(json); const raw = Array.isArray(json.items) ? json.items[0] : json.value ?? (typeof json.id === "string" ? json : undefined); @@ -635,3 +640,87 @@ export async function getFormSpecification( return FormSpecificationSchema.parse(raw); } +/** 检查已知业务错误包装;单据的 code(如 B26000001)不是状态码。 */ +function assertBillResponse(value: unknown): asserts value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new EkbApiError("单据接口返回的响应格式无效", "BILL_RESPONSE_INVALID", 502); + } + const record = value as Record; + const errorCode = record.errorCode; + const hasErrorCode = errorCode != null && ![0, "0", "", "SUCCESS", false].includes(errorCode as string | number | boolean); + if (!hasErrorCode && record.success !== false && record.error !== true && !(typeof record.code === "number" && record.code !== 0 && record.code !== 200)) return; + const message = [record.errorMessage, record.message, record.msg].find((item): item is string => typeof item === "string" && item.length > 0) || "单据接口拒绝了操作"; + const status = Number(errorCode ?? record.code); + if (status === 401) throw new AuthenticationError(message); + if (status === 403) throw new PermissionError(message); + throw new EkbApiError(message, "BILL_API_ERROR", 400); +} + +function billFlowResult(json: unknown): BillFlowWriteResult { + assertBillResponse(json); + const flow = json.flow ?? json.value ?? json; + assertBillResponse(flow); + if (typeof flow.id !== "string" || !flow.id.trim() || (flow.form !== undefined && (!flow.form || typeof flow.form !== "object" || Array.isArray(flow.form)))) { + throw new EkbApiError("单据写入响应缺少有效流程 ID 或表单结构", "BILL_WRITE_RESPONSE_INVALID", 502); + } + return flow as BillFlowWriteResult; +} + +export async function getBillCurrentStaff(client: KyInstance, corpId: string): Promise> { + const response = await client.get("api/v1/organization/staffs/me", { searchParams: { corpId } }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value; + const staff = value && typeof value === "object" ? (value as Record).staff ?? json : json; + assertBillResponse(staff); + return staff; +} + +export async function getBillTemplateGroups(client: KyInstance, corpId: string): Promise { + // 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。 + const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", { + searchParams: { corpId, _t: String(Date.now()) }, + headers: { "cache-control": "no-cache", pragma: "no-cache" }, + }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value as { items?: unknown } | undefined; + return z.array(z.object({ + name: z.string().optional(), active: z.boolean().optional(), + specifications: z.array(z.object({ id: z.string().optional(), originalId: z.string().optional(), name: z.string().optional(), type: z.string().optional(), active: z.boolean().optional() })).optional(), + })).parse(json.items ?? value?.items ?? []); +} + +export async function createBillFlow(client: KyInstance, corpId: string, form: Record): Promise { + const response = await client.post("api/flow/v1/flows", { searchParams: { corpId }, json: { name: "freeflow.edit", form } }); + return billFlowResult(await response.json()); +} + +export async function computeBillApprovalPlan(client: KyInstance, corpId: string, flowId: string, flowPlanConfigId: string, form: Record, formType: string): Promise { + const response = await client.post("api/v1/flow/plans/computed", { + searchParams: { corpId }, json: { flowId, flowPlanConfigId, form, formType, params: {} }, + }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value as { nodes?: unknown } | undefined; + const parsed = z.array(z.object({ id: z.string().optional(), name: z.string().optional(), type: z.string().optional(), approverId: z.unknown().optional(), approverIds: z.array(z.unknown()).optional() }).passthrough()).safeParse(value?.nodes ?? []); + if (!parsed.success) throw new EkbApiError("审批计划节点格式无效", "BILL_PLAN_RESPONSE_INVALID", 502); + return parsed.data; +} + +export async function submitBillFlow(client: KyInstance, corpId: string, flowId: string, form: Record, formType: string, nodes: BillPlanNode[]): Promise { + const response = await client.post(`api/flow/v1/flows/$${flowId}`, { + searchParams: { corpId, pushMessageCode: "debug" }, json: { id: flowId, name: "freeflow.submit", formType, form, nodes }, + }); + const json: unknown = await response.json(); + billFlowResult(json); + return json; +} + +export async function deleteBillFlow(client: KyInstance, corpId: string, flowId: string): Promise { + const response = await client.post(`api/flow/v1/flows/$${flowId}`, { searchParams: { corpId }, json: { id: flowId, name: "freeflow.delete" } }); + const text = await response.text(); + if (!text) throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500); + billFlowResult(JSON.parse(text)); +} + diff --git a/src/domains/bill/copy.ts b/src/domains/bill/copy.ts index 5575741..ba9cb2e 100644 --- a/src/domains/bill/copy.ts +++ b/src/domains/bill/copy.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; import { NotFoundError } from "../../core/errors.js"; -import { getRawBillFlow } from "./api.js"; +import { createBillFlow, getRawBillFlow } from "./api.js"; import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js"; /** @@ -81,20 +81,20 @@ export function buildBillCopyForm( amountSum += moneyNumber(ft.amount); // 复制不携带发票绑定;发票总额归零 - ft.invoice = "0"; - ft.invoiceForm = { type: "exist", invoices: [] }; - ft.u_发票总金额 = zeroMoney(ft.u_发票总金额); + 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) { + if (!keepAttachments && ft.attachments !== undefined) { ft.attachments = []; } } - form.u_发票总金额 = zeroMoney(form.u_发票总金额); + 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) { + if (!keepAttachments && form.attachments !== undefined) { form.attachments = []; } @@ -124,19 +124,7 @@ export async function copyBillAsDraft( const form = buildBillCopyForm(sourceForm, options); assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form)); - const response = await client.post("api/flow/v1/flows", { - searchParams: { corpId }, - json: { name: "freeflow.edit", form }, - }); - const json = (await response.json()) as { - value?: { id?: string; form?: { code?: string } } | string; - flow?: { id?: string; form?: { code?: string } }; - id?: string; - form?: { code?: string }; - }; - const value = (json.value && typeof json.value === "object" ? json.value : undefined) - ?? json.flow - ?? json; + const value = await createBillFlow(client, corpId, form); const formSnapshot = (value.form ?? {}) as Record; return { diff --git a/src/domains/bill/create.ts b/src/domains/bill/create.ts index b5f1be5..1567c39 100644 --- a/src/domains/bill/create.ts +++ b/src/domains/bill/create.ts @@ -1,7 +1,8 @@ import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; -import { getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js"; +import { createBillFlow, getBillCurrentStaff, getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js"; import { listBillTemplates } from "./templates.js"; +import { assertBillDraftValid } from "./draft-validation.js"; /** * 纯接口创建单据草稿。 @@ -57,7 +58,7 @@ export function filterBillFormByTemplate( /** * 按费用类型 schema 过滤明细字段:费用类型没有声明的字段不发(如 feeDate)。 - * schema 拉取失败(components 为空)时保留候选字段,由服务端兜底。 + * 规格未声明字段(components 为空)时保留候选字段;调用方须先确认规格存在。 */ export function filterFeeTypeFormBySpec( candidate: Record, @@ -136,11 +137,7 @@ export async function prepareBillDraft( versionedSpecificationId = hit.versionedId; } - const meResponse = await client.get("api/v1/organization/staffs/me", { - searchParams: { corpId }, - }); - const meJson = (await meResponse.json()) as Record; - const staff = meJson.value?.staff ?? meJson; + const staff = await getBillCurrentStaff(client, corpId); const submitterId = options.submitterId || staff.id; const corpDeptCandidate = (value: unknown): string | undefined => { if (typeof value === "string" && value && value !== corpId) return value; @@ -201,6 +198,7 @@ export async function prepareBillDraft( standardStrCode: "CNY", }; const detailSpec = await getFormSpecification(client, corpId, feeType.expenseSpecificationId); + if (!detailSpec) throw new NotFoundError(`未找到费用类型规格: ${feeType.expenseSpecificationId}`); const detailComponents = ((detailSpec as { components?: TemplateComponent[] } | undefined)?.components ?? []) as TemplateComponent[]; const feeTypeForm = filterFeeTypeFormBySpec( @@ -236,6 +234,8 @@ export async function prepareBillDraft( ); } + assertBillDraftValid(form, { components: specification.components, detailComponents: [detailSpec.components] }); + return { form, title, amount, feeType: feeType.name ?? "" }; } @@ -245,15 +245,7 @@ export async function createBillDraft( options: CreateBillOptions ): Promise { const { form, title, amount, feeType } = await prepareBillDraft(client, corpId, options); - const response = await client.post("api/flow/v1/flows", { - searchParams: { corpId }, - json: { name: "freeflow.edit", form }, - }); - const json = (await response.json()) as Record; - const value = - (json.value && typeof json.value === "object" ? json.value : undefined) ?? - json.flow ?? - json; + const value = await createBillFlow(client, corpId, form); return { flowId: String(value?.id ?? ""), diff --git a/src/domains/bill/submit.ts b/src/domains/bill/submit.ts index 2ea6a6c..733bc6f 100644 --- a/src/domains/bill/submit.ts +++ b/src/domains/bill/submit.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; -import { getFormSpecification, getRawBillFlow } from "./api.js"; +import { computeBillApprovalPlan, getFormSpecification, getRawBillFlow, submitBillFlow } from "./api.js"; import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js"; /** @@ -26,15 +26,6 @@ export interface SubmitBillResult { response: unknown; } -interface PlanNode { - id?: string; - name?: string; - type?: string; - approverId?: unknown; - approverIds?: unknown[]; - [key: string]: unknown; -} - export async function submitBillDraft( client: KyInstance, corpId: string, @@ -67,12 +58,7 @@ export async function submitBillDraft( } const formType = String(form.type ?? flow.formType ?? "expense"); - const planResponse = await client.post("api/v1/flow/plans/computed", { - searchParams: { corpId }, - json: { flowId, flowPlanConfigId, form, formType, params: {} }, - }); - const planJson = (await planResponse.json()) as { value?: { nodes?: PlanNode[] } }; - const nodes = planJson.value?.nodes ?? []; + const nodes = await computeBillApprovalPlan(client, corpId, flowId, flowPlanConfigId, form, formType); if (nodes.length === 0) { throw new ValidationError("审批计划为空,无法提交"); } @@ -96,15 +82,12 @@ export async function submitBillDraft( ); } - const response = await client.post(`api/flow/v1/flows/$${flowId}`, { - searchParams: { corpId, pushMessageCode: "debug" }, - json: { id: flowId, name: "freeflow.submit", formType, form, nodes }, - }); + const response = await submitBillFlow(client, corpId, flowId, form, formType, nodes); return { flowId, code: String(form.code ?? target), nodeCount: nodes.length, - response: await response.json(), + response, }; } diff --git a/src/domains/bill/templates.ts b/src/domains/bill/templates.ts index 2795fc3..ee61084 100644 --- a/src/domains/bill/templates.ts +++ b/src/domains/bill/templates.ts @@ -1,4 +1,6 @@ import type { KyInstance } from "ky"; +import { getBillTemplateGroups } from "./api.js"; +import type { BillTemplateRawGroup as RawGroup } from "./types.js"; /** * 单据模板(表单规格)列表。 @@ -32,25 +34,11 @@ export interface BillTemplateList { inactive: number; } -interface RawSpecification { - id?: string; - originalId?: string; - name?: string; - type?: string; - active?: boolean; -} - /** 去掉版本化 ID 末尾的 `:`,保留可被 `bill spec` 使用的原始 ID。 */ function stripVersionHash(id: string): string { return id.replace(/:[0-9a-f]{32,64}$/i, ""); } -interface RawGroup { - name?: string; - active?: boolean; - specifications?: RawSpecification[]; -} - export interface ListBillTemplatesOptions { includeInactive?: boolean; } @@ -101,12 +89,5 @@ export async function listBillTemplates( corpId: string, options: ListBillTemplatesOptions = {} ): Promise { - // 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。 - const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", { - searchParams: { corpId, _t: String(Date.now()) }, - headers: { "cache-control": "no-cache", pragma: "no-cache" }, - }); - const json = (await response.json()) as { items?: RawGroup[]; value?: { items?: RawGroup[] } }; - const items = json.items ?? json.value?.items ?? []; - return normalizeTemplateGroups(items, options); + return normalizeTemplateGroups(await getBillTemplateGroups(client, corpId), options); } diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index 7f2884b..38718f3 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -80,6 +80,27 @@ export type FormPriorityItem = z.infer; export type FormSpecificationComponent = z.infer; export type FormSpecification = z.infer; +export interface BillTemplateRawGroup { + name?: string; + active?: boolean; + specifications?: Array<{ id?: string; originalId?: string; name?: string; type?: string; active?: boolean }>; +} + +export interface BillPlanNode { + id?: string; + name?: string; + type?: string; + approverId?: unknown; + approverIds?: unknown[]; + [key: string]: unknown; +} + +export interface BillFlowWriteResult { + id: string; + form?: Record; + [key: string]: unknown; +} + // ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)───────────────────── export const RawBillMoneySchema = z.object({ diff --git a/src/domains/bill/write-contract.test.ts b/src/domains/bill/write-contract.test.ts index e35f40a..b7adf5a 100644 --- a/src/domains/bill/write-contract.test.ts +++ b/src/domains/bill/write-contract.test.ts @@ -21,6 +21,9 @@ function fixture(options: { missingSpec?: boolean; missingDetailSpec?: boolean; specError?: Error; + titleMaxLength?: number; + writeResponse?: unknown; + planResponse?: unknown; } = {}) { const writes: Array<{ url: string; json: any }> = []; const reads: string[] = []; @@ -36,7 +39,7 @@ function fixture(options: { return { items: options.missingSpec || (detailSpec && options.missingDetailSpec) ? [] : [{ id: detailSpec ? "detail" : "spec", name: "测试模板", configs: [{ ability: "flow", flowPlanConfigId: "plan" }], - components: [{ field: "title", optional: true }, ...(required ? [{ field: required, optional: false }] : [])], + components: [{ field: "title", optional: true, maxLength: options.titleMaxLength }, ...(required ? [{ field: required, optional: false }] : [])], }] }; } if (url.includes("feeTypes/")) return { items: options.tree ?? [{ feeType: { id: "folder" }, children: [{ feeType: fee, children: [] }] }] }; @@ -48,16 +51,53 @@ function fixture(options: { if (url.includes("/flows/flowId/")) return { value: { id: "f", state: "draft", form: source } }; if (url.endsWith("/plans/computed")) { plans.push(payload.json); - return { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } }; + return options.planResponse ?? { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } }; } writes.push({ url, json: payload.json }); - return { flow: { id: "new", form: { code: "B1" } } }; + return options.writeResponse ?? { flow: { id: "new", form: { code: "B1" } } }; } }), } as unknown as KyInstance; return { client, writes, reads, plans }; } describe("bill API write contracts", () => { + test("复制通用模板不注入源单没有的发票或租户自定义字段", async () => { + const { client, writes } = fixture(); + await copyBillAsDraft(client, "corp", "f", { keepAttachments: false }); + expect(writes).toHaveLength(1); + expect(writes[0].json.form).not.toHaveProperty("u_发票总金额"); + expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("u_发票总金额"); + expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("invoice"); + expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("invoiceForm"); + expect(writes[0].json.form).not.toHaveProperty("attachments"); + expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("attachments"); + }); + test("创建和预演均拒绝缺失明细规格、必填明细与过长表头,不发起创建", async () => { + for (const options of [{ missingDetailSpec: true }, { detailRequired: "u_项目" }, { titleMaxLength: 1 }]) { + const { client, writes } = fixture(options); + await expect(prepareBillDraft(client, "corp", { templateId: versionedId, title: "过长标题" })).rejects.toThrow(); + await expect(createBillDraft(client, "corp", { templateId: versionedId, title: "过长标题" })).rejects.toThrow(); + expect(writes).toEqual([]); + } + }); + for (const action of [ + (client: KyInstance) => createBillDraft(client, "corp", { templateId: versionedId }), + (client: KyInstance) => copyBillAsDraft(client, "corp", "f"), + (client: KyInstance) => submitBillDraft(client, "corp", "f"), + ]) { + test("单据写入明确拒绝业务错误或缺失 ID 的成功响应", async () => { + for (const writeResponse of [{ errorCode: "REJECTED", errorMessage: "规则拒绝" }, {}, { flow: { id: "" } }]) { + const { client, writes } = fixture({ writeResponse }); + await expect(action(client)).rejects.toThrow(); + expect(writes).toHaveLength(1); + } + }); + } + test("计算计划返回业务错误时不会继续送审", async () => { + const { client, writes } = fixture({ planResponse: { errorCode: "DENIED", errorMessage: "计划不可用" } }); + await expect(submitBillDraft(client, "corp", "f")).rejects.toThrow("计划不可用"); + expect(writes).toEqual([]); + }); test("creates with nested canonical feeType nodes and retains flat response compatibility", async () => { for (const tree of [undefined, [fee]]) { const { client, writes } = fixture({ tree }); diff --git a/src/domains/bill/write-response.test.ts b/src/domains/bill/write-response.test.ts new file mode 100644 index 0000000..45cead5 --- /dev/null +++ b/src/domains/bill/write-response.test.ts @@ -0,0 +1,43 @@ +import { expect, test } from "bun:test"; +import ky from "ky"; +import { createBillFlow, deleteBillFlow, submitBillFlow } from "./api.js"; +import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js"; + +function fixture(response: unknown, status = 200) { + let requests = 0; + const client = ky.create({ prefix: "https://tenant.invalid", retry: 0, fetch: async () => { + requests++; + return Response.json(response, { status }); + } }); + return { client, count: () => requests }; +} + +test("创建兼容 flow/value/裸对象包装,保留正常业务单号", async () => { + const flow = { id: "created", code: "B26000001", form: { code: "B26000001" } }; + for (const response of [{ flow }, { value: flow }, flow]) { + expect(await createBillFlow(fixture(response).client, "corp", { title: "草稿" })).toEqual(flow); + } +}); + +test("所有单据写动作检查 HTTP 200 中的业务拒绝与鉴权错误", async () => { + for (const action of [ + (client: ReturnType) => createBillFlow(client, "corp", {}), + (client: ReturnType) => submitBillFlow(client, "corp", "f", {}, "expense", []), + (client: ReturnType) => deleteBillFlow(client, "corp", "f"), + ]) { + for (const [errorCode, ErrorClass] of [["REJECTED", EkbApiError], [401, AuthenticationError], [403, PermissionError]] as const) { + const { client, count } = fixture({ errorCode, errorMessage: "拒绝操作" }); + await expect(action(client)).rejects.toBeInstanceOf(ErrorClass); + expect(count()).toBe(1); + } + } +}); + +test("HTTP 失败不被吞掉;无效或空流程 ID 不被强转为成功", async () => { + const { client, count } = fixture({ error: "unavailable" }, 503); + await expect(createBillFlow(client, "corp", {})).rejects.toThrow(); + expect(count()).toBe(1); + for (const response of [{ flow: {} }, { flow: { id: 1 } }, { value: { id: " " } }, { id: "f", form: [] }]) { + await expect(createBillFlow(fixture(response).client, "corp", {})).rejects.toBeInstanceOf(EkbApiError); + } +}); diff --git a/src/domains/bill/write.ts b/src/domains/bill/write.ts index daafb88..d6e0224 100644 --- a/src/domains/bill/write.ts +++ b/src/domains/bill/write.ts @@ -1,5 +1,5 @@ import type { KyInstance } from "ky"; -import { EkbApiError } from "../../core/errors.js"; +import { deleteBillFlow } from "./api.js"; /** * 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$` + `name` 区分)。 @@ -12,25 +12,6 @@ import { EkbApiError } from "../../core/errors.js"; * 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。 */ -async function postFlowAction( - client: KyInstance, - corpId: string, - flowId: string, - name: string, - extra: Record = {}, - searchParams: Record = {} -): Promise | undefined> { - const response = await client.post(`api/flow/v1/flows/$${flowId}`, { - searchParams: { corpId, ...searchParams }, - json: { id: flowId, name, ...extra }, - }); - const text = await response.text(); - if (!text) return undefined; - const json = JSON.parse(text) as { flow?: Record }; - if (json.flow) return json.flow; - return undefined; -} - /** * 删除草稿单据及其费用明细(`freeflow.delete`)。 * 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。 @@ -40,8 +21,5 @@ export async function deleteBillDraft( corpId: string, flowId: string ): Promise { - const flow = await postFlowAction(client, corpId, flowId, "freeflow.delete"); - if (!flow) { - throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500); - } + await deleteBillFlow(client, corpId, flowId); } diff --git a/src/domains/datalink/README.datalink.md b/src/domains/datalink/README.datalink.md index 8e84674..72ac2f2 100644 --- a/src/domains/datalink/README.datalink.md +++ b/src/domains/datalink/README.datalink.md @@ -8,8 +8,8 @@ DataLink 域负责跨企业查询当前账号可见的自建应用、业务对 src/domains/datalink/ ├── types.ts # 应用详情、对象字段、记录分页与权限模型 ├── api.ts # DataLink HTTP 传输层 -├── services.ts # 应用/对象名称解析与查询表达式辅助 -└── tools.ts # MCP tool 注册 +├── services.ts # 应用/对象名称解析与查询表达式辅助、SDK 门面 +└── fields.ts # 读取与写入共用的唯一字段解析 ``` ## 查询链路 @@ -62,6 +62,7 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称> - `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。 - `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。 - `record get` 支持直传 `<记录ID>` 免传应用与业务对象。 +- 筛选、`--set` 与 JSON 安全合并共用字段解析:明确物理键优先,标签或模糊匹配必须唯一;歧义在写入前拒绝,须改用完整物理字段名。未知原始字段继续保持兼容透传,`--raw` 仍直接透传原始补丁。 - `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E__*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。 - `records --all` 自动按 `500` 条/页循环拉取全量台账记录。 - `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。 @@ -73,19 +74,25 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称> ```typescript import { initCorpRuntime, + requireSelectedCorp, + createClientsForCorp, resolvePlatform, resolveEntity, iterateAllEntityRecords, normalizeDatalinkRecord, - calculateEntityRecordStats, } from "hose-use/sdk"; -const runtime = await initCorpRuntime(); -const platform = await resolvePlatform(runtime.clients.ekbClient, "新转转集团"); -const entity = await resolveEntity(runtime.clients.ekbClient, platform.id, "合同"); +const runtime = initCorpRuntime({ corpId: "企业配置ID", stateless: true }); +const corp = requireSelectedCorp(runtime); +const clients = await createClientsForCorp(corp); +const corpId = corp.corpId || corp.credentials.corpId; +const platform = await resolvePlatform(clients.ekbClient, corpId, "应用名称"); +if (!platform) throw new Error("未找到自建应用"); +const entity = await resolveEntity(clients.ekbClient, corpId, platform, "合同"); +if (!entity) throw new Error("未找到业务对象"); // 1. 万级海量数据 $O(1)$ 内存流式遍历 -for await (const rawRecord of iterateAllEntityRecords(runtime.clients.ekbClient, runtime.corpId, entity.id, { pageSize: 200 })) { +for await (const rawRecord of iterateAllEntityRecords(clients.ekbClient, corpId, entity.id, { pageSize: 200 })) { const record = normalizeDatalinkRecord(rawRecord, entity); // 执行业务逻辑... } diff --git a/src/domains/datalink/api.ts b/src/domains/datalink/api.ts index cb5a3a7..ccda9fe 100644 --- a/src/domains/datalink/api.ts +++ b/src/domains/datalink/api.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { KyInstance } from "ky"; +import { resolveDatalinkField } from "./fields.js"; import { DatalinkEntitySchema, DatalinkPlatformDetailSchema, @@ -356,19 +357,9 @@ export function resolveEntityFieldKey( existingForm: Record = {} ): { key: string; fieldDef?: DatalinkField } { const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId; - const exactByName = fields.find((f) => f.name === inputKey); - if (exactByName) { - return { key: exactByName.name, fieldDef: exactByName }; - } + const field = resolveDatalinkField(fields, bareEntityId, inputKey); + if (field) return { key: field.name, fieldDef: field }; const prefixedKey = `E_${bareEntityId}_${inputKey}`; - const byPrefixedName = fields.find((f) => f.name === prefixedKey); - if (byPrefixedName) { - return { key: byPrefixedName.name, fieldDef: byPrefixedName }; - } - const byLabel = fields.find((f) => f.label === inputKey); - if (byLabel && byLabel.name) { - return { key: byLabel.name, fieldDef: byLabel }; - } if (inputKey.startsWith(`E_${bareEntityId}_`)) { return { key: inputKey }; } diff --git a/src/domains/datalink/field-target.test.ts b/src/domains/datalink/field-target.test.ts new file mode 100644 index 0000000..2446630 --- /dev/null +++ b/src/domains/datalink/field-target.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from "bun:test"; +import ky from "ky"; +import { DatalinkEntitySchema } from "./types.js"; +import { buildSafeRecordEditPayload, compileRecordPredicate, parseSetClause, safeEditRecord } from "./services.js"; + +const entity = DatalinkEntitySchema.parse({ id: "entity", fields: [ + { name: "E_entity_a", label: "金额", type: "number" }, + { name: "E_entity_b", label: "金额", type: "number" }, +] }); + +test("筛选、赋值和 JSON 安全合并均拒绝歧义标签", () => { + expect(() => compileRecordPredicate("金额 == 10", entity)).toThrow("歧义"); + expect(() => parseSetClause("金额=10", entity)).toThrow("歧义"); + expect(() => buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: entity.fields, patchForm: { 金额: 10 } })).toThrow("歧义"); +}); + +test("明确物理键即使与另一个字段的标签冲突,也保持唯一目标", () => { + const collision = DatalinkEntitySchema.parse({ id: "entity", fields: [ + { name: "E_entity_a", label: "E_entity_b", type: "number" }, + { name: "E_entity_b", label: "金额", type: "number" }, + ] }); + expect(parseSetClause("E_entity_b=10", collision)).toEqual({ E_entity_b: 10 }); + expect(compileRecordPredicate("E_entity_b == 10", collision)({ E_entity_a: 1, E_entity_b: 10 })).toBe(true); + const payload = buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: collision.fields, patchForm: { E_entity_b: 10 } }); + expect(payload.form.E_entity_b).toBe(10); + expect(payload.form.E_entity_a).toBeUndefined(); +}); + +test("模糊匹配不唯一时拒绝;物理短名、唯一标签和未知字段兼容保留", () => { + const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [ + { name: "E_entity_a", label: "原始金额", type: "number" }, + { name: "E_entity_b", label: "折算金额", type: "number" }, + ] }); + expect(() => parseSetClause("金额=10", fields)).toThrow("歧义"); + expect(parseSetClause("a=10,折算金额=20,active=true", fields)).toEqual({ E_entity_a: 10, E_entity_b: 20, active: true }); +}); + +test("安全编辑遇到歧义字段在发出写请求前终止", async () => { + const requests: string[] = []; + const client = ky.create({ prefix: "https://tenant.invalid", fetch: async input => { + requests.push(String(input)); + return Response.json({}); + } }); + await expect(safeEditRecord(client, "corp", { entityId: entity.id, recordId: "r", detail: { id: "r" }, fields: entity.fields, patchForm: { 金额: 10 } })).rejects.toThrow("歧义"); + expect(requests).toEqual([]); +}); + +test("未声明的系统字段保留原语义,不会模糊匹配 inactive 等业务标签", () => { + const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [{ name: "E_entity_old", label: "inactive", type: "text" }] }); + expect(compileRecordPredicate("active == true", fields)({ active: true, E_entity_old: false })).toBe(true); + expect(parseSetClause("active=true", fields)).toEqual({ active: true }); +}); diff --git a/src/domains/datalink/fields.ts b/src/domains/datalink/fields.ts new file mode 100644 index 0000000..a6322dc --- /dev/null +++ b/src/domains/datalink/fields.ts @@ -0,0 +1,27 @@ +import { ValidationError } from "../../core/errors.js"; +import type { DatalinkField } from "./types.js"; + +/** 物理键优先;标签和模糊匹配必须指向唯一物理字段。未知字段由调用方决定是否透传。 */ +export function resolveDatalinkField( + fields: DatalinkField[], + entityId: string, + query: string +): DatalinkField | undefined { + const key = query.trim().toLowerCase(); + if (!key) return undefined; + const prefix = `e_${entityId.replace(/^\$/, "").toLowerCase()}_`; + const unique = (matches: DatalinkField[]): DatalinkField | undefined => { + const byName = new Map(matches.map((field) => [field.name, field])); + if (byName.size > 1) { + throw new ValidationError(`字段存在歧义: ${query},请使用完整字段名`); + } + return byName.values().next().value; + }; + const exact = unique(fields.filter((field) => field.name.toLowerCase() === key)) + ?? unique(fields.filter((field) => field.name.toLowerCase() === prefix + key)) + ?? unique(fields.filter((field) => field.label?.toLowerCase() === key)); + if (exact) return exact; + // 未在元数据声明的系统键由调用方读取/透传,不能误匹配到 inactive 等业务标签。 + if (["id", "recordid", "active", "name", "code", "createtime", "updatetime", "entityid"].includes(key)) return undefined; + return unique(fields.filter((field) => field.label?.toLowerCase().includes(key))); +} diff --git a/src/domains/datalink/services.ts b/src/domains/datalink/services.ts index 48275c2..ce78c2d 100644 --- a/src/domains/datalink/services.ts +++ b/src/domains/datalink/services.ts @@ -1,6 +1,7 @@ import type { KyInstance } from "ky"; import * as api from "./api.js"; import { ValidationError } from "../../core/errors.js"; +import { resolveDatalinkField } from "./fields.js"; import type { DatalinkEntity, DatalinkField, @@ -990,19 +991,7 @@ export function resolveEntityField( entity: DatalinkEntity, query: string ): DatalinkField | undefined { - const q = query.trim().toLowerCase(); - const bareQ = q.replace(/^e_[^_]+_/, "").replace(/^e_/, ""); - - return ( - entity.fields.find( - (f) => - f.name.toLowerCase() === q || - f.label?.toLowerCase() === q || - f.name.toLowerCase() === `e_${entity.id.toLowerCase()}_${bareQ}` || - f.name.replace(/^e_[^_]+_/, "").toLowerCase() === bareQ - ) || - entity.fields.find((f) => f.label?.toLowerCase().includes(q)) - ); + return resolveDatalinkField(entity.fields, entity.id, query); } /** @@ -1316,15 +1305,8 @@ function predicateLiteral(raw: string): string | number | boolean | null { } function predicateField(entity: DatalinkEntity, query: string): DatalinkField | string { - const key = query.trim().toLowerCase(); - const candidates = entity.fields.filter(f => - f.name.toLowerCase() === key || f.label?.toLowerCase() === key || - f.name.toLowerCase() === `e_${entity.id.replace(/^\$/, "").toLowerCase()}_${key}` - ); - if (!candidates.length && ["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query; - const matches = candidates.length ? candidates : entity.fields.filter(f => f.label?.toLowerCase().includes(key)); - if (matches.length > 1) throw new ValidationError(`筛选字段存在歧义: ${query},请使用完整字段名`); - if (matches.length === 1) return matches[0]; + const field = resolveEntityField(entity, query); + if (field) return field; if (["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query; throw new ValidationError(`未知筛选字段: ${query}`); } diff --git a/src/domains/platform/README.platform.md b/src/domains/platform/README.platform.md index e4de76e..5f32587 100644 --- a/src/domains/platform/README.platform.md +++ b/src/domains/platform/README.platform.md @@ -19,7 +19,7 @@ src/domains/platform/ │ ├── analysis/ # 工作流静态吞错、审批状态死锁过滤与联动覆盖巡检 (analyzer, types) │ ├── state/ # 草稿版本状态机与发布乐观锁保护 │ └── alert/ # 错误指纹告警与 SQLite 本地持久化 -└── tools.ts # MCP tool 注册 +└── execution-context.ts # 执行树与节点输出上下文辅助 ``` ## 工作流使用与诊断 @@ -34,6 +34,6 @@ CLI 命令、触发器分类、生产调试风险、节点与脚本校验、实 ## 详细文档 -完整接口说明、认证链路、MCP tool 列表见: +接口职责、认证链路与 CLI 能力导航见(MCP 统一使用 `hose_cli`): [docs/modules/platform.md](../../../docs/modules/platform.md) diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index 747fc00..3bc5f92 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -44,8 +44,7 @@ function throwEasoResponseError(response: Response, record?: Record) @@ -57,6 +56,21 @@ async function readEasoResponse(response: Response) { return { raw, record }; } +async function readEasoResponse(response: Response) { + return checkEasoResponse(response, await response.json()); +} + +/** 无返回值的写接口也要检查业务码;兼容 204 与空成功响应。 */ +async function readEasoWriteResponse(response: Response): Promise { + const text = await response.text(); + if (response.ok === false) throwEasoResponseError(response); + if (!text.trim()) return; + let raw: unknown; + try { raw = JSON.parse(text); } + catch { throw new EkbApiError("EASO/Piper 写接口返回无效 JSON", "EASO_RESPONSE_INVALID", 502); } + checkEasoResponse(response, raw); +} + // Helper to unwrap { data: T } / { value: T } response with null/error defense export async function unwrap(response: Response, schema: z.ZodType): Promise { const { raw, record } = await readEasoResponse(response); @@ -152,7 +166,8 @@ export async function updateWorkflowChooses( client: KyInstance, pipelineId: string ): Promise { - await client.put(`api/easo/pipelines/${pipelineId}/chooses`); + const response = await client.put(`api/easo/pipelines/${pipelineId}/chooses`); + await readEasoWriteResponse(response); } export async function copyWorkflow( @@ -181,7 +196,7 @@ export async function deleteWorkflow( pipelineId: string ): Promise { const response = await client.delete(`api/easo/pipelines/${pipelineId}`); - await response.text().catch(() => ""); + await readEasoWriteResponse(response); return true; } diff --git a/src/domains/platform/services.ts b/src/domains/platform/services.ts index d31e794..06f1bae 100644 --- a/src/domains/platform/services.ts +++ b/src/domains/platform/services.ts @@ -1,5 +1,6 @@ import { KyInstance } from "ky"; import { CorpConfig } from "../../core/config/types.js"; +import { WorkflowSavePartialError } from "./workflow/save-error.js"; import * as api from "./api.js"; import { PermissionError, ValidationError } from "../../core/errors.js"; import { explainConditionBranches } from "./workflow/branch/index.js"; @@ -76,10 +77,19 @@ export async function updateWorkflow( const sanitized = sanitizeWorkflowSnapshot(payload); const updated = await api.updateWorkflow(client, sanitized); // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 - await api.updateWorkflowChooses(client, updated.id || workflow.id); + try { + await api.updateWorkflowChooses(client, updated.id || workflow.id); + } catch (error) { + throw new WorkflowSavePartialError(updated, error); + } return updated; } +/** 只重试元数据刷新,不重新提交完整工作流快照。 */ +export function refreshWorkflowChooses(client: KyInstance, pipelineId: string): Promise { + return api.updateWorkflowChooses(client, pipelineId); +} + export async function copyWorkflow( client: import("ky").KyInstance, pipelineId: string, diff --git a/src/domains/platform/workflow/README.workflow.md b/src/domains/platform/workflow/README.workflow.md index e7777fc..079db59 100644 --- a/src/domains/platform/workflow/README.workflow.md +++ b/src/domains/platform/workflow/README.workflow.md @@ -2,6 +2,12 @@ Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。 +## 保存结果与恢复 + +主保存 PUT 后仍需刷新 chooses。刷新返回的业务错误会被检查;HTTP 200 不等于业务成功,空成功响应仍兼容。主保存成功、刷新失败时,SDK 抛出 `WorkflowSavePartialError`,携带 `savedWorkflow` 及结构化 `details`,不得自动重发整个保存。 + +`workflow save --in-place` 遇到这类部分成功仍同步本地版本,返回非零退出码、`status: "partial"`、`remoteSaved: true`、新版本和恢复命令。主保存本身失败则不改本地版本。恢复可用 `workflow refresh-chooses --platform-id= --yes`,只刷新元数据,不提交快照;该命令也支持 `--dry-run`。 + ## CLI 常用命令 ```bash diff --git a/src/domains/platform/workflow/save-error.ts b/src/domains/platform/workflow/save-error.ts new file mode 100644 index 0000000..2e1b05c --- /dev/null +++ b/src/domains/platform/workflow/save-error.ts @@ -0,0 +1,17 @@ +import { EkbError } from "../../../core/errors.js"; +import type { WorkflowDetail } from "../types.js"; + +/** 主保存已经提交,后续元数据刷新失败。调用方必须保留已保存版本。 */ +export class WorkflowSavePartialError extends EkbError { + readonly remoteSaved = true; + + constructor(readonly savedWorkflow: WorkflowDetail, readonly cause: unknown) { + super( + `工作流 [${savedWorkflow.id}] 主保存已完成(tasksVersion=${savedWorkflow.tasksVersion}),元数据刷新失败;请仅重试元数据刷新,不要重复主保存。原因: ${cause instanceof Error ? cause.message : String(cause)}`, + "WORKFLOW_SAVE_PARTIAL", + 502, + { remoteSaved: true, failedStep: "chooses", saved: { pipelineId: savedWorkflow.id, version: savedWorkflow.version, tasksVersion: savedWorkflow.tasksVersion, updateTime: savedWorkflow.updateTime } } + ); + this.name = "WorkflowSavePartialError"; + } +} diff --git a/src/domains/platform/workflow/state/index.test.ts b/src/domains/platform/workflow/state/index.test.ts index 9b29a25..d762a1d 100644 --- a/src/domains/platform/workflow/state/index.test.ts +++ b/src/domains/platform/workflow/state/index.test.ts @@ -67,7 +67,7 @@ describe("workflow draft state machine", () => { let request: { url: string; json: WorkflowDetail } | undefined; const client = { put: async (url: string, options: { json: WorkflowDetail }) => { - if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) }; + if (url.endsWith("/chooses")) return Response.json({ data: [] }); request = { url, json: options.json }; return { json: async () => ({ data: options.json }) }; }, @@ -83,7 +83,7 @@ describe("workflow draft state machine", () => { let sentWorkflow: WorkflowDetail | undefined; const client = { put: async (url: string, options: { json: WorkflowDetail }) => { - if (url.endsWith("/chooses")) return { json: async () => ({ data: [] }) }; + if (url.endsWith("/chooses")) return Response.json({ data: [] }); sentWorkflow = options.json; return { json: async () => ({ data: options.json }) }; }, diff --git a/src/domains/platform/workflow/state/index.ts b/src/domains/platform/workflow/state/index.ts index b4db2c6..7a34379 100644 --- a/src/domains/platform/workflow/state/index.ts +++ b/src/domains/platform/workflow/state/index.ts @@ -1,7 +1,7 @@ import { NotFoundError, ValidationError } from "../../../../core/errors.js"; import type { WorkflowDetail } from "../../types.js"; -export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "failed"; +export type WorkflowDraftStatus = "clean" | "dirty" | "saving" | "saved" | "partial" | "failed"; export interface WorkflowDraftState { workflow: WorkflowDetail; diff --git a/src/domains/platform/write-result.test.ts b/src/domains/platform/write-result.test.ts new file mode 100644 index 0000000..4ec071c --- /dev/null +++ b/src/domains/platform/write-result.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import ky from "ky"; +import { deleteWorkflow, updateWorkflowChooses } from "./api.js"; +import { refreshWorkflowChooses, updateWorkflow } from "./services.js"; +import { WorkflowDetailSchema } from "./types.js"; +import { WorkflowSavePartialError } from "./workflow/save-error.js"; +import { AuthenticationError } from "../../core/errors.js"; + +test("Piper 无返回值写操作兼容空成功,拒绝业务失败与无效 JSON", async () => { + for (const action of [deleteWorkflow, updateWorkflowChooses]) { + for (const body of ["", JSON.stringify({ code: 200, data: [] })]) { + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) }); + await action(client, "p"); + } + for (const body of [JSON.stringify({ code: 500, msg: "拒绝写入" }), "{broken"]) { + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => new Response(body) }); + await expect(action(client, "p")).rejects.toThrow(); + } + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async () => Response.json({ code: 401, msg: "凭证失效" }) }); + await expect(action(client, "p")).rejects.toBeInstanceOf(AuthenticationError); + } +}); + +test("两阶段保存保留已提交版本,恢复只刷新 chooses", async () => { + const workflow = WorkflowDetailSchema.parse({ id: "p", version: "v1", tasksVersion: 1 }); + const calls: string[] = []; + let failRefresh = true; + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => { + const path = new URL(input instanceof Request ? input.url : input.toString()).pathname; + calls.push(path); + return path.endsWith("/chooses") + ? Response.json(failRefresh ? { code: 500, msg: "刷新拒绝" } : { code: 200, data: [] }) + : Response.json({ code: 200, data: { ...workflow, tasksVersion: 2 } }); + } }); + let partial: WorkflowSavePartialError | undefined; + try { await updateWorkflow(client, workflow); } + catch (error) { expect(error).toBeInstanceOf(WorkflowSavePartialError); partial = error as WorkflowSavePartialError; } + expect(partial?.savedWorkflow.tasksVersion).toBe(2); + expect(partial?.details).toMatchObject({ remoteSaved: true, failedStep: "chooses", saved: { tasksVersion: 2 } }); + failRefresh = false; + await refreshWorkflowChooses(client, "p"); + expect(calls).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]); +}); + +test("主保存失败不会刷新 chooses,也不报告部分成功", async () => { + const calls: string[] = []; + const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async input => { + calls.push(input instanceof Request ? input.url : input.toString()); + return Response.json({ code: 500, msg: "主保存拒绝" }); + } }); + const error = await updateWorkflow(client, WorkflowDetailSchema.parse({ id: "p" })).catch(error => error); + expect(error).not.toBeInstanceOf(WorkflowSavePartialError); + expect(calls).toHaveLength(1); +});