From a2cdefb32262389eefe02b584e9262a992cfd964 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Fri, 30 Oct 2026 17:05:20 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E5=B9=B3=E5=8F=B0=E6=9C=8D=E5=8A=A1=E8=81=8C=E8=B4=A3?= =?UTF-8?q?=E5=B9=B6=E5=9B=BA=E5=8C=96=E6=97=A0=E7=8E=AF=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将工作流查询、配置、执行、差异、调试、目录和 DataLink 记录、表达式、审计分别归位。 门面保留显式导出,消除 tracker 及分支类型经聚合出口形成的循环,补充文件级循环检查。 同步总纲、层级文档与接口源码索引,交付完整整改报告。 验证:943 项测试通过,类型、版本和 README 审计通过;二进制和插件构建、验证与打包通过。 81 个迁移函数体保持一致,公共 SDK 导出名和三份生成规范与原始基线一致。 --- AGENTS.md | 1 + docs/modules/platform.md | 11 +- .../reviews/2026-10-30-platform-subdomains.md | 54 + docs/reviews/README.reviews.md | 1 + specs/hose-close-api/endpoints.md | 60 +- .../schemas/workflow-detail.schema.json | 2 +- .../workflow-job-execution.schema.json | 2 +- .../schemas/workflow-snapshot.schema.json | 2 +- src/cli/architecture-boundaries.test.ts | 9 +- src/domains/platform/applications/api.ts | 1 - src/domains/platform/applications/services.ts | 1 - .../platform/datalink/README.datalink.md | 13 +- src/domains/platform/datalink/audit.ts | 641 ++++++++ src/domains/platform/datalink/predicates.ts | 295 ++++ src/domains/platform/datalink/records.ts | 497 ++++++ src/domains/platform/datalink/services.ts | 1442 +---------------- .../platform/workflow/README.workflow.md | 18 + src/domains/platform/workflow/catalog.ts | 125 ++ .../platform/workflow/configuration.ts | 210 +++ src/domains/platform/workflow/debug.ts | 151 ++ src/domains/platform/workflow/diff.ts | 298 ++++ src/domains/platform/workflow/execution.ts | 135 ++ src/domains/platform/workflow/queries.ts | 206 +++ src/domains/platform/workflow/services.ts | 1141 +------------ src/domains/platform/workflow/types.ts | 2 +- .../platform/workflow/watch/README.watch.md | 2 +- .../platform/workflow/watch/tracker.ts | 2 +- 27 files changed, 2811 insertions(+), 2511 deletions(-) create mode 100644 docs/reviews/2026-10-30-platform-subdomains.md create mode 100644 src/domains/platform/datalink/audit.ts create mode 100644 src/domains/platform/datalink/predicates.ts create mode 100644 src/domains/platform/datalink/records.ts create mode 100644 src/domains/platform/workflow/catalog.ts create mode 100644 src/domains/platform/workflow/configuration.ts create mode 100644 src/domains/platform/workflow/debug.ts create mode 100644 src/domains/platform/workflow/diff.ts create mode 100644 src/domains/platform/workflow/execution.ts create mode 100644 src/domains/platform/workflow/queries.ts diff --git a/AGENTS.md b/AGENTS.md index f1fb0b4..4b37b92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,7 @@ CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/h - `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`) - `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表 - 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts` +- 自建应用平台统一位于 `domains/platform/`,applications、datalink、workflow 分别拥有自己的模型、传输与服务出口;applications 不反向依赖另外两者,DataLink 不依赖 workflow,跨子模块不得直接调用 api。 - `domains/**/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入 - `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/` - 所有本地 SQLite 持久化(审批引擎、多级缓存、事件轮询去重、工作流错误指纹)统一收敛至 `core/db/` 并通过版本迁移管理 diff --git a/docs/modules/platform.md b/docs/modules/platform.md index b43437a..3641554 100644 --- a/docs/modules/platform.md +++ b/docs/modules/platform.md @@ -59,7 +59,7 @@ MCP 调用方式统一为 `hose_cli` 的 `command` 参数传入下列命令。 | `workflow check` | 扫描错误管道并持久化去重提醒 | EKB + Piper + 本地 | | `workflow toggle/publish` | 切换启停状态 | Piper | -统计、配额、DSL、员工与采样等底层能力由 `src/domains/platform/workflow/services.ts` 暴露,不存在同名的独立 MCP 工具。完整命令语义见 [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) 和 [DataLink 说明](../../src/domains/platform/datalink/README.datalink.md)。 +统计、配额、DSL、员工与采样等工作流专属能力由 `src/domains/platform/workflow/services.ts` 暴露,不存在同名的独立 MCP 工具。完整命令语义见 [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) 和 [DataLink 说明](../../src/domains/platform/datalink/README.datalink.md)。 ## 服务层聚合能力 @@ -94,3 +94,12 @@ bun run export:workflow-schema - `Workflow.state = 1` 为启用,`0` 为停用。 - `levelIndex` 表示节点在流程树中的层级坐标,如 `[6, 1, 0]` 表示第 6 个顶级节点下的第 1 个子节点下的第 0 个节点。 - 控制节点(`every` / `condition`)内部有 `tasks` 子列表,需要递归遍历。 + + +## 子模块所有权与维护 + +应用基础/详情模型统一位于 [applications/types.ts](../../src/domains/platform/applications/types.ts),应用服务由 applications 提供;对象、字段、记录由 DataLink 提供;工作流的配置和执行模型由 workflow 提供。CLI 的 platform、datalink、workflow 及工作台 app 命令保留原有入口语义。 + +[Workflow 服务](../../src/domains/platform/workflow/services.ts) 是显式出口,查询、配置、执行、差异、调试及节点目录分别实现;[DataLink 服务](../../src/domains/platform/datalink/services.ts) 将记录操作、表达式和审计分开。内部实现不反向导入聚合出口,避免循环。 + +applications 不依赖 DataLink 或 workflow,DataLink 不依赖 workflow。入口层不得直接访问任意深度的域 API;平台内部跨子模块只能使用模型或业务服务。以上规则以及包含类型导入的循环检查由架构测试执行。 diff --git a/docs/reviews/2026-10-30-platform-subdomains.md b/docs/reviews/2026-10-30-platform-subdomains.md new file mode 100644 index 0000000..d3016d1 --- /dev/null +++ b/docs/reviews/2026-10-30-platform-subdomains.md @@ -0,0 +1,54 @@ +# 2026-10-30 应用平台子模块整理完成报告 + +## 范围与交付 + +以 `3345ce9` 为业务整理基线,按用户确认的三个阶段实施。应用元数据、业务对象数据和工作流统一归入 `src/domains/platform/` 的 applications、datalink、workflow 子模块。没有将工作流提升为顶层域,也没有改变 Core、工作台菜单、应用商店或协助平台的业务归属。 + +阶段 A 提交 `edf300b`,阶段 B 提交 `4e03c9b`;阶段 C 为本报告所在提交。顶层域由 15 个变为 14 个。没有发布版本、修改全局安装或执行真实企业数据操作。 + +## 实际修改及前后行为 + +| 内容 | 修改及原因 | 复查位置 | +|---|---|---| +| 应用所有权 | 两处应用列表和应用模型统一归 applications;启用应用列表共用请求实现,基础和详情投影保持各自语义 | [api.ts](../../src/domains/platform/applications/api.ts)、[types.ts](../../src/domains/platform/applications/types.ts)、[兼容测试](../../src/domains/platform/applications/application-contract.test.ts) | +| 数据能力下沉 | 原顶层 DataLink 归 platform/datalink,应用模型不再由数据子模块定义;记录、表达式和审计分开 | [DataLink 说明](../../src/domains/platform/datalink/README.datalink.md) | +| 工作流完整归位 | 原 platform 根 api/types/services、执行上下文与测试移入 workflow;配置、查询、执行、差异、调试、节点目录分别实现 | [Workflow 说明](../../src/domains/platform/workflow/README.workflow.md) | +| 入口迁移 | CLI、probe、SDK 和生成脚本使用新归属路径,保留命令、别名、确认、返回结构和公共 SDK 导出名 | [sdk.ts](../../src/sdk.ts)、[CLI 命令层](../../src/cli/commands/README.commands.md)、[Schema 导出](../../scripts/generate/export-workflow-schema.ts) | +| 分层卡点 | 禁止入口访问任意深度域 API,禁止跨子模块直接访问 API;applications 不反向依赖,DataLink 不依赖 workflow;含类型导入的文件级循环检查 | [架构边界测试](../../src/cli/architecture-boundaries.test.ts) | +| 导航与证据 | 同步总纲、域数量、活跃 README、SDK 示例路径及当前接口清单源码定位;历史报告和证据保留当时内容 | [AGENTS.md](../../AGENTS.md)、[域总览](../../src/domains/README.domains.md)、[模块说明](../modules/platform.md)、[接口清单](../../specs/hose-close-api/endpoints.md) | + +### 关键兼容行为 + +- `listBasicPlatforms` 保留基础视图,剥离未建模字段且缺少 items 时拒绝;`listPlatforms` 保留详情扩展、admin 清洗和空值兼容。没有把两种模型简单互换。 +- 公开 `hose-use/sdk` 导出名称集合与 `3345ce9` 一致,原 `DatalinkPlatformDetail` 名称由 applications 拥有并维持 SDK 同名出口。 +- 原工作流 44 个、DataLink 37 个服务函数的函数体在职责拆分前后逐字节一致;内部依赖改为直接引用所属实现,服务门面只保留显式出口。 +- 工作流的服务门面由原 1094 行变为 81 行;DataLink 由原 1426 行变为 53 行;applications 门面为 24 行。算法分散到有明确职责的文件中,没有只做路径搬迁。 +- 三份生成规范与 `3345ce9` 逐字节一致:`specs/openapi.json`、`specs/openapi.raw.json`、`specs/workflow-schema.json`。 + +## 依赖环处理与方案落实 + +新增文件级检查发现并消除了两条旧环:watch/tracker 经 services 聚合出口绕回自身,现直接依赖 execution;工作流报告类型经 branch/index 回到类型模块,现直接依赖 branch/types。保留返回结构,不删除类型约束,也不通过忽略 type import 使检查通过。 + +DataLink 内部为 predicates/audit 使用 records 的字段读取及归一化辅助,未引入记录模块反向依赖服务门面。原私有根路径不保留转发文件;仓库内调用均迁移,旧私有路径再次出现会由边界测试拦截。 + +实际实施符合三阶段范围。应用查询特征回归确认的兼容差异全部保留,包括旧全量接口收到裸数组时归为空列表的行为;本轮没有借整理修正该既有问题。阶段 B 的新增空白尾行在阶段 C 清理,最终 diff 检查通过。 + +## 实际验证 + +| 阶段 | 全量测试 | 类型与版本检查 | +|---|---|---| +| A:兼容与边界 | 943 通过、0 失败,123 文件、4544 次断言 | 通过 | +| B:归属与调用迁移 | 943 通过、0 失败,123 文件、4544 次断言 | 通过 | +| C:拆分与文件级循环检查 | 943 通过、0 失败,123 文件、4545 次断言 | 通过 | + +- 全量测试使用临时配置、账号/Token、企业目录和 SQLite 路径;未执行真实企业写入。 +- `bun run openapi:all`、`bun run export:workflow-schema` 成功,产物与原始基线一致。 +- 当前平台二进制构建与产物 CLI/MCP 验证成功;MCP bundle 构建、插件验证和归档打包成功。 +- 公共 SDK 示例编译包含在全量回归中;命令、保存版本冲突、部分成功恢复、数据安全编辑/过滤与流式输出等既有回归保持通过。 +- 活跃文档本地链接零断链;README 审计 81 个目录,27 个必需目录全部通过;`git diff --check` 和生成脚本/测试的独立严格类型检查通过;原始验证日志保存在 Git 忽略目录 `.drafts/platform-reorganization-20261030/`。 + +## 限制与需要注意的迁移 + +仅承诺已有公共 SDK 和 CLI 兼容。直接导入旧 `src/domains/datalink/*` 或 platform 根 api/services/types 的个人脚本,需要迁移到新内部路径或公共 SDK。 + +没有在 Windows/Linux 主机执行完整发布矩阵;没有重做认证基础设施、提取独立 SDK 运行时或调整数据库。工作流和对象关联仍在应用平台业务域内,API 命令并未变成通用跨产品工作流引擎。目录规模与函数体一致性是辅助证据,不替代完整的业务回归或所有租户响应变体验收。 diff --git a/docs/reviews/README.reviews.md b/docs/reviews/README.reviews.md index 9405550..83385a6 100644 --- a/docs/reviews/README.reviews.md +++ b/docs/reviews/README.reviews.md @@ -12,6 +12,7 @@ | [2026-10-29 业务域契约整改](./2026-10-29-domain-contract-fixes.md) | 身份/字段歧义、单据写入、工作流部分保存与认证重放 | | [2026-10-30 脚本整理](./2026-10-30-scripts-reorganization.md) | 脚本分组、调用路径及构建验证 | | [2026-10-30 Schema 导出修复](./2026-10-30-workflow-schema-export-fix.md) | 告警字段导出视图与生成文件同步 | +| [2026-10-30 应用平台子模块整理](./2026-10-30-platform-subdomains.md) | 应用、业务对象与工作流的归属、服务拆分和兼容验收 | | [2026-10-30 README 校验器](./2026-10-30-readme-checker.md) | 权重规则、首次审计与文档缺口 | [2026-10-25 证据目录](./2026-10-25-codex-review-evidence) 保留当次日志,日志中的旧路径和历史错误不随目录迁移改写。 diff --git a/specs/hose-close-api/endpoints.md b/specs/hose-close-api/endpoints.md index d8eeacd..7dd9689 100644 --- a/specs/hose-close-api/endpoints.md +++ b/specs/hose-close-api/endpoints.md @@ -45,36 +45,36 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth? | # | Method | Path | 请求 | 响应 | 来源 | 抓包 | |---|---|---|---|---|---|---| -| P01 | GET | `EKB /api/v2/datalink/platform/search` | Query `{scope:"enable",corpId}` | `{items:[Platform]}` | `src/domains/platform/workflow/api.ts:82`、`src/domains/platform/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/workflow/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/workflow/api.ts:112` | 否 | -| P04 | GET | `PIPER /api/easo/charge` | 无 | `{code,msg,data:{corporationId,status,orderType,total,used,remaining}}` | `src/domains/platform/workflow/api.ts:121` | 否 | -| P05 | GET | `PIPER /api/easo/pipelines/{pipelineId}` | 无 | `{code,msg,data:WorkflowDetail}`;结构见 `schemas/workflow-detail.schema.json` | `src/domains/platform/workflow/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/workflow/api.ts:141`、`src/domains/platform/workflow/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/workflow/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/workflow/api.ts:163` | 否 | -| P09 | POST | `PIPER /api/easo/pipelines` | body 为工作流对象 | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/workflow/api.ts:173` | 否 | -| P10 | DELETE | `PIPER /api/easo/pipelines/{id}` | 无 | 读取并丢弃响应文本;代码视为成功 | `src/domains/platform/workflow/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/workflow/api.ts:194` | 否 | -| P12 | GET | `PIPER /api/easo/pipelines/snapshot/{snapshotId}` | 无 | `{code,msg,data:WorkflowSnapshot}`;`inputs`/`outputs` 为 JSON 字符串 | `src/domains/platform/workflow/api.ts:207` | 见 `_tmp-captured` | -| P13 | GET | `PIPER /api/easo/snapshots/{snapshotId}` | 无 | 同 P12;P12 失败后的 fallback | `src/domains/platform/workflow/api.ts:208` | 否 | -| P14 | GET | `PIPER /api/easo/pipelines/{pipelineId}/snapshots/{snapshotId}` | 无 | 同 P12;P12/P13 失败后的 fallback | `src/domains/platform/workflow/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/workflow/api.ts:234` | 否 | -| P16 | PUT | `PIPER /api/easo/pipelines/state/{pipelineId}` | Query `{state:"0"|"1"}` | 2xx 即成功;响应体忽略 | `src/domains/platform/workflow/api.ts:253` | legacy | -| P17 | GET | `PIPER /api/easo/jobs/running` | Query `{pipelineId,runType:"DEBUG"|"PROD"}` | `{code,msg,data:WorkflowJob|WorkflowJob[]}` | `src/domains/platform/workflow/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/workflow/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/workflow/api.ts:294` | 见 `_tmp-captured`(CLI 聚合) | -| P20 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level/failed` | 无 | `{code,msg,data:ExecutionPage|TaskExecution[]}` | `src/domains/platform/workflow/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/workflow/api.ts:333` | 否 | -| P22 | GET | `PIPER /api/easo/executions/{executionId}/logs` | 无 | `{code,msg,data:ExecutionLog[]|{items:[ExecutionLog]}}` | `src/domains/platform/workflow/api.ts:347` | 否 | -| P23 | GET | `PIPER /api/easo/dsl/all` | 无 | `{data:NodeDef[]}` 或 `{data:{action:[],control:[],trigger:[]}}`;NodeDef 见下 | `src/domains/platform/workflow/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/workflow/api.ts:400` | legacy | -| P25 | GET | `PIPER /api/webhook/{pipelineId}` | 无 | `{code,msg,data:{id,pipelineId,url,active}}` | `src/domains/platform/workflow/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/workflow/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/workflow/api.ts:433` | 否 | -| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:|{id}|{jobId}}` | `src/domains/platform/workflow/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/workflow/api.ts:486` | 否 | -| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/api.ts:511` | 否 | +| P01 | GET | `EKB /api/v2/datalink/platform/search` | Query `{scope:"enable",corpId}` | `{items:[Platform]}` | `src/domains/platform/applications/api.ts:9`、`src/domains/platform/applications/api.ts:15`、`src/domains/platform/applications/api.ts:37` | 否 | +| 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/workflow/api.ts:92` | legacy | +| P03 | GET | `PIPER /api/easo/stats` | Query `{platformId}` | `{code,msg,data:{total,completed,failed,started,pipelineOpenCount,pipelineCloseCount,pipelineAllCount}}` | `src/domains/platform/workflow/api.ts:108` | 否 | +| P04 | GET | `PIPER /api/easo/charge` | 无 | `{code,msg,data:{corporationId,status,orderType,total,used,remaining}}` | `src/domains/platform/workflow/api.ts:118` | 否 | +| P05 | GET | `PIPER /api/easo/pipelines/{pipelineId}` | 无 | `{code,msg,data:WorkflowDetail}`;结构见 `schemas/workflow-detail.schema.json` | `src/domains/platform/workflow/api.ts:127` | 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/workflow/api.ts:137`、`src/domains/platform/workflow/configuration.ts:26` | 见 `_tmp-captured` | +| P07 | PUT | `PIPER /api/easo/pipelines/{id}/chooses` | 无 body | `{code,msg,data:[{key,label,displayName,choose}]}`;`choose` 为递归选择器树 | `src/domains/platform/workflow/api.ts:151`、`src/domains/platform/workflow/configuration.ts:26` | 见 `_tmp-captured` | +| P08 | PUT | `PIPER /api/easo/pipelines/{id}/copy` | body 为 `WorkflowDetail`(复制后的详情) | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/workflow/api.ts:159` | 否 | +| P09 | POST | `PIPER /api/easo/pipelines` | body 为工作流对象 | `{code,msg,data:WorkflowDetail}` | `src/domains/platform/workflow/api.ts:170` | 否 | +| P10 | DELETE | `PIPER /api/easo/pipelines/{id}` | 无 | 检查 HTTP 状态与业务码;兼容空成功响应 | `src/domains/platform/workflow/api.ts:180` | 否 | +| P11 | GET | `PIPER /api/easo/pipelines/{id}/snapshots` | Query `{number,pageSize}` | `{code,msg,data:{number,size,totalPages,totalItems,items:[WorkflowSnapshot]}}` | `src/domains/platform/workflow/api.ts:189` | 否 | +| P12 | GET | `PIPER /api/easo/pipelines/snapshot/{snapshotId}` | 无 | `{code,msg,data:WorkflowSnapshot}`;`inputs`/`outputs` 为 JSON 字符串 | `src/domains/platform/workflow/api.ts:201` | 见 `_tmp-captured` | +| P13 | GET | `PIPER /api/easo/snapshots/{snapshotId}` | 无 | 同 P12;P12 失败后的 fallback | `src/domains/platform/workflow/api.ts:201` | 否 | +| P14 | GET | `PIPER /api/easo/pipelines/{pipelineId}/snapshots/{snapshotId}` | 无 | 同 P12;P12/P13 失败后的 fallback | `src/domains/platform/workflow/api.ts:201` | 否 | +| 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/workflow/api.ts:224` | 否 | +| P16 | PUT | `PIPER /api/easo/pipelines/state/{pipelineId}` | Query `{state:"0"|"1"}` | 2xx 即成功;响应体忽略 | `src/domains/platform/workflow/api.ts:249` | legacy | +| P17 | GET | `PIPER /api/easo/jobs/running` | Query `{pipelineId,runType:"DEBUG"|"PROD"}` | `{code,msg,data:WorkflowJob|WorkflowJob[]}` | `src/domains/platform/workflow/api.ts:262` | legacy | +| P18 | GET | `PIPER /api/easo/jobs/{jobId}` | 无 | `{code,msg,data:JobDetail}`;Job 字段见 `schemas/workflow-job-execution.schema.json` | `src/domains/platform/workflow/api.ts:282` | 见 `_tmp-captured`(CLI 聚合) | +| P19 | GET | `PIPER /api/easo/jobs/{jobId}/execution` | Query `{number,pageSize}` | `{code,msg,data:TaskExecution[]|ExecutionPage}` | `src/domains/platform/workflow/api.ts:290` | 见 `_tmp-captured`(CLI 聚合) | +| P20 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level/failed` | 无 | `{code,msg,data:ExecutionPage|TaskExecution[]}` | `src/domains/platform/workflow/api.ts:308` | 见 `_tmp-captured`(CLI 聚合) | +| P21 | GET | `PIPER /api/easo/jobs/{jobId}/execution/level` | Query `{parentId,number,pageSize}` | `{code,msg,data:ExecutionPage}` | `src/domains/platform/workflow/api.ts:329` | 否 | +| P22 | GET | `PIPER /api/easo/executions/{executionId}/logs` | 无 | `{code,msg,data:ExecutionLog[]|{items:[ExecutionLog]}}` | `src/domains/platform/workflow/api.ts:344` | 否 | +| P23 | GET | `PIPER /api/easo/dsl/all` | 无 | `{data:NodeDef[]}` 或 `{data:{action:[],control:[],trigger:[]}}`;NodeDef 见下 | `src/domains/platform/workflow/api.ts:361`、`src/domains/platform/workflow/api.ts:379` | legacy | +| P24 | GET | `PIPER /api/easo/common/staffs` | Query `{external:"true"|"false"}` | `{code,msg,data:[{id,name,email?,department?}]}` | `src/domains/platform/workflow/api.ts:397` | legacy | +| P25 | GET | `PIPER /api/webhook/{pipelineId}` | 无 | `{code,msg,data:{id,pipelineId,url,active}}` | `src/domains/platform/workflow/api.ts:409` | 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/workflow/api.ts:419`、`src/domains/platform/workflow/api.ts:468` | 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/workflow/api.ts:429` | 否 | +| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:|{id}|{jobId}}` | `src/domains/platform/workflow/api.ts:444` | 否 | +| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/workflow/api.ts:481` | 否 | +| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/api.ts:498` | 否 | `Platform` 代码字段(`src/domains/platform/workflow/types.ts:5`): diff --git a/specs/hose-close-api/schemas/workflow-detail.schema.json b/specs/hose-close-api/schemas/workflow-detail.schema.json index e8faa8a..9d64dea 100644 --- a/specs/hose-close-api/schemas/workflow-detail.schema.json +++ b/specs/hose-close-api/schemas/workflow-detail.schema.json @@ -4,7 +4,7 @@ "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/workflow/types.ts:273 (WorkflowDetailSchema)", + "code-derived: src/domains/platform/workflow/types.ts:252 (WorkflowDetailSchema)", "reference: _tmp-captured/raw/PUT-api-easo-pipelines-id.json" ], "type": "object", diff --git a/specs/hose-close-api/schemas/workflow-job-execution.schema.json b/specs/hose-close-api/schemas/workflow-job-execution.schema.json index 047f5d5..1d3f0b7 100644 --- a/specs/hose-close-api/schemas/workflow-job-execution.schema.json +++ b/specs/hose-close-api/schemas/workflow-job-execution.schema.json @@ -4,7 +4,7 @@ "title": "Workflow job execution", "description": "Piper 任务实例与节点执行数据。/execution 与 /execution/level/failed 的 data 可能是数组,也可能是分页对象 {number,size,totalPages,totalItems,items}。", "x-source": [ - "code-derived: src/domains/platform/workflow/types.ts:360", + "code-derived: src/domains/platform/workflow/types.ts:339", "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution.json", "reference: _tmp-captured/raw/GET-api-easo-jobs-id-execution-completed.json" ], diff --git a/specs/hose-close-api/schemas/workflow-snapshot.schema.json b/specs/hose-close-api/schemas/workflow-snapshot.schema.json index 0c0f9ce..5d2f616 100644 --- a/specs/hose-close-api/schemas/workflow-snapshot.schema.json +++ b/specs/hose-close-api/schemas/workflow-snapshot.schema.json @@ -4,7 +4,7 @@ "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/workflow/types.ts:307 (WorkflowSnapshotSchema)", + "code-derived: src/domains/platform/workflow/types.ts:286 (WorkflowSnapshotSchema)", "reference: _tmp-captured/raw/GET-api-easo-pipelines-snapshot-id.json" ], "type": "object", diff --git a/src/cli/architecture-boundaries.test.ts b/src/cli/architecture-boundaries.test.ts index f285be5..a6d0963 100644 --- a/src/cli/architecture-boundaries.test.ts +++ b/src/cli/architecture-boundaries.test.ts @@ -90,13 +90,15 @@ describe("Architecture Layering Boundaries", () => { }); test("platform submodules respect ownership and have no cross-module cycles", () => { - const graph = new Map>(), violations: string[] = []; + const graph = new Map>(), fileGraph = new Map>(), violations: string[] = []; for (const file of collectTsFiles(join(SRC_ROOT, "domains", "platform"))) { const from = relative(SRC_ROOT, file).replaceAll("\\", "/").replace(/\.ts$/, ""); const source = platformModule(from); + fileGraph.set(from, new Set()); for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) { const target = resolveImportRelativeToSrc(file, specifier); if (!target) continue; + if (target.startsWith("domains/platform/")) fileGraph.get(from)!.add(target); if (platformDependencyViolation(from, target)) violations.push(`${from} -> ${target}`); const destination = platformModule(target); if (source && destination && source !== destination) { @@ -107,6 +109,7 @@ describe("Architecture Layering Boundaries", () => { } expect(violations).toEqual([]); expect(findCycles(graph)).toEqual([]); + expect(findCycles(fileGraph)).toEqual([]); }); test("bill Session HTTP calls stay in the transport module", () => { @@ -131,8 +134,8 @@ describe("Architecture Layering Boundaries", () => { } 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))$/; + test("platform imports use owned submodules and reject retired private paths", () => { + const legacy = /^(?:domains\/datalink(?:\/|$)|domains\/platform\/(?:api|services|types|execution-context|analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$)/; const violations: string[] = []; for (const file of collectTsFiles(SRC_ROOT, true)) { for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) { diff --git a/src/domains/platform/applications/api.ts b/src/domains/platform/applications/api.ts index fac3307..9ffc7d1 100644 --- a/src/domains/platform/applications/api.ts +++ b/src/domains/platform/applications/api.ts @@ -71,4 +71,3 @@ export async function getPlatform( const json = asRecord(await response.json()); return DatalinkPlatformDetailSchema.parse(sanitizePlatformDetail(json.value ?? json.data ?? json)); } - diff --git a/src/domains/platform/applications/services.ts b/src/domains/platform/applications/services.ts index 73c6275..af2d623 100644 --- a/src/domains/platform/applications/services.ts +++ b/src/domains/platform/applications/services.ts @@ -22,4 +22,3 @@ export async function resolvePlatform( ); return found ? api.getPlatform(client, corpId, found.id) : undefined; } - diff --git a/src/domains/platform/datalink/README.datalink.md b/src/domains/platform/datalink/README.datalink.md index fb83cbe..11269c1 100644 --- a/src/domains/platform/datalink/README.datalink.md +++ b/src/domains/platform/datalink/README.datalink.md @@ -6,10 +6,13 @@ DataLink 是应用平台的数据子模块,负责业务对象、字段定义 ```text src/domains/platform/datalink/ -├── types.ts # 应用详情、对象字段、记录分页与权限模型 -├── api.ts # DataLink HTTP 传输层 -├── services.ts # 应用/对象名称解析与查询表达式辅助、SDK 门面 -└── fields.ts # 读取与写入共用的唯一字段解析 +├── types.ts # 业务对象、字段、记录与对象级权限模型 +├── api.ts # 对象/记录 HTTP 传输与响应校验 +├── services.ts # 显式业务出口,不反向参与内部依赖 +├── records.ts # 对象解析、分页/流式记录、归一化与安全批量编辑 +├── predicates.ts # 服务端过滤表达式、客户端谓词和声明式赋值解析 +├── audit.ts # 统计、台账审计、聚合与连续性检查 +└── fields.ts # 读写共用的唯一字段解析 ``` ## 查询链路 @@ -21,7 +24,7 @@ platform/search └─ searchPlatformDataLinkWithChild/{entityId} 业务记录 ``` -应用列表和应用详情使用 EKB client。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。 +应用列表、详情和应用级权限元数据由 applications 模块通过 EKB client 提供。记录查询的 `filterBy` 原样支持 DataLink 过滤表达式;CLI 另提供 `--keyword`,自动生成名称/编码模糊查询。 ## CLI diff --git a/src/domains/platform/datalink/audit.ts b/src/domains/platform/datalink/audit.ts new file mode 100644 index 0000000..8a7d6dc --- /dev/null +++ b/src/domains/platform/datalink/audit.ts @@ -0,0 +1,641 @@ +import type { DatalinkEntity, DatalinkField, DatalinkRecord, AggregateFieldStats, GroupAggregateResult, LedgerAggregateReport, ContinuityIssue, LedgerContinuityReport, DatalinkRecordStats } from "./types.js"; +import { normalizeDatalinkRecord, extractRefIdAndName, resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js"; + + +/** + * 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。 + * 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。 + */ +export function calculateEntityRecordStats( + records: Iterable, + entity?: DatalinkEntity, + explicitTotal?: number +): DatalinkRecordStats { + let total = 0; + let activeCount = 0; + let inactiveCount = 0; + + const namesMap = new Map(); + const patternsMap = new Map(); + + let earliestCreate: number | null = null; + let latestUpdate: number | null = null; + + for (const raw of records) { + total++; + const norm = normalizeDatalinkRecord(raw, entity); + if (norm.active) activeCount++; + else inactiveCount++; + + if (norm.createTime && typeof norm.createTime === "number") { + if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime; + } + if (norm.updateTime && typeof norm.updateTime === "number") { + if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime; + } + + // 统计名称重名与状态交叉 + if (norm.name) { + if (!namesMap.has(norm.name)) { + namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 }); + } + const nStats = namesMap.get(norm.name)!; + nStats.total++; + if (norm.active) nStats.active++; + else nStats.inactive++; + } + + // 统计编码结构聚类 + const code = norm.code || "EMPTY"; + const pattern = code + .replace(/\d{8}/g, "YYYYMMDD") + .replace(/\d{6}/g, "SEQ6") + .replace(/\d+/g, "N"); + + if (!patternsMap.has(pattern)) { + patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 }); + } + const pStats = patternsMap.get(pattern)!; + pStats.count++; + if (norm.active) pStats.activeCount++; + else pStats.inactiveCount++; + } + + const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total; + const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%"; + + let duplicateNamesCount = 0; + let mixedStatusNamesCount = 0; + for (const n of namesMap.values()) { + if (n.total > 1) duplicateNamesCount++; + if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++; + } + + const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count); + + const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null); + + return { + total: finalTotal, + activeCount, + inactiveCount, + activeRate, + uniqueNames: namesMap.size, + duplicateNamesCount, + mixedStatusNamesCount, + codePatterns, + earliestCreateTime: formatDate(earliestCreate), + latestUpdateTime: formatDate(latestUpdate), + }; +} + + +export interface DatalinkAuditIssue { + recordId: string; + recordCode: string; + recordName: string; + active: boolean; + type: + | "MISSING_FIELD" + | "DISABLED_REFERENCE" + | "CROSS_LEDGER_MISSING_SYNC" + | "CROSS_LEDGER_MISMATCH"; + field: string; + fieldLabel: string; + message: string; + linkedField?: string; + linkedFieldLabel?: string; + linkedRecordId?: string; + actualId?: string; + actualName?: string; + expectedId?: string; + expectedName?: string; +} + + +export interface DatalinkAuditReport { + entityId: string; + entityName: string; + totalRecords: number; + auditedRecords: number; + healthyRecords: number; + affectedRecordCount: number; + issueCount: number; + summary: { + missingFieldCount: number; + disabledReferenceCount: number; + crossLedgerMissingSyncCount: number; + crossLedgerMismatchCount: number; + }; + issues: DatalinkAuditIssue[]; + suggestedPatches: Array<{ + id: string; + code: string; + name: string; + form: Record; + reason: string; + }>; +} + + +function isEmptyFieldValue(value: unknown): boolean { + if (value === undefined || value === null || value === "") return true; + if (Array.isArray(value)) return value.length === 0; + if (typeof value === "object") { + const obj = value as Record; + if ("id" in obj) { + return obj.id === undefined || obj.id === null || obj.id === ""; + } + if ("standard" in obj) { + return obj.standard === undefined || obj.standard === null || obj.standard === ""; + } + return Object.keys(obj).length === 0; + } + return false; +} + + +/** + * 对业务对象记录集合执行数据健康度体检: + * 1. 必填/关键字段缺失检查 (MISSING_FIELD) + * 2. 关联对象/档案停用检查 (DISABLED_REFERENCE) + * 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH) + */ +export function auditEntityRecords( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {} +): DatalinkAuditReport { + const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id; + const nameField = entity.fields.find( + (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") + ); + const codeField = entity.fields.find( + (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") + ); + + // 解析需要检查缺失的字段集合 + const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean); + const fieldsToCheck: DatalinkField[] = + explicitSelectors.length > 0 + ? explicitSelectors.map((selector) => { + const found = entity.fields.find( + (f) => + f.name === selector || + f.label === selector || + f.name === `E_${bareEntityId}_${selector}` + ); + return ( + found ?? { + name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`, + label: selector, + type: "text", + } + ); + }) + : entity.fields.filter( + (f) => + f.optional === false || + f.type === "dimension" || + f.type === "dataLink" + ); + + const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink"); + const dimensionFields = entity.fields.filter((f) => f.type === "dimension"); + + const issues: DatalinkAuditIssue[] = []; + const suggestedPatchesMap = new Map< + string, + { id: string; code: string; name: string; form: Record; reasons: string[] } + >(); + const affectedRecordIds = new Set(); + let auditedRecords = 0; + + let missingFieldCount = 0; + let disabledReferenceCount = 0; + let crossLedgerMissingSyncCount = 0; + let crossLedgerMismatchCount = 0; + + for (const rawRecord of records) { + const dl = + rawRecord.dataLink && + typeof rawRecord.dataLink === "object" && + !Array.isArray(rawRecord.dataLink) + ? (rawRecord.dataLink as Record) + : (rawRecord as Record); + const recordId = String(dl.id ?? rawRecord.id ?? ""); + const active = (dl.active ?? rawRecord.active) !== false; + if (options.activeOnly && !active) continue; + + auditedRecords++; + const recordName = String( + dl.name ?? + dl["名称"] ?? + (nameField ? dl[nameField.name] : undefined) ?? + dl[`E_${bareEntityId}_name`] ?? + "" + ); + const recordCode = String( + dl.code ?? + dl["编码"] ?? + (codeField ? dl[codeField.name] : undefined) ?? + dl[`E_${bareEntityId}_code`] ?? + "" + ); + + const getFieldVal = (field: DatalinkField): unknown => + dl[field.name] ?? + dl[`E_${bareEntityId}_${field.name}`] ?? + (dl.form && typeof dl.form === "object" + ? (dl.form as Record)[field.name] + : undefined) ?? + dl[field.label]; + + // 1. 必填/关键字段缺失检查 + for (const field of fieldsToCheck) { + const val = getFieldVal(field); + if (isEmptyFieldValue(val)) { + missingFieldCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "MISSING_FIELD", + field: field.name, + fieldLabel: field.label || field.name, + message: `字段 [${field.label || field.name}] (${field.name}) 为空`, + }); + } + } + + // 2. 关联对象/档案停用检查 + for (const field of entity.fields) { + if (field.type !== "dimension" && field.type !== "dataLink") continue; + const val = getFieldVal(field); + const items = Array.isArray(val) ? val : val ? [val] : []; + for (const item of items) { + const refInfo = extractRefIdAndName(item); + if (refInfo.active === false) { + disabledReferenceCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "DISABLED_REFERENCE", + field: field.name, + fieldLabel: field.label || field.name, + actualId: refInfo.id, + actualName: refInfo.name, + message: `字段 [${field.label || field.name}] 引用的${ + field.type === "dataLink" ? "业务对象记录" : "维度档案" + } [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`, + }); + } + } + } + + // 3. 跨表关联同名维度一致性检查 + for (const linkField of dataLinkFields) { + const linkVal = getFieldVal(linkField); + if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue; + const linkObj = linkVal as Record; + const parentDl = + linkObj.data && + typeof linkObj.data === "object" && + (linkObj.data as Record).dataLink && + typeof (linkObj.data as Record).dataLink === "object" + ? ((linkObj.data as Record).dataLink as Record) + : linkObj.dataLink && typeof linkObj.dataLink === "object" + ? (linkObj.dataLink as Record) + : linkObj; + const linkedRecordId = String(parentDl.id ?? linkObj.id ?? ""); + + for (const dimField of dimensionFields) { + const entityPrefix = `E_${bareEntityId}_`; + const suffix = dimField.name.startsWith(entityPrefix) + ? dimField.name.slice(entityPrefix.length) + : dimField.name.replace(/^E_[^_]+_/, ""); + const parentKey = Object.keys(parentDl).find( + (k) => + k === dimField.label || + k === suffix || + k.endsWith(`_${suffix}`) || + (Boolean(dimField.label) && k.endsWith(`_${dimField.label}`)) + ); + if (!parentKey) continue; + + const parentRef = extractRefIdAndName(parentDl[parentKey]); + if (!parentRef.id) continue; + + const childRef = extractRefIdAndName(getFieldVal(dimField)); + if (!childRef.id) { + crossLedgerMissingSyncCount++; + affectedRecordIds.add(recordId); + const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${ + linkField.label || linkField.name + }] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${ + parentRef.id + }),建议回填修复`; + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "CROSS_LEDGER_MISSING_SYNC", + field: dimField.name, + fieldLabel: dimField.label || dimField.name, + linkedField: linkField.name, + linkedFieldLabel: linkField.label || linkField.name, + linkedRecordId, + expectedId: parentRef.id, + expectedName: parentRef.name, + message: reason, + }); + + const existingPatch = suggestedPatchesMap.get(recordId) ?? { + id: recordId, + code: recordCode, + name: recordName, + form: {}, + reasons: [], + }; + existingPatch.form[dimField.name] = parentRef.id; + existingPatch.reasons.push( + `${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})` + ); + suggestedPatchesMap.set(recordId, existingPatch); + } else if (childRef.id !== parentRef.id) { + crossLedgerMismatchCount++; + affectedRecordIds.add(recordId); + issues.push({ + recordId, + recordCode, + recordName, + active, + type: "CROSS_LEDGER_MISMATCH", + field: dimField.name, + fieldLabel: dimField.label || dimField.name, + linkedField: linkField.name, + linkedFieldLabel: linkField.label || linkField.name, + linkedRecordId, + actualId: childRef.id, + actualName: childRef.name, + expectedId: parentRef.id, + expectedName: parentRef.name, + message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${ + childRef.name || childRef.id + }] (${childRef.id}) 与关联 [${ + linkField.label || linkField.name + }] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${ + parentRef.id + }) 不一致`, + }); + } + } + } + } + + const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({ + id: item.id, + code: item.code, + name: item.name, + form: item.form, + reason: item.reasons.join("; "), + })); + + return { + entityId: entity.id, + entityName: entity.name, + totalRecords: options.total ?? records.length, + auditedRecords, + healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size), + affectedRecordCount: affectedRecordIds.size, + issueCount: issues.length, + summary: { + missingFieldCount, + disabledReferenceCount, + crossLedgerMissingSyncCount, + crossLedgerMismatchCount, + }, + issues, + suggestedPatches, + }; +} + + +/** + * 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组) + */ +export function aggregateRecordFields( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { + fields: string[]; + groupBy?: string; + } +): LedgerAggregateReport { + const resolvedFields = options.fields.map((f) => { + const resolved = resolveEntityField(entity, f); + return { + query: f, + field: resolved ?? { name: f, label: f, type: "number" }, + }; + }); + + const calcStats = (list: DatalinkRecord[]): Record => { + const stats: Record = {}; + for (const { query, field } of resolvedFields) { + let count = 0; + let sum = 0; + let min = Infinity; + let max = -Infinity; + + for (const r of list) { + const num = extractNumericFieldValue(r, field); + if (num !== null) { + count++; + sum += num; + if (num < min) min = num; + if (num > max) max = num; + } + } + + stats[query] = { + field: field.name, + fieldLabel: field.label || field.name, + count, + sum: Math.round(sum * 100) / 100, + avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0, + min: count > 0 ? min : 0, + max: count > 0 ? max : 0, + }; + } + return stats; + }; + + const overall = calcStats(records); + + let groups: GroupAggregateResult[] | undefined; + if (options.groupBy) { + const groupField = resolveEntityField(entity, options.groupBy) ?? { + name: options.groupBy, + label: options.groupBy, + type: "text", + }; + const groupMap = new Map(); + for (const r of records) { + const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)"); + const existing = groupMap.get(gVal); + if (existing) existing.push(r); + else groupMap.set(gVal, [r]); + } + + groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({ + groupValue, + count: groupRecords.length, + aggregates: calcStats(groupRecords), + })); + } + + return { + totalRecords: records.length, + overall, + groups, + }; +} + + +/** + * 台账序号连续性检查与期望基线数学核对 + */ +export function auditLedgerContinuityAndBaseline( + records: DatalinkRecord[], + entity: DatalinkEntity, + options: { + sequenceField?: string; + expectedValues?: Array<{ + field: string; + targetValue: number; + tolerance?: number; + }>; + } +): LedgerContinuityReport { + const issues: ContinuityIssue[] = []; + const outliers: LedgerContinuityReport["outliers"] = []; + + let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined; + + // 1. 序号连续性核查 + if (options.sequenceField) { + const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? { + name: options.sequenceField, + label: options.sequenceField, + type: "number", + }; + + const seqMap = new Map(); + const numbers: number[] = []; + + for (const r of records) { + const num = extractNumericFieldValue(r, resolvedSeqField); + if (num !== null) { + const intVal = Math.round(num); + numbers.push(intVal); + const existing = seqMap.get(intVal); + const rId = r.id || String(r.recordId || ""); + if (existing) existing.push(rId); + else seqMap.set(intVal, [rId]); + } + } + + if (numbers.length > 0) { + const min = Math.min(...numbers); + const max = Math.max(...numbers); + const missing: number[] = []; + const duplicates: number[] = []; + + for (let i = min; i <= max; i++) { + const count = seqMap.get(i)?.length ?? 0; + if (count === 0) { + missing.push(i); + issues.push({ + type: "MISSING_SEQUENCE", + field: resolvedSeqField.name, + message: `台账序号断层:缺少第 [${i}] 期记录`, + expected: i, + actual: null, + }); + } else if (count > 1) { + duplicates.push(i); + issues.push({ + type: "DUPLICATE_SEQUENCE", + field: resolvedSeqField.name, + message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`, + expected: 1, + actual: count, + }); + } + } + + sequenceSummary = { + field: resolvedSeqField.name, + fieldLabel: resolvedSeqField.label || resolvedSeqField.name, + min, + max, + expectedCount: max - min + 1, + actualCount: numbers.length, + missing, + duplicates, + }; + } + } + + // 2. 基线离群异常核对 + if (options.expectedValues && options.expectedValues.length > 0) { + for (const exp of options.expectedValues) { + const field = resolveEntityField(entity, exp.field) ?? { + name: exp.field, + label: exp.field, + type: "number", + }; + const tolerance = exp.tolerance ?? 0.05; + + for (const r of records) { + const val = extractNumericFieldValue(r, field); + if (val !== null) { + const diff = Math.abs(val - exp.targetValue); + if (diff > tolerance) { + const rId = r.id || String(r.recordId || ""); + outliers.push({ + recordId: rId, + field: field.name, + fieldLabel: field.label || field.name, + value: val, + expectedValue: exp.targetValue, + diff: Math.round(diff * 100) / 100, + }); + issues.push({ + type: "VALUE_OUTLIER", + recordId: rId, + field: field.name, + message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`, + expected: exp.targetValue, + actual: val, + }); + } + } + } + } + } + + return { + totalRecords: records.length, + sequenceSummary, + issues, + outliers, + }; +} diff --git a/src/domains/platform/datalink/predicates.ts b/src/domains/platform/datalink/predicates.ts new file mode 100644 index 0000000..9605115 --- /dev/null +++ b/src/domains/platform/datalink/predicates.ts @@ -0,0 +1,295 @@ +import { ValidationError } from "../../../core/errors.js"; +import type { DatalinkEntity, DatalinkField, DatalinkRecord } from "./types.js"; +import { resolveEntityField, extractRecordFieldValue, extractNumericFieldValue } from "./records.js"; + + +export interface BuildKeywordFilterOptions { + entity?: DatalinkEntity; + searchFields?: string[]; +} + + +/** + * 格式化服务端 filterBy 字段表达式。 + * 针对 DataLink 特性: + * - 动态业务字段(E_ 前缀)自动附加 form. 命名空间 + * - money 货币复合对象自动下钻到 .standard 标准字符串 + * - number 数值字段支持比较运算符 + */ +export function formatServerFieldExpr( + fieldKey: string, + op: string, + rawVal: string, + entity?: DatalinkEntity +): string { + const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined; + const targetKey = resolved?.name || fieldKey; + const isCustom = targetKey.startsWith("E_"); + const serverPath = isCustom ? `form.${targetKey}` : targetKey; + const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== ""; + + // Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... }) + if (resolved?.type === "money") { + const moneyPath = `${serverPath}.standard`; + const num = Number(rawVal); + const withDec = !Number.isNaN(num) && !rawVal.includes("../../datalink") ? `${rawVal}.00` : rawVal; + if (op === "=" || op === "==") { + if (withDec !== rawVal) { + return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`; + } + return `${moneyPath}=="${escaped}"`; + } + if (op === "!=") { + return `${moneyPath}!="${escaped}"`; + } + return `${moneyPath}.containsIgnoreCase("${escaped}")`; + } + + // Number 字段 + if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) { + if (op === "~" || op === "=~" || op === ":") { + return `${serverPath}.containsIgnoreCase("${escaped}")`; + } + const cmp = op === "=" ? "==" : op; + return `${serverPath}${cmp}${rawVal}`; + } + + // Text / Ref / Other 字段 + if (op === "~" || op === "=~" || op === ":") { + return `${serverPath}.containsIgnoreCase("${escaped}")`; + } + if (op === "!=") { + return `${serverPath}!="${escaped}"`; + } + return `${serverPath}=="${escaped}"`; +} + + +export function buildKeywordFilter( + keyword: string, + options?: BuildKeywordFilterOptions +): string { + const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + const conds: string[] = [ + `name.containsIgnoreCase("${escaped}")`, + `code.containsIgnoreCase("${escaped}")`, + ]; + + if (options?.entity && options.searchFields && options.searchFields.length > 0) { + for (const searchField of options.searchFields) { + const resolved = resolveEntityField(options.entity, searchField); + const targetName = resolved?.name || searchField; + if (targetName && targetName !== "name" && targetName !== "code") { + const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity); + conds.push(expr); + } + } + } + + return `(${conds.join("||")})&&(active.in(true,false))`; +} + + +/** + * 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。 + * 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。 + */ +export function buildServerFieldFilter( + filterInput: string, + entity?: DatalinkEntity +): string { + const trimmed = filterInput.trim(); + if ( + trimmed.startsWith("(") || + trimmed.includes(".containsIgnoreCase(") || + trimmed.includes(".in(") || + trimmed.includes("==") + ) { + return trimmed; + } + + // 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用" + const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/); + if (!match) return trimmed; + + const rawKey = match[1].trim(); + const op = match[2]; + const rawVal = match[3].trim().replace(/^["']|["']$/g, ""); + + const expr = formatServerFieldExpr(rawKey, op, rawVal, entity); + return expr ? `(${expr})&&(active.in(true,false))` : trimmed; +} + + +/** + * 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合) + */ +function splitPredicateParts(source: string, separator: string): string[] { + const parts: string[] = []; + let quote = "", depth = 0, start = 0; + for (let i = 0; i < source.length; i++) { + const char = source[i]; + if (quote) { + if (char === "\\") i++; + else if (char === quote) quote = ""; + continue; + } + if (char === "'" || char === '"') quote = char; + else if (char === "(") depth++; + else if (char === ")") { + if (--depth < 0) throw new ValidationError("筛选条件括号不匹配"); + } else if (depth === 0 && source.startsWith(separator, i)) { + parts.push(source.slice(start, i).trim()); + start = i + separator.length; + i += separator.length - 1; + } + } + if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配"); + parts.push(source.slice(start).trim()); + if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空"); + return parts; +} + + +function predicateLiteral(raw: string): string | number | boolean | null { + if (/^(["']).*\1$/s.test(raw)) { + const value = raw.slice(1, -1); + if (raw[0] === '"') { + try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); } + } + if (/(? boolean { + const conditions = splitPredicateParts(whereClause, "&&").map(cond => { + // 1. in 操作符: field in (v1, v2, v3) + const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i); + // 2. 比较操作符: ==, !=, >=, <=, >, <, = + const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s); + if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`); + const field = predicateField(entity, (inMatch ?? compMatch)![1].trim()); + const op = inMatch ? "in" : compMatch![2]; + const targets = inMatch + ? splitPredicateParts(inMatch[2], ",").map(predicateLiteral) + : [predicateLiteral(compMatch![3].trim())]; + return (record: DatalinkRecord) => { + const actual = extractRecordFieldValue(record, field); + const equal = (target: string | number | boolean | null): boolean => { + if (target === null) return actual === null || actual === undefined; + if (typeof target === "number") return extractNumericFieldValue(record, field) === target; + return actual !== null && actual !== undefined && String(actual) === String(target); + }; + if (op === "in") return targets.some(equal); + // 字符串/布尔比较 + if (op === "=" || op === "==") return equal(targets[0]); + if (op === "!=") return !equal(targets[0]); + // 数值比较 + const value = extractNumericFieldValue(record, field); + const target = targets[0]; + if (value === null || typeof target !== "number") return false; + return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target; + }; + }); + return record => conditions.every(condition => condition(record)); +} + + +export function filterRecordsByPredicate( + records: DatalinkRecord[], + whereClause: string, + entity: DatalinkEntity +): DatalinkRecord[] { + if (!whereClause || !whereClause.trim()) return records; + return records.filter(compileRecordPredicate(whereClause, entity)); +} + + +/** + * 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销" + */ +export function parseSetClause( + setClause: string, + entity: DatalinkEntity +): Record { + const result: Record = {}; + let assignments: string[]; + try { assignments = splitPredicateParts(setClause, ","); } + catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); } + + for (const assign of assignments) { + const eqIdx = assign.indexOf("="); + if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`); + const rawKey = assign.slice(0, eqIdx).trim(); + if (!rawKey) throw new ValidationError("赋值字段不能为空"); + let rawVal = assign.slice(eqIdx + 1).trim(); + + // 去除外层引号,同时保留显式字符串的类型与转义语义。 + const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'")); + const literal = quoted ? predicateLiteral(rawVal) : undefined; + + const field = resolveEntityField(entity, rawKey); + const targetKey = field ? field.name : rawKey; + + // 类型智能转换 + if (quoted) { + result[targetKey] = literal; + } else if (rawVal === "true") { + result[targetKey] = true; + } else if (rawVal === "false") { + result[targetKey] = false; + } else if (rawVal === "null") { + result[targetKey] = null; + } else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") { + result[targetKey] = Number(rawVal); + } else { + result[targetKey] = rawVal; + } + } + + return result; +} + + +/** + * 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05" + */ +export function parseExpectClause( + expectClause: string +): Array<{ field: string; targetValue: number; tolerance?: number }> { + if (!expectClause || !expectClause.trim()) return []; + const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean); + const results: Array<{ field: string; targetValue: number; tolerance?: number }> = []; + + for (const part of parts) { + const match = part.match( + /^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/ + ); + if (match) { + const field = match[1].trim(); + const targetValue = parseFloat(match[2]); + const tolerance = match[3] ? parseFloat(match[3]) : undefined; + if (!Number.isNaN(targetValue)) { + results.push({ field, targetValue, tolerance }); + } + } + } + return results; +} diff --git a/src/domains/platform/datalink/records.ts b/src/domains/platform/datalink/records.ts new file mode 100644 index 0000000..1f50e2a --- /dev/null +++ b/src/domains/platform/datalink/records.ts @@ -0,0 +1,497 @@ +import type { KyInstance } from "ky"; +import * as api from "./api.js"; +import { resolveDatalinkField } from "./fields.js"; +import type { DatalinkEntity, DatalinkField, DatalinkRecord, DatalinkRecordEditPayload, DatalinkRecordPage, NormalizedDatalinkRecord } from "./types.js"; +import type { DatalinkPlatformDetail } from "../applications/types.js"; + + +export function listPlatformEntities(...args: Parameters) { + return api.listPlatformEntities(...args); +} + + +export function searchEntityRecords(...args: Parameters) { + return api.searchEntityRecords(...args); +} + + +export function listImportJobs(...args: Parameters) { + return api.listImportJobs(...args); +} + + +export function getImportResult(...args: Parameters) { + return api.getImportResult(...args); +} + + +export function toggleRecordState(...args: Parameters) { + return api.toggleRecordState(...args); +} + + +export function getRecordDetail(...args: Parameters) { + return api.getRecordDetail(...args); +} + + +export function getRecordFormSchema(...args: Parameters) { + return api.getRecordFormSchema(...args); +} + + +export function editRecord(...args: Parameters) { + return api.editRecord(...args); +} + + +export function buildSafeRecordEditPayload(...args: Parameters) { + return api.buildSafeRecordEditPayload(...args); +} + + +export function safeEditRecord(...args: Parameters) { + return api.safeEditRecord(...args); +} + + +export function recomputeRecordLedger(...args: Parameters) { + return api.recomputeRecordLedger(...args); +} + + +function matches(value: unknown, target: string): boolean { + return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); +} + + +export async function resolveEntity( + client: KyInstance, + corpId: string, + platform: DatalinkPlatformDetail, + target: string +): Promise { + const entities = await api.listPlatformEntities(client, corpId, platform.id); + return entities.find((entity) => + [entity.id, entity.name, entity.code].some((value) => matches(value, target)) + ); +} + + +export function selectRecordFields( + record: Record, + fields: string[], + definitions: DatalinkField[] = [] +): Record { + if (fields.length === 0) return record; + const dataLink = + record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) + ? (record.dataLink as Record) + : record; + const selected: Record = {}; + const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields) + ? record.fields as Record + : undefined; + for (const selector of fields) { + const definition = definitions.find( + (field) => field.name === selector || field.label === selector + ); + const sourceName = definition?.name ?? selector; + const label = definition?.label || selector; + if (sourceName in dataLink) selected[label] = dataLink[sourceName]; + else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label]; + else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName]; + else if (normalizedFields) { + const systemName = sourceName.replace(/^E_.+_/, ""); + if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName]; + } + } + return record.dataLink && typeof record.dataLink === "object" + ? { ...record, dataLink: selected } + : selected; +} + + +/** + * 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。 + */ +export async function fetchAllEntityRecords( + client: KyInstance, + corpId: string, + entityId: string, + options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} +): Promise { + const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); + let start = 0; + let total = 0; + const allData: DatalinkRecord[] = []; + let firstPage: DatalinkRecordPage | undefined; + + while (true) { + const page = await api.searchEntityRecords(client, corpId, entityId, { + start, + count: pageSize, + filterBy: options.filterBy, + orderBy: options.orderBy, + }); + firstPage ??= page; + total = page.total; + if (page.data.length === 0) break; + allData.push(...page.data); + start += page.data.length; + if (allData.length >= total || page.data.length < pageSize) { + break; + } + } + + return { + total: Math.max(total, allData.length), + data: allData, + actions: firstPage?.actions ?? [], + components: firstPage?.components ?? [], + path: firstPage?.path, + template: firstPage?.template, + }; +} + + +/** + * 流式异步迭代器:逐页拉取并逐条产出业务对象记录。 + * 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。 + */ +export async function* iterateAllEntityRecords( + client: KyInstance, + corpId: string, + entityId: string, + options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} +): AsyncGenerator { + const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); + let start = 0; + let total = 0; + let yielded = 0; + + while (true) { + const page = await api.searchEntityRecords(client, corpId, entityId, { + start, + count: pageSize, + filterBy: options.filterBy, + orderBy: options.orderBy, + }); + total = page.total; + if (page.data.length === 0) break; + for (const record of page.data) { + yield record; + yielded++; + } + start += page.data.length; + if (yielded >= total || page.data.length < pageSize) { + break; + } + } +} + + +/** + * 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。 + * 彻底消除 r.id vs r.dataLink.id 以及 E__ 动态前缀的困扰。 + */ +export function normalizeDatalinkRecord( + rawRecord: DatalinkRecord, + entity?: DatalinkEntity, + options: { includeRaw?: boolean } = {} +): NormalizedDatalinkRecord { + const dl = + rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink) + ? (rawRecord.dataLink as Record) + : (rawRecord as Record); + + const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? ""); + const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId; + + const id = String(dl.id ?? rawRecord.id ?? ""); + const active = (dl.active ?? rawRecord.active) !== false; + const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null; + const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null; + + const nameField = entity?.fields.find( + (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") + ); + const codeField = entity?.fields.find( + (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") + ); + + const name = String( + dl.name ?? + dl["名称"] ?? + (nameField ? dl[nameField.name] : undefined) ?? + (bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ?? + "" + ); + + const code = String( + dl.code ?? + dl["编码"] ?? + (codeField ? dl[codeField.name] : undefined) ?? + (bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ?? + "" + ); + + const fields: Record = {}; + if (entity?.fields) { + for (const field of entity.fields) { + if (field.name === nameField?.name || field.name === codeField?.name) continue; + const keyCandidates = [ + field.name, + bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined, + field.label, + ].filter(Boolean) as string[]; + + let val: unknown = undefined; + for (const key of keyCandidates) { + if (key in dl) { + val = dl[key]; + break; + } + } + + if (val !== undefined && val !== null) { + if (typeof val === "object" && !Array.isArray(val)) { + const obj = val as Record; + if ("standard" in obj) { + val = obj.standard; + } else if ("name" in obj && typeof obj.name === "string" && obj.name) { + val = obj.name; + } else { + let targetDataLink: Record | undefined = undefined; + if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) { + targetDataLink = obj.dataLink as Record; + } else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record)) { + targetDataLink = (obj.data as Record).dataLink as Record; + } + + if (targetDataLink) { + const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record; + const combined = { ...targetDataLink, ...form }; + let subDisplay: string | undefined = undefined; + for (const [k, v] of Object.entries(combined)) { + if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) { + subDisplay = v; + break; + } + } + if (!subDisplay) { + for (const [k, v] of Object.entries(combined)) { + if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) { + subDisplay = v; + break; + } + } + } + val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined); + } else if (obj.id && typeof obj.id === "string") { + val = obj.id; + } + } + } + fields[field.label || field.name] = val; + } + } + } + + return { + id, + code, + name, + active, + createTime, + updateTime, + fields, + ...(options.includeRaw ? { raw: rawRecord } : {}), + }; +} + + +export function extractRefIdAndName(value: unknown): { + id?: string; + name?: string; + active?: boolean; +} { + if (typeof value === "string" && value.trim()) { + return { id: value.trim() }; + } + if (!value || typeof value !== "object" || Array.isArray(value)) { + return {}; + } + const obj = value as Record; + const nestedData = + obj.data && typeof obj.data === "object" + ? (obj.data as Record) + : undefined; + const nestedDl = + nestedData?.dataLink && typeof nestedData.dataLink === "object" + ? (nestedData.dataLink as Record) + : obj.dataLink && typeof obj.dataLink === "object" + ? (obj.dataLink as Record) + : undefined; + const id = + typeof obj.id === "string" && obj.id.trim() + ? obj.id.trim() + : typeof nestedDl?.id === "string" && nestedDl.id.trim() + ? nestedDl.id.trim() + : undefined; + const name = + typeof obj.name === "string" && obj.name.trim() + ? obj.name.trim() + : typeof nestedDl?.name === "string" && nestedDl.name.trim() + ? nestedDl.name.trim() + : undefined; + const active = + typeof obj.active === "boolean" + ? obj.active + : typeof nestedDl?.active === "boolean" + ? nestedDl.active + : undefined; + return { id, name, active }; +} + + +export interface BatchEditTargetItem { + recordId: string; + patchForm: Record; + active?: boolean; +} + + +export interface BatchEditItemResult { + recordId: string; + status: "preview" | "updated" | "failed"; + payload?: DatalinkRecordEditPayload; + result?: Record; + error?: string; +} + + +export async function batchSafeEditRecords( + client: KyInstance, + corpId: string, + entity: DatalinkEntity, + targets: BatchEditTargetItem[], + options: { concurrency?: number; dryRun?: boolean } = {} +): Promise { + const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32)); + const results: BatchEditItemResult[] = new Array(targets.length); + let cursor = 0; + + const worker = async () => { + while (true) { + const idx = cursor++; + if (idx >= targets.length) break; + const target = targets[idx]; + try { + const detail = await api.getRecordDetail(client, corpId, target.recordId); + const payload = api.buildSafeRecordEditPayload({ + entityId: entity.id, + recordId: target.recordId, + detail, + fields: entity.fields, + patchForm: target.patchForm, + active: target.active, + }); + if (options.dryRun) { + results[idx] = { + recordId: target.recordId, + status: "preview", + payload, + }; + } else { + const res = await api.editRecord(client, corpId, payload); + results[idx] = { + recordId: target.recordId, + status: "updated", + payload, + result: res, + }; + } + } catch (error) { + results[idx] = { + recordId: target.recordId, + status: "failed", + error: error instanceof Error ? error.message : String(error), + }; + } + } + }; + + await Promise.all( + Array.from({ length: Math.min(concurrency, targets.length) }, () => worker()) + ); + return results; +} + + +// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ─────────────────── + +/** + * 根据字段名或标签模糊解析实体字段元数据 + */ +export function resolveEntityField( + entity: DatalinkEntity, + query: string +): DatalinkField | undefined { + return resolveDatalinkField(entity.fields, entity.id, query); +} + + +/** + * 通用提取记录中某一字段的原始值 + */ +export function extractRecordFieldValue( + record: DatalinkRecord, + field: DatalinkField | string +): unknown { + const source = + record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) + ? (record.dataLink as Record) + : record; + const fieldName = typeof field === "string" ? field : field.name; + const fieldLabel = typeof field === "string" ? undefined : field.label; + + let val = source[fieldName] ?? record[fieldName]; + if (val === undefined && fieldLabel) { + val = source[fieldLabel] ?? record[fieldLabel]; + } + if (val === undefined && record.form && typeof record.form === "object") { + val = (record.form as Record)[fieldName]; + if (val === undefined && fieldLabel) { + val = (record.form as Record)[fieldLabel]; + } + } + return val; +} + + +/** + * 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串) + */ +export function extractNumericFieldValue( + record: DatalinkRecord, + field: DatalinkField | string +): number | null { + const val = extractRecordFieldValue(record, field); + if (val === null || val === undefined || val === "") return null; + if (typeof val === "number" && !Number.isNaN(val)) return val; + if (typeof val === "object" && !Array.isArray(val)) { + const std = (val as any).standard ?? (val as any).amount; + if (typeof std === "number" && !Number.isNaN(std)) return std; + if (typeof std === "string") { + const parsed = parseFloat(std); + if (!Number.isNaN(parsed)) return parsed; + } + } + if (typeof val === "string") { + const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, ""); + const parsed = parseFloat(clean); + if (!Number.isNaN(parsed)) return parsed; + } + return null; +} diff --git a/src/domains/platform/datalink/services.ts b/src/domains/platform/datalink/services.ts index 81990bb..60665b4 100644 --- a/src/domains/platform/datalink/services.ts +++ b/src/domains/platform/datalink/services.ts @@ -1,1389 +1,53 @@ -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, DatalinkRecord, DatalinkRecordEditPayload, DatalinkRecordPage, AggregateFieldStats, GroupAggregateResult, LedgerAggregateReport, ContinuityIssue, LedgerContinuityReport, NormalizedDatalinkRecord, DatalinkRecordStats } from "./types.js"; -import type { DatalinkPlatformDetail } from "../applications/types.js"; - -export type { SafeRecordEditOptions } from "./api.js"; - -export function listPlatformEntities(...args: Parameters) { - return api.listPlatformEntities(...args); -} - -export function searchEntityRecords(...args: Parameters) { - return api.searchEntityRecords(...args); -} - -export function listImportJobs(...args: Parameters) { - return api.listImportJobs(...args); -} - -export function getImportResult(...args: Parameters) { - return api.getImportResult(...args); -} - -export function toggleRecordState(...args: Parameters) { - return api.toggleRecordState(...args); -} - -export function getRecordDetail(...args: Parameters) { - return api.getRecordDetail(...args); -} - -export function getRecordFormSchema(...args: Parameters) { - return api.getRecordFormSchema(...args); -} - -export function editRecord(...args: Parameters) { - return api.editRecord(...args); -} - -export function buildSafeRecordEditPayload(...args: Parameters) { - return api.buildSafeRecordEditPayload(...args); -} - -export function safeEditRecord(...args: Parameters) { - return api.safeEditRecord(...args); -} - -export function recomputeRecordLedger(...args: Parameters) { - return api.recomputeRecordLedger(...args); -} - -function matches(value: unknown, target: string): boolean { - return typeof value === "string" && value.toLowerCase() === target.toLowerCase(); -} - -export async function resolveEntity( - client: KyInstance, - corpId: string, - platform: DatalinkPlatformDetail, - target: string -): Promise { - const entities = await api.listPlatformEntities(client, corpId, platform.id); - return entities.find((entity) => - [entity.id, entity.name, entity.code].some((value) => matches(value, target)) - ); -} - -export interface BuildKeywordFilterOptions { - entity?: DatalinkEntity; - searchFields?: string[]; -} - -/** - * 格式化服务端 filterBy 字段表达式。 - * 针对 DataLink 特性: - * - 动态业务字段(E_ 前缀)自动附加 form. 命名空间 - * - money 货币复合对象自动下钻到 .standard 标准字符串 - * - number 数值字段支持比较运算符 - */ -export function formatServerFieldExpr( - fieldKey: string, - op: string, - rawVal: string, - entity?: DatalinkEntity -): string { - const resolved = entity ? resolveEntityField(entity, fieldKey) : undefined; - const targetKey = resolved?.name || fieldKey; - const isCustom = targetKey.startsWith("E_"); - const serverPath = isCustom ? `form.${targetKey}` : targetKey; - const escaped = rawVal.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - const isNumericString = !Number.isNaN(Number(rawVal)) && rawVal.trim() !== ""; - - // Money 字段 (服务端为 { standard: "100.00", standardUnit: "元", ... }) - if (resolved?.type === "money") { - const moneyPath = `${serverPath}.standard`; - const num = Number(rawVal); - const withDec = !Number.isNaN(num) && !rawVal.includes("../../datalink") ? `${rawVal}.00` : rawVal; - if (op === "=" || op === "==") { - if (withDec !== rawVal) { - return `(${moneyPath}=="${escaped}"||${moneyPath}=="${withDec}")`; - } - return `${moneyPath}=="${escaped}"`; - } - if (op === "!=") { - return `${moneyPath}!="${escaped}"`; - } - return `${moneyPath}.containsIgnoreCase("${escaped}")`; - } - - // Number 字段 - if (resolved?.type === "number" || (isNumericString && op !== "~" && op !== "=~" && op !== ":")) { - if (op === "~" || op === "=~" || op === ":") { - return `${serverPath}.containsIgnoreCase("${escaped}")`; - } - const cmp = op === "=" ? "==" : op; - return `${serverPath}${cmp}${rawVal}`; - } - - // Text / Ref / Other 字段 - if (op === "~" || op === "=~" || op === ":") { - return `${serverPath}.containsIgnoreCase("${escaped}")`; - } - if (op === "!=") { - return `${serverPath}!="${escaped}"`; - } - return `${serverPath}=="${escaped}"`; -} - -export function buildKeywordFilter( - keyword: string, - options?: BuildKeywordFilterOptions -): string { - const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - const conds: string[] = [ - `name.containsIgnoreCase("${escaped}")`, - `code.containsIgnoreCase("${escaped}")`, - ]; - - if (options?.entity && options.searchFields && options.searchFields.length > 0) { - for (const searchField of options.searchFields) { - const resolved = resolveEntityField(options.entity, searchField); - const targetName = resolved?.name || searchField; - if (targetName && targetName !== "name" && targetName !== "code") { - const expr = formatServerFieldExpr(targetName, "~", keyword, options.entity); - conds.push(expr); - } - } - } - - return `(${conds.join("||")})&&(active.in(true,false))`; -} - -/** - * 将字段过滤表达式解析并转换为 DataLink 服务端原生 filterBy 语法。 - * 支持透传原生 DSL,或智能解析 "字段~值"、"字段=值"、"字段!=值" 并结合元数据映射为物理 Key。 - */ -export function buildServerFieldFilter( - filterInput: string, - entity?: DatalinkEntity -): string { - const trimmed = filterInput.trim(); - if ( - trimmed.startsWith("(") || - trimmed.includes(".containsIgnoreCase(") || - trimmed.includes(".in(") || - trimmed.includes("==") - ) { - return trimmed; - } - - // 解析 key-value: 如 "客户名称~猫子"、"不含税金额=191700"、"状态!=停用" - const match = trimmed.match(/^([^=~:!]+)\s*(=~|==|!=|~|:|=)\s*(.+)$/); - if (!match) return trimmed; - - const rawKey = match[1].trim(); - const op = match[2]; - const rawVal = match[3].trim().replace(/^["']|["']$/g, ""); - - const expr = formatServerFieldExpr(rawKey, op, rawVal, entity); - return expr ? `(${expr})&&(active.in(true,false))` : trimmed; -} - -export function selectRecordFields( - record: Record, - fields: string[], - definitions: DatalinkField[] = [] -): Record { - if (fields.length === 0) return record; - const dataLink = - record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) - ? (record.dataLink as Record) - : record; - const selected: Record = {}; - const normalizedFields = record.fields && typeof record.fields === "object" && !Array.isArray(record.fields) - ? record.fields as Record - : undefined; - for (const selector of fields) { - const definition = definitions.find( - (field) => field.name === selector || field.label === selector - ); - const sourceName = definition?.name ?? selector; - const label = definition?.label || selector; - if (sourceName in dataLink) selected[label] = dataLink[sourceName]; - else if (normalizedFields && label in normalizedFields) selected[label] = normalizedFields[label]; - else if (normalizedFields && sourceName in normalizedFields) selected[label] = normalizedFields[sourceName]; - else if (normalizedFields) { - const systemName = sourceName.replace(/^E_.+_/, ""); - if (["name", "code"].includes(systemName) && systemName in record) selected[label] = record[systemName]; - } - } - return record.dataLink && typeof record.dataLink === "object" - ? { ...record, dataLink: selected } - : selected; -} - -/** - * 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。 - */ -export async function fetchAllEntityRecords( - client: KyInstance, - corpId: string, - entityId: string, - options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} -): Promise { - const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); - let start = 0; - let total = 0; - const allData: DatalinkRecord[] = []; - let firstPage: DatalinkRecordPage | undefined; - - while (true) { - const page = await api.searchEntityRecords(client, corpId, entityId, { - start, - count: pageSize, - filterBy: options.filterBy, - orderBy: options.orderBy, - }); - firstPage ??= page; - total = page.total; - if (page.data.length === 0) break; - allData.push(...page.data); - start += page.data.length; - if (allData.length >= total || page.data.length < pageSize) { - break; - } - } - - return { - total: Math.max(total, allData.length), - data: allData, - actions: firstPage?.actions ?? [], - components: firstPage?.components ?? [], - path: firstPage?.path, - template: firstPage?.template, - }; -} - -/** - * 流式异步迭代器:逐页拉取并逐条产出业务对象记录。 - * 内存开销恒定为 O(pageSize),可直接支持 10 万+ 级海量数据的流式下发与外部管道消费。 - */ -export async function* iterateAllEntityRecords( - client: KyInstance, - corpId: string, - entityId: string, - options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {} -): AsyncGenerator { - const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000)); - let start = 0; - let total = 0; - let yielded = 0; - - while (true) { - const page = await api.searchEntityRecords(client, corpId, entityId, { - start, - count: pageSize, - filterBy: options.filterBy, - orderBy: options.orderBy, - }); - total = page.total; - if (page.data.length === 0) break; - for (const record of page.data) { - yield record; - yielded++; - } - start += page.data.length; - if (yielded >= total || page.data.length < pageSize) { - break; - } - } -} - -/** - * 将数据互联原始报文规范化为标准、扁平、脱敏于动态前缀的结构。 - * 彻底消除 r.id vs r.dataLink.id 以及 E__ 动态前缀的困扰。 - */ -export function normalizeDatalinkRecord( - rawRecord: DatalinkRecord, - entity?: DatalinkEntity, - options: { includeRaw?: boolean } = {} -): NormalizedDatalinkRecord { - const dl = - rawRecord.dataLink && typeof rawRecord.dataLink === "object" && !Array.isArray(rawRecord.dataLink) - ? (rawRecord.dataLink as Record) - : (rawRecord as Record); - - const entityId = String(entity?.id ?? dl.entityId ?? rawRecord.entityId ?? ""); - const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId; - - const id = String(dl.id ?? rawRecord.id ?? ""); - const active = (dl.active ?? rawRecord.active) !== false; - const createTime = (dl.createTime ?? rawRecord.createTime ?? null) as number | null; - const updateTime = (dl.updateTime ?? rawRecord.updateTime ?? null) as number | null; - - const nameField = entity?.fields.find( - (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") - ); - const codeField = entity?.fields.find( - (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") - ); - - const name = String( - dl.name ?? - dl["名称"] ?? - (nameField ? dl[nameField.name] : undefined) ?? - (bareEntityId ? dl[`E_${bareEntityId}_name`] : undefined) ?? - "" - ); - - const code = String( - dl.code ?? - dl["编码"] ?? - (codeField ? dl[codeField.name] : undefined) ?? - (bareEntityId ? dl[`E_${bareEntityId}_code`] : undefined) ?? - "" - ); - - const fields: Record = {}; - if (entity?.fields) { - for (const field of entity.fields) { - if (field.name === nameField?.name || field.name === codeField?.name) continue; - const keyCandidates = [ - field.name, - bareEntityId ? `E_${bareEntityId}_${field.name}` : undefined, - field.label, - ].filter(Boolean) as string[]; - - let val: unknown = undefined; - for (const key of keyCandidates) { - if (key in dl) { - val = dl[key]; - break; - } - } - - if (val !== undefined && val !== null) { - if (typeof val === "object" && !Array.isArray(val)) { - const obj = val as Record; - if ("standard" in obj) { - val = obj.standard; - } else if ("name" in obj && typeof obj.name === "string" && obj.name) { - val = obj.name; - } else { - let targetDataLink: Record | undefined = undefined; - if ("dataLink" in obj && typeof obj.dataLink === "object" && obj.dataLink) { - targetDataLink = obj.dataLink as Record; - } else if ("data" in obj && typeof obj.data === "object" && obj.data && "dataLink" in (obj.data as Record)) { - targetDataLink = (obj.data as Record).dataLink as Record; - } - - if (targetDataLink) { - const form = (targetDataLink.form && typeof targetDataLink.form === "object" ? targetDataLink.form : {}) as Record; - const combined = { ...targetDataLink, ...form }; - let subDisplay: string | undefined = undefined; - for (const [k, v] of Object.entries(combined)) { - if (typeof v === "string" && v.trim() && (k === "name" || k === "title" || k === "名称" || k === "标题" || k.endsWith("_name") || k.endsWith("_title"))) { - subDisplay = v; - break; - } - } - if (!subDisplay) { - for (const [k, v] of Object.entries(combined)) { - if (typeof v === "string" && v.trim() && (k === "code" || k === "编码" || k.endsWith("_code") || k.includes("编号"))) { - subDisplay = v; - break; - } - } - } - val = subDisplay || (targetDataLink.id ? String(targetDataLink.id) : undefined) || (obj.id ? String(obj.id) : undefined); - } else if (obj.id && typeof obj.id === "string") { - val = obj.id; - } - } - } - fields[field.label || field.name] = val; - } - } - } - - return { - id, - code, - name, - active, - createTime, - updateTime, - fields, - ...(options.includeRaw ? { raw: rawRecord } : {}), - }; -} - -/** - * 计算业务对象记录的轻量级宏观分布画像(统计总数、启用/停用数、重名率、编码前缀聚类等)。 - * 既可接收全量内存数组,也可配合流式生成器在 O(1) 内存下在线累加计算。 - */ -export function calculateEntityRecordStats( - records: Iterable, - entity?: DatalinkEntity, - explicitTotal?: number -): DatalinkRecordStats { - let total = 0; - let activeCount = 0; - let inactiveCount = 0; - - const namesMap = new Map(); - const patternsMap = new Map(); - - let earliestCreate: number | null = null; - let latestUpdate: number | null = null; - - for (const raw of records) { - total++; - const norm = normalizeDatalinkRecord(raw, entity); - if (norm.active) activeCount++; - else inactiveCount++; - - if (norm.createTime && typeof norm.createTime === "number") { - if (earliestCreate === null || norm.createTime < earliestCreate) earliestCreate = norm.createTime; - } - if (norm.updateTime && typeof norm.updateTime === "number") { - if (latestUpdate === null || norm.updateTime > latestUpdate) latestUpdate = norm.updateTime; - } - - // 统计名称重名与状态交叉 - if (norm.name) { - if (!namesMap.has(norm.name)) { - namesMap.set(norm.name, { total: 0, active: 0, inactive: 0 }); - } - const nStats = namesMap.get(norm.name)!; - nStats.total++; - if (norm.active) nStats.active++; - else nStats.inactive++; - } - - // 统计编码结构聚类 - const code = norm.code || "EMPTY"; - const pattern = code - .replace(/\d{8}/g, "YYYYMMDD") - .replace(/\d{6}/g, "SEQ6") - .replace(/\d+/g, "N"); - - if (!patternsMap.has(pattern)) { - patternsMap.set(pattern, { pattern, sample: code, count: 0, activeCount: 0, inactiveCount: 0 }); - } - const pStats = patternsMap.get(pattern)!; - pStats.count++; - if (norm.active) pStats.activeCount++; - else pStats.inactiveCount++; - } - - const finalTotal = explicitTotal !== undefined ? Math.max(explicitTotal, total) : total; - const activeRate = finalTotal > 0 ? `${((activeCount / finalTotal) * 100).toFixed(1)}%` : "0.0%"; - - let duplicateNamesCount = 0; - let mixedStatusNamesCount = 0; - for (const n of namesMap.values()) { - if (n.total > 1) duplicateNamesCount++; - if (n.active > 0 && n.inactive > 0) mixedStatusNamesCount++; - } - - const codePatterns = Array.from(patternsMap.values()).sort((a, b) => b.count - a.count); - - const formatDate = (ts: number | null) => (ts ? new Date(ts).toLocaleString("zh-CN", { hour12: false }) : null); - - return { - total: finalTotal, - activeCount, - inactiveCount, - activeRate, - uniqueNames: namesMap.size, - duplicateNamesCount, - mixedStatusNamesCount, - codePatterns, - earliestCreateTime: formatDate(earliestCreate), - latestUpdateTime: formatDate(latestUpdate), - }; -} - -export interface DatalinkAuditIssue { - recordId: string; - recordCode: string; - recordName: string; - active: boolean; - type: - | "MISSING_FIELD" - | "DISABLED_REFERENCE" - | "CROSS_LEDGER_MISSING_SYNC" - | "CROSS_LEDGER_MISMATCH"; - field: string; - fieldLabel: string; - message: string; - linkedField?: string; - linkedFieldLabel?: string; - linkedRecordId?: string; - actualId?: string; - actualName?: string; - expectedId?: string; - expectedName?: string; -} - -export interface DatalinkAuditReport { - entityId: string; - entityName: string; - totalRecords: number; - auditedRecords: number; - healthyRecords: number; - affectedRecordCount: number; - issueCount: number; - summary: { - missingFieldCount: number; - disabledReferenceCount: number; - crossLedgerMissingSyncCount: number; - crossLedgerMismatchCount: number; - }; - issues: DatalinkAuditIssue[]; - suggestedPatches: Array<{ - id: string; - code: string; - name: string; - form: Record; - reason: string; - }>; -} - -function isEmptyFieldValue(value: unknown): boolean { - if (value === undefined || value === null || value === "") return true; - if (Array.isArray(value)) return value.length === 0; - if (typeof value === "object") { - const obj = value as Record; - if ("id" in obj) { - return obj.id === undefined || obj.id === null || obj.id === ""; - } - if ("standard" in obj) { - return obj.standard === undefined || obj.standard === null || obj.standard === ""; - } - return Object.keys(obj).length === 0; - } - return false; -} - -function extractRefIdAndName(value: unknown): { - id?: string; - name?: string; - active?: boolean; -} { - if (typeof value === "string" && value.trim()) { - return { id: value.trim() }; - } - if (!value || typeof value !== "object" || Array.isArray(value)) { - return {}; - } - const obj = value as Record; - const nestedData = - obj.data && typeof obj.data === "object" - ? (obj.data as Record) - : undefined; - const nestedDl = - nestedData?.dataLink && typeof nestedData.dataLink === "object" - ? (nestedData.dataLink as Record) - : obj.dataLink && typeof obj.dataLink === "object" - ? (obj.dataLink as Record) - : undefined; - const id = - typeof obj.id === "string" && obj.id.trim() - ? obj.id.trim() - : typeof nestedDl?.id === "string" && nestedDl.id.trim() - ? nestedDl.id.trim() - : undefined; - const name = - typeof obj.name === "string" && obj.name.trim() - ? obj.name.trim() - : typeof nestedDl?.name === "string" && nestedDl.name.trim() - ? nestedDl.name.trim() - : undefined; - const active = - typeof obj.active === "boolean" - ? obj.active - : typeof nestedDl?.active === "boolean" - ? nestedDl.active - : undefined; - return { id, name, active }; -} - -/** - * 对业务对象记录集合执行数据健康度体检: - * 1. 必填/关键字段缺失检查 (MISSING_FIELD) - * 2. 关联对象/档案停用检查 (DISABLED_REFERENCE) - * 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH) - */ -export function auditEntityRecords( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {} -): DatalinkAuditReport { - const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id; - const nameField = entity.fields.find( - (f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name") - ); - const codeField = entity.fields.find( - (f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code") - ); - - // 解析需要检查缺失的字段集合 - const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean); - const fieldsToCheck: DatalinkField[] = - explicitSelectors.length > 0 - ? explicitSelectors.map((selector) => { - const found = entity.fields.find( - (f) => - f.name === selector || - f.label === selector || - f.name === `E_${bareEntityId}_${selector}` - ); - return ( - found ?? { - name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`, - label: selector, - type: "text", - } - ); - }) - : entity.fields.filter( - (f) => - f.optional === false || - f.type === "dimension" || - f.type === "dataLink" - ); - - const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink"); - const dimensionFields = entity.fields.filter((f) => f.type === "dimension"); - - const issues: DatalinkAuditIssue[] = []; - const suggestedPatchesMap = new Map< - string, - { id: string; code: string; name: string; form: Record; reasons: string[] } - >(); - const affectedRecordIds = new Set(); - let auditedRecords = 0; - - let missingFieldCount = 0; - let disabledReferenceCount = 0; - let crossLedgerMissingSyncCount = 0; - let crossLedgerMismatchCount = 0; - - for (const rawRecord of records) { - const dl = - rawRecord.dataLink && - typeof rawRecord.dataLink === "object" && - !Array.isArray(rawRecord.dataLink) - ? (rawRecord.dataLink as Record) - : (rawRecord as Record); - const recordId = String(dl.id ?? rawRecord.id ?? ""); - const active = (dl.active ?? rawRecord.active) !== false; - if (options.activeOnly && !active) continue; - - auditedRecords++; - const recordName = String( - dl.name ?? - dl["名称"] ?? - (nameField ? dl[nameField.name] : undefined) ?? - dl[`E_${bareEntityId}_name`] ?? - "" - ); - const recordCode = String( - dl.code ?? - dl["编码"] ?? - (codeField ? dl[codeField.name] : undefined) ?? - dl[`E_${bareEntityId}_code`] ?? - "" - ); - - const getFieldVal = (field: DatalinkField): unknown => - dl[field.name] ?? - dl[`E_${bareEntityId}_${field.name}`] ?? - (dl.form && typeof dl.form === "object" - ? (dl.form as Record)[field.name] - : undefined) ?? - dl[field.label]; - - // 1. 必填/关键字段缺失检查 - for (const field of fieldsToCheck) { - const val = getFieldVal(field); - if (isEmptyFieldValue(val)) { - missingFieldCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "MISSING_FIELD", - field: field.name, - fieldLabel: field.label || field.name, - message: `字段 [${field.label || field.name}] (${field.name}) 为空`, - }); - } - } - - // 2. 关联对象/档案停用检查 - for (const field of entity.fields) { - if (field.type !== "dimension" && field.type !== "dataLink") continue; - const val = getFieldVal(field); - const items = Array.isArray(val) ? val : val ? [val] : []; - for (const item of items) { - const refInfo = extractRefIdAndName(item); - if (refInfo.active === false) { - disabledReferenceCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "DISABLED_REFERENCE", - field: field.name, - fieldLabel: field.label || field.name, - actualId: refInfo.id, - actualName: refInfo.name, - message: `字段 [${field.label || field.name}] 引用的${ - field.type === "dataLink" ? "业务对象记录" : "维度档案" - } [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`, - }); - } - } - } - - // 3. 跨表关联同名维度一致性检查 - for (const linkField of dataLinkFields) { - const linkVal = getFieldVal(linkField); - if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue; - const linkObj = linkVal as Record; - const parentDl = - linkObj.data && - typeof linkObj.data === "object" && - (linkObj.data as Record).dataLink && - typeof (linkObj.data as Record).dataLink === "object" - ? ((linkObj.data as Record).dataLink as Record) - : linkObj.dataLink && typeof linkObj.dataLink === "object" - ? (linkObj.dataLink as Record) - : linkObj; - const linkedRecordId = String(parentDl.id ?? linkObj.id ?? ""); - - for (const dimField of dimensionFields) { - const entityPrefix = `E_${bareEntityId}_`; - const suffix = dimField.name.startsWith(entityPrefix) - ? dimField.name.slice(entityPrefix.length) - : dimField.name.replace(/^E_[^_]+_/, ""); - const parentKey = Object.keys(parentDl).find( - (k) => - k === dimField.label || - k === suffix || - k.endsWith(`_${suffix}`) || - (Boolean(dimField.label) && k.endsWith(`_${dimField.label}`)) - ); - if (!parentKey) continue; - - const parentRef = extractRefIdAndName(parentDl[parentKey]); - if (!parentRef.id) continue; - - const childRef = extractRefIdAndName(getFieldVal(dimField)); - if (!childRef.id) { - crossLedgerMissingSyncCount++; - affectedRecordIds.add(recordId); - const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${ - linkField.label || linkField.name - }] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${ - parentRef.id - }),建议回填修复`; - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "CROSS_LEDGER_MISSING_SYNC", - field: dimField.name, - fieldLabel: dimField.label || dimField.name, - linkedField: linkField.name, - linkedFieldLabel: linkField.label || linkField.name, - linkedRecordId, - expectedId: parentRef.id, - expectedName: parentRef.name, - message: reason, - }); - - const existingPatch = suggestedPatchesMap.get(recordId) ?? { - id: recordId, - code: recordCode, - name: recordName, - form: {}, - reasons: [], - }; - existingPatch.form[dimField.name] = parentRef.id; - existingPatch.reasons.push( - `${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})` - ); - suggestedPatchesMap.set(recordId, existingPatch); - } else if (childRef.id !== parentRef.id) { - crossLedgerMismatchCount++; - affectedRecordIds.add(recordId); - issues.push({ - recordId, - recordCode, - recordName, - active, - type: "CROSS_LEDGER_MISMATCH", - field: dimField.name, - fieldLabel: dimField.label || dimField.name, - linkedField: linkField.name, - linkedFieldLabel: linkField.label || linkField.name, - linkedRecordId, - actualId: childRef.id, - actualName: childRef.name, - expectedId: parentRef.id, - expectedName: parentRef.name, - message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${ - childRef.name || childRef.id - }] (${childRef.id}) 与关联 [${ - linkField.label || linkField.name - }] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${ - parentRef.id - }) 不一致`, - }); - } - } - } - } - - const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({ - id: item.id, - code: item.code, - name: item.name, - form: item.form, - reason: item.reasons.join("; "), - })); - - return { - entityId: entity.id, - entityName: entity.name, - totalRecords: options.total ?? records.length, - auditedRecords, - healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size), - affectedRecordCount: affectedRecordIds.size, - issueCount: issues.length, - summary: { - missingFieldCount, - disabledReferenceCount, - crossLedgerMissingSyncCount, - crossLedgerMismatchCount, - }, - issues, - suggestedPatches, - }; -} - -export interface BatchEditTargetItem { - recordId: string; - patchForm: Record; - active?: boolean; -} - -export interface BatchEditItemResult { - recordId: string; - status: "preview" | "updated" | "failed"; - payload?: DatalinkRecordEditPayload; - result?: Record; - error?: string; -} - -export async function batchSafeEditRecords( - client: KyInstance, - corpId: string, - entity: DatalinkEntity, - targets: BatchEditTargetItem[], - options: { concurrency?: number; dryRun?: boolean } = {} -): Promise { - const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32)); - const results: BatchEditItemResult[] = new Array(targets.length); - let cursor = 0; - - const worker = async () => { - while (true) { - const idx = cursor++; - if (idx >= targets.length) break; - const target = targets[idx]; - try { - const detail = await api.getRecordDetail(client, corpId, target.recordId); - const payload = api.buildSafeRecordEditPayload({ - entityId: entity.id, - recordId: target.recordId, - detail, - fields: entity.fields, - patchForm: target.patchForm, - active: target.active, - }); - if (options.dryRun) { - results[idx] = { - recordId: target.recordId, - status: "preview", - payload, - }; - } else { - const res = await api.editRecord(client, corpId, payload); - results[idx] = { - recordId: target.recordId, - status: "updated", - payload, - result: res, - }; - } - } catch (error) { - results[idx] = { - recordId: target.recordId, - status: "failed", - error: error instanceof Error ? error.message : String(error), - }; - } - } - }; - - await Promise.all( - Array.from({ length: Math.min(concurrency, targets.length) }, () => worker()) - ); - return results; -} - -// ── 台账数学核对与声明式更新引擎 (Ledger Math & In-line Ops) ─────────────────── - -/** - * 根据字段名或标签模糊解析实体字段元数据 - */ -export function resolveEntityField( - entity: DatalinkEntity, - query: string -): DatalinkField | undefined { - return resolveDatalinkField(entity.fields, entity.id, query); -} - -/** - * 通用提取记录中某一字段的原始值 - */ -export function extractRecordFieldValue( - record: DatalinkRecord, - field: DatalinkField | string -): unknown { - const source = - record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink) - ? (record.dataLink as Record) - : record; - const fieldName = typeof field === "string" ? field : field.name; - const fieldLabel = typeof field === "string" ? undefined : field.label; - - let val = source[fieldName] ?? record[fieldName]; - if (val === undefined && fieldLabel) { - val = source[fieldLabel] ?? record[fieldLabel]; - } - if (val === undefined && record.form && typeof record.form === "object") { - val = (record.form as Record)[fieldName]; - if (val === undefined && fieldLabel) { - val = (record.form as Record)[fieldLabel]; - } - } - return val; -} - -/** - * 提取记录中某一字段的数值(兼容数值、货币对象与格式化字符串) - */ -export function extractNumericFieldValue( - record: DatalinkRecord, - field: DatalinkField | string -): number | null { - const val = extractRecordFieldValue(record, field); - if (val === null || val === undefined || val === "") return null; - if (typeof val === "number" && !Number.isNaN(val)) return val; - if (typeof val === "object" && !Array.isArray(val)) { - const std = (val as any).standard ?? (val as any).amount; - if (typeof std === "number" && !Number.isNaN(std)) return std; - if (typeof std === "string") { - const parsed = parseFloat(std); - if (!Number.isNaN(parsed)) return parsed; - } - } - if (typeof val === "string") { - const clean = val.replace(/^[¥$¥\s,]+/, "").replace(/,/g, ""); - const parsed = parseFloat(clean); - if (!Number.isNaN(parsed)) return parsed; - } - return null; -} - -/** - * 对记录进行聚合统计(COUNT, SUM, AVG, MIN, MAX,可选分组) - */ -export function aggregateRecordFields( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { - fields: string[]; - groupBy?: string; - } -): LedgerAggregateReport { - const resolvedFields = options.fields.map((f) => { - const resolved = resolveEntityField(entity, f); - return { - query: f, - field: resolved ?? { name: f, label: f, type: "number" }, - }; - }); - - const calcStats = (list: DatalinkRecord[]): Record => { - const stats: Record = {}; - for (const { query, field } of resolvedFields) { - let count = 0; - let sum = 0; - let min = Infinity; - let max = -Infinity; - - for (const r of list) { - const num = extractNumericFieldValue(r, field); - if (num !== null) { - count++; - sum += num; - if (num < min) min = num; - if (num > max) max = num; - } - } - - stats[query] = { - field: field.name, - fieldLabel: field.label || field.name, - count, - sum: Math.round(sum * 100) / 100, - avg: count > 0 ? Math.round((sum / count) * 100) / 100 : 0, - min: count > 0 ? min : 0, - max: count > 0 ? max : 0, - }; - } - return stats; - }; - - const overall = calcStats(records); - - let groups: GroupAggregateResult[] | undefined; - if (options.groupBy) { - const groupField = resolveEntityField(entity, options.groupBy) ?? { - name: options.groupBy, - label: options.groupBy, - type: "text", - }; - const groupMap = new Map(); - for (const r of records) { - const gVal = String(extractRecordFieldValue(r, groupField) ?? "(未填写)"); - const existing = groupMap.get(gVal); - if (existing) existing.push(r); - else groupMap.set(gVal, [r]); - } - - groups = Array.from(groupMap.entries()).map(([groupValue, groupRecords]) => ({ - groupValue, - count: groupRecords.length, - aggregates: calcStats(groupRecords), - })); - } - - return { - totalRecords: records.length, - overall, - groups, - }; -} - -/** - * 台账序号连续性检查与期望基线数学核对 - */ -export function auditLedgerContinuityAndBaseline( - records: DatalinkRecord[], - entity: DatalinkEntity, - options: { - sequenceField?: string; - expectedValues?: Array<{ - field: string; - targetValue: number; - tolerance?: number; - }>; - } -): LedgerContinuityReport { - const issues: ContinuityIssue[] = []; - const outliers: LedgerContinuityReport["outliers"] = []; - - let sequenceSummary: LedgerContinuityReport["sequenceSummary"] | undefined; - - // 1. 序号连续性核查 - if (options.sequenceField) { - const resolvedSeqField = resolveEntityField(entity, options.sequenceField) ?? { - name: options.sequenceField, - label: options.sequenceField, - type: "number", - }; - - const seqMap = new Map(); - const numbers: number[] = []; - - for (const r of records) { - const num = extractNumericFieldValue(r, resolvedSeqField); - if (num !== null) { - const intVal = Math.round(num); - numbers.push(intVal); - const existing = seqMap.get(intVal); - const rId = r.id || String(r.recordId || ""); - if (existing) existing.push(rId); - else seqMap.set(intVal, [rId]); - } - } - - if (numbers.length > 0) { - const min = Math.min(...numbers); - const max = Math.max(...numbers); - const missing: number[] = []; - const duplicates: number[] = []; - - for (let i = min; i <= max; i++) { - const count = seqMap.get(i)?.length ?? 0; - if (count === 0) { - missing.push(i); - issues.push({ - type: "MISSING_SEQUENCE", - field: resolvedSeqField.name, - message: `台账序号断层:缺少第 [${i}] 期记录`, - expected: i, - actual: null, - }); - } else if (count > 1) { - duplicates.push(i); - issues.push({ - type: "DUPLICATE_SEQUENCE", - field: resolvedSeqField.name, - message: `台账序号重号:第 [${i}] 期存在 ${count} 条重复记录 (${seqMap.get(i)?.join(", ")})`, - expected: 1, - actual: count, - }); - } - } - - sequenceSummary = { - field: resolvedSeqField.name, - fieldLabel: resolvedSeqField.label || resolvedSeqField.name, - min, - max, - expectedCount: max - min + 1, - actualCount: numbers.length, - missing, - duplicates, - }; - } - } - - // 2. 基线离群异常核对 - if (options.expectedValues && options.expectedValues.length > 0) { - for (const exp of options.expectedValues) { - const field = resolveEntityField(entity, exp.field) ?? { - name: exp.field, - label: exp.field, - type: "number", - }; - const tolerance = exp.tolerance ?? 0.05; - - for (const r of records) { - const val = extractNumericFieldValue(r, field); - if (val !== null) { - const diff = Math.abs(val - exp.targetValue); - if (diff > tolerance) { - const rId = r.id || String(r.recordId || ""); - outliers.push({ - recordId: rId, - field: field.name, - fieldLabel: field.label || field.name, - value: val, - expectedValue: exp.targetValue, - diff: Math.round(diff * 100) / 100, - }); - issues.push({ - type: "VALUE_OUTLIER", - recordId: rId, - field: field.name, - message: `记录 [${rId}] 字段 [${field.label || field.name}] 数值 [${val}] 偏离基线期望 [${exp.targetValue}] (差额: ${diff > 0 ? "+" : ""}${Math.round(diff * 100) / 100})`, - expected: exp.targetValue, - actual: val, - }); - } - } - } - } - } - - return { - totalRecords: records.length, - sequenceSummary, - issues, - outliers, - }; -} - -/** - * 客户端声明式筛选器(支持 ==, !=, >, >=, <, <=, in (...) 以及 && 组合) - */ -function splitPredicateParts(source: string, separator: string): string[] { - const parts: string[] = []; - let quote = "", depth = 0, start = 0; - for (let i = 0; i < source.length; i++) { - const char = source[i]; - if (quote) { - if (char === "\\") i++; - else if (char === quote) quote = ""; - continue; - } - if (char === "'" || char === '"') quote = char; - else if (char === "(") depth++; - else if (char === ")") { - if (--depth < 0) throw new ValidationError("筛选条件括号不匹配"); - } else if (depth === 0 && source.startsWith(separator, i)) { - parts.push(source.slice(start, i).trim()); - start = i + separator.length; - i += separator.length - 1; - } - } - if (quote || depth !== 0) throw new ValidationError("筛选条件引号或括号不匹配"); - parts.push(source.slice(start).trim()); - if (parts.some(part => !part)) throw new ValidationError("筛选条件或列表值不能为空"); - return parts; -} - -function predicateLiteral(raw: string): string | number | boolean | null { - if (/^(["']).*\1$/s.test(raw)) { - const value = raw.slice(1, -1); - if (raw[0] === '"') { - try { return JSON.parse(raw); } catch { throw new ValidationError(`筛选值不是有效字符串: ${raw}`); } - } - if (/(? boolean { - const conditions = splitPredicateParts(whereClause, "&&").map(cond => { - // 1. in 操作符: field in (v1, v2, v3) - const inMatch = cond.match(/^(.+?)\s+in\s*\((.*)\)$/i); - // 2. 比较操作符: ==, !=, >=, <=, >, <, = - const compMatch = inMatch ? null : cond.match(/^(.+?)\s*(==|!=|>=|<=|>|<|=)\s*(.+)$/s); - if (!inMatch && !compMatch) throw new ValidationError(`不支持的筛选条件: ${cond}`); - const field = predicateField(entity, (inMatch ?? compMatch)![1].trim()); - const op = inMatch ? "in" : compMatch![2]; - const targets = inMatch - ? splitPredicateParts(inMatch[2], ",").map(predicateLiteral) - : [predicateLiteral(compMatch![3].trim())]; - return (record: DatalinkRecord) => { - const actual = extractRecordFieldValue(record, field); - const equal = (target: string | number | boolean | null): boolean => { - if (target === null) return actual === null || actual === undefined; - if (typeof target === "number") return extractNumericFieldValue(record, field) === target; - return actual !== null && actual !== undefined && String(actual) === String(target); - }; - if (op === "in") return targets.some(equal); - // 字符串/布尔比较 - if (op === "=" || op === "==") return equal(targets[0]); - if (op === "!=") return !equal(targets[0]); - // 数值比较 - const value = extractNumericFieldValue(record, field); - const target = targets[0]; - if (value === null || typeof target !== "number") return false; - return op === ">" ? value > target : op === ">=" ? value >= target : op === "<" ? value < target : value <= target; - }; - }); - return record => conditions.every(condition => condition(record)); -} - -export function filterRecordsByPredicate( - records: DatalinkRecord[], - whereClause: string, - entity: DatalinkEntity -): DatalinkRecord[] { - if (!whereClause || !whereClause.trim()) return records; - return records.filter(compileRecordPredicate(whereClause, entity)); -} - -/** - * 解析 --set 表达式为字段更新补丁: "租赁费用 = 78787.55, 状态 = 待摊销" - */ -export function parseSetClause( - setClause: string, - entity: DatalinkEntity -): Record { - const result: Record = {}; - let assignments: string[]; - try { assignments = splitPredicateParts(setClause, ","); } - catch { throw new ValidationError("赋值表达式引号或括号不匹配,且赋值项不能为空"); } - - for (const assign of assignments) { - const eqIdx = assign.indexOf("="); - if (eqIdx === -1) throw new ValidationError(`赋值项缺少等号: ${assign}`); - const rawKey = assign.slice(0, eqIdx).trim(); - if (!rawKey) throw new ValidationError("赋值字段不能为空"); - let rawVal = assign.slice(eqIdx + 1).trim(); - - // 去除外层引号,同时保留显式字符串的类型与转义语义。 - const quoted = (rawVal.startsWith('"') && rawVal.endsWith('"')) || (rawVal.startsWith("'") && rawVal.endsWith("'")); - const literal = quoted ? predicateLiteral(rawVal) : undefined; - - const field = resolveEntityField(entity, rawKey); - const targetKey = field ? field.name : rawKey; - - // 类型智能转换 - if (quoted) { - result[targetKey] = literal; - } else if (rawVal === "true") { - result[targetKey] = true; - } else if (rawVal === "false") { - result[targetKey] = false; - } else if (rawVal === "null") { - result[targetKey] = null; - } else if (!Number.isNaN(Number(rawVal)) && rawVal !== "") { - result[targetKey] = Number(rawVal); - } else { - result[targetKey] = rawVal; - } - } - - return result; -} - -/** - * 解析 --expect 表达式为数值基线期望列表: "租赁费用 ~= 78787.55, 日折旧费 = 2626.25 +- 0.05" - */ -export function parseExpectClause( - expectClause: string -): Array<{ field: string; targetValue: number; tolerance?: number }> { - if (!expectClause || !expectClause.trim()) return []; - const parts = expectClause.split(/[,;]/).map((s) => s.trim()).filter(Boolean); - const results: Array<{ field: string; targetValue: number; tolerance?: number }> = []; - - for (const part of parts) { - const match = part.match( - /^(.+?)\s*(?:~=|==|=|\:)\s*([0-9.-]+)(?:\s*(?:\+\-|\+\/\-|±|\~)\s*([0-9.]+))?$/ - ); - if (match) { - const field = match[1].trim(); - const targetValue = parseFloat(match[2]); - const tolerance = match[3] ? parseFloat(match[3]) : undefined; - if (!Number.isNaN(targetValue)) { - results.push({ field, targetValue, tolerance }); - } - } - } - return results; -} +// datalink 业务服务出口;具体实现按职责拆分,内部模块避免反向导入此门面。 +export { + listPlatformEntities, + searchEntityRecords, + listImportJobs, + getImportResult, + toggleRecordState, + getRecordDetail, + getRecordFormSchema, + editRecord, + buildSafeRecordEditPayload, + safeEditRecord, + recomputeRecordLedger, + resolveEntity, + selectRecordFields, + fetchAllEntityRecords, + iterateAllEntityRecords, + normalizeDatalinkRecord, + batchSafeEditRecords, + resolveEntityField, + extractRecordFieldValue, + extractNumericFieldValue, +} from "./records.js"; +export type { + BatchEditTargetItem, + BatchEditItemResult, +} from "./records.js"; +export { + formatServerFieldExpr, + buildKeywordFilter, + buildServerFieldFilter, + compileRecordPredicate, + filterRecordsByPredicate, + parseSetClause, + parseExpectClause, +} from "./predicates.js"; +export type { + BuildKeywordFilterOptions, +} from "./predicates.js"; +export { + calculateEntityRecordStats, + auditEntityRecords, + aggregateRecordFields, + auditLedgerContinuityAndBaseline, +} from "./audit.js"; +export type { + DatalinkAuditIssue, + DatalinkAuditReport, +} from "./audit.js"; + +export type { + SafeRecordEditOptions, +} from "./api.js"; diff --git a/src/domains/platform/workflow/README.workflow.md b/src/domains/platform/workflow/README.workflow.md index 3975f0a..41d1f8e 100644 --- a/src/domains/platform/workflow/README.workflow.md +++ b/src/domains/platform/workflow/README.workflow.md @@ -195,3 +195,21 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 ` 2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析; 3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退; 4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。 + + +## 模块内部职责 + +工作流的模型、传输和服务出口都位于本目录,具体编排按职责分开: + +| 文件 | 职责 | +|---|---| +| [api.ts](./api.ts)、[types.ts](./types.ts) | HTTP 请求/响应校验与工作流 Zod 模型 | +| [services.ts](./services.ts) | 显式业务出口及既有能力目录的统一导出 | +| [queries.ts](./queries.ts) | 列表、历史、执行读取和跨应用工作流检索 | +| [configuration.ts](./configuration.ts) | 创建、复制、保存、启停、快照清洗与部分成功恢复 | +| [execution.ts](./execution.ts)、[execution-context.ts](./execution-context.ts) | 执行树展开、失败节点提取及执行实例上下文 | +| [diff.ts](./diff.ts) | 配置快照与执行结果差异 | +| [debug.ts](./debug.ts) | 调试、输入采样和结果汇总 | +| [catalog.ts](./catalog.ts) | DSL、节点权限、枚举字典与回退 | + +内部实现直接导入所属模块,不反向导入 services 门面。watch 的 tracker 使用 execution,工作流报告类型直接引用 branch/types,避免通过聚合出口形成循环。跨应用查询只通过 applications 的公开业务服务取得应用;各子模块禁止绕过服务直接调用兄弟模块 api。 diff --git a/src/domains/platform/workflow/catalog.ts b/src/domains/platform/workflow/catalog.ts new file mode 100644 index 0000000..a910698 --- /dev/null +++ b/src/domains/platform/workflow/catalog.ts @@ -0,0 +1,125 @@ +import { KyInstance } from "ky"; +import { CorpConfig } from "../../../core/config/types.js"; +import * as api from "./api.js"; +import { PermissionError, ValidationError } from "../../../core/errors.js"; + + +export function listDsl(...args: Parameters) { + return api.listDsl(...args); +} + + +export function listStaffs(...args: Parameters) { + return api.listStaffs(...args); +} + + +export function getWorkflowEnumOptions(...args: Parameters) { + return api.getWorkflowEnumOptions(...args); +} + + +export async function resolveWorkflowEnumOptions( + client?: import("ky").KyInstance, + thirdId = "action", + platformId?: string +): Promise> { + if (client) { + try { + const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId); + if (remote && remote.length > 0) { + return remote.map((item) => ({ + code: item.code, + label: item.label, + name: item.name || item.label, + })); + } + } catch { + // 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典 + } + } + + if (thirdId.toLowerCase() === "action") { + const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./enums.js"); + return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({ + code: item.code, + label: item.label, + name: item.name, + description: item.description, + })); + } + + return []; +} + + +// ── 工作流企业可用节点探针与灰度开通 ────────────────────────────────────────── + +export async function getWorkflowAvailableNodes( + client: KyInstance +): Promise { + const catalog = await api.listDslCatalog(client); + const allTypes = new Set(); + + for (const item of catalog.action) { + if (item.type) allTypes.add(item.type); + } + for (const item of catalog.control) { + if (item.type) allTypes.add(item.type); + } + for (const item of catalog.trigger) { + if (item.type) allTypes.add(item.type); + } + + return { + allTypes, + actionNodes: catalog.action, + controlNodes: catalog.control, + triggerNodes: catalog.trigger, + }; +} + + +export async function grantWorkflowNodes( + corp: CorpConfig, + options: import("./types.js").GrantWorkflowNodesOptions +): Promise { + if (!options.nodes || options.nodes.length === 0) { + throw new ValidationError("必须指定至少一个需要开通的节点名称或类型"); + } + + // 1. 管理员密码保护预留设计 + const adminPassword = process.env.HOSE_ADMIN_PASSWORD; + if (adminPassword) { + if (!options.password || options.password !== adminPassword) { + throw new PermissionError( + "灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码" + ); + } + } + + // 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type) + const { findGrayNode } = await import("./nodes/gray-nodes-catalog.js"); + const normalizedNodes = options.nodes.map((node) => { + const matched = findGrayNode(node); + return matched ? matched.type : node.trim(); + }); + + const token = corp.credentials?.accessToken; + const corpId = corp.corpId || corp.credentials?.corpId || corp.id; + const baseUrl = corp.baseUrl; + + if (!token) { + throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请"); + } + + // 3. 调用开通 API + const result = await api.grantWorkflowNodesApi({ + token, + corpId, + nodes: normalizedNodes, + baseUrl, + }); + + return result; +} diff --git a/src/domains/platform/workflow/configuration.ts b/src/domains/platform/workflow/configuration.ts new file mode 100644 index 0000000..3a5a043 --- /dev/null +++ b/src/domains/platform/workflow/configuration.ts @@ -0,0 +1,210 @@ +import { KyInstance } from "ky"; +import { WorkflowSavePartialError } from "./save-error.js"; +import * as api from "./api.js"; +import { WorkflowTask } from "./types.js"; + + +export function sanitizeWorkflowSnapshot( + detail: import("./types.js").WorkflowDetail +): import("./types.js").WorkflowDetail { + const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; + if (Array.isArray(cloned.$snapshot)) { + cloned.$snapshot = cloned.$snapshot.map((entry) => { + if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) { + return { + ...entry, + value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"), + }; + } + return entry; + }); + } + return cloned; +} + + +export async function updateWorkflow( + client: KyInstance, + workflow: import("./types.js").WorkflowDetail, + platformId?: string +) { + // 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。 + const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length + ? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] } + : workflow; + const sanitized = sanitizeWorkflowSnapshot(payload); + const updated = await api.updateWorkflow(client, sanitized); + // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 + 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, + options: { label?: string; platformId?: string } = {} +): Promise { + const detail = await api.getWorkflowDetail(client, pipelineId); + const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; + if (options.label) { + cloned.label = options.label; + } else if (!cloned.label.includes("副本")) { + cloned.label = `${cloned.label} 副本`; + } + if (options.platformId) { + cloned.platformId = options.platformId; + } + // 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本 + if (cloned.tasks?.[0]?.type === "webhook") { + (cloned.tasks[0] as any).urlPath = crypto.randomUUID(); + delete (cloned.tasks[0] as any).sampleId; + } + const result = await api.copyWorkflow(client, pipelineId, cloned); + if (options.label && result.label !== options.label) { + result.label = options.label; + return updateWorkflow(client, result, options.platformId ?? (result as any).platformId); + } + return result; +} + + +export interface CreateWorkflowOptions { + label?: string; + platformId?: string; + trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string; + file?: string; + workflow?: Record; + state?: number; + desc?: string; +} + + +export function buildInitialTriggerTask(triggerType: string): WorkflowTask { + const norm = triggerType.toLowerCase().trim(); + switch (norm) { + case "webhook": + return { + name: "trigger_webhook", + type: "webhook", + label: "Webhook触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + urlPath: crypto.randomUUID(), + params: [], + }; + case "clock": + case "schedule": + case "timer": + return { + name: "trigger_clock", + type: "clock", + label: "定时触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + cron: "0 0 * * *", + timeZone: "Asia/Shanghai", + }; + case "datalink": + case "data-link": + case "entity": + return { + name: "trigger_datalink_create", + type: "ekuaibao-datalink-create-trigger", + label: "业务对象新增时触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + case "flowform": + case "flow": + case "bill": + return { + name: "trigger_flowform", + type: "ekuaibao-flowform-trigger", + label: "单据审批事件触发", + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + default: + return { + name: `trigger_${norm.replace(/-/g, "_")}`, + type: norm, + label: `${norm}触发`, + groupName: "trigger", + orderIndex: 0, + levelIndex: [0], + status: "active", + }; + } +} + + +export async function createWorkflow( + client: import("ky").KyInstance, + options: CreateWorkflowOptions = {} +): Promise { + let base: Record = {}; + if (options.file) { + const fs = await import("fs/promises"); + const raw = await fs.readFile(options.file, "utf-8"); + base = JSON.parse(raw); + } else if (options.workflow) { + base = JSON.parse(JSON.stringify(options.workflow)); + } + + const payload: Record = { + ...base, + label: options.label || base.label || "未命名流程", + state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承 + }; + + if (options.platformId || base.platformId) { + payload.platformId = options.platformId || base.platformId; + } + if (options.desc || base.desc) { + payload.desc = options.desc || base.desc; + } + + // 触发器节点初始化 + if (!payload.tasks || payload.tasks.length === 0) { + if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") { + payload.tasks = [buildInitialTriggerTask(options.trigger)]; + } else { + payload.tasks = []; + } + } else if (payload.tasks[0]?.type === "webhook") { + if (!payload.tasks[0].urlPath) { + payload.tasks[0].urlPath = crypto.randomUUID(); + } + } + + return api.createWorkflow(client, payload); +} + + +export function deleteWorkflow(...args: Parameters) { + return api.deleteWorkflow(...args); +} + + +export function toggleWorkflow(...args: Parameters) { + return api.toggleWorkflow(...args); +} diff --git a/src/domains/platform/workflow/debug.ts b/src/domains/platform/workflow/debug.ts new file mode 100644 index 0000000..682ee80 --- /dev/null +++ b/src/domains/platform/workflow/debug.ts @@ -0,0 +1,151 @@ +import * as api from "./api.js"; +import { ValidationError } from "../../../core/errors.js"; +import { explainConditionBranches } from "./branch/index.js"; +import { WorkflowJobDetail } from "./types.js"; +import { extractFailureExecutions } from "./execution.js"; + + +export function getWebhookInfo(...args: Parameters) { + return api.getWebhookInfo(...args); +} + + +export function sampleWorkflowData(...args: Parameters) { + return api.sampleWorkflowData(...args); +} + + +export function getWorkflowDebugSource(...args: Parameters) { + return api.getWorkflowDebugSource(...args); +} + + +export function triggerWorkflowDebug(...args: Parameters) { + return api.triggerWorkflowDebug(...args); +} + + +export async function runWorkflowDebugTest( + client: import("ky").KyInstance, + pipelineId: string, + options: { + flowCodeOrId?: string; + data?: Record; + triggerCategory?: import("./types.js").WorkflowTriggerCategory; + triggerType?: string; + triggerLabel?: string; + autoPublish?: boolean; + timeoutMs?: number; + pollIntervalMs?: number; + } = {} +): Promise { + if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) { + throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数"); + } + let targetEntityId = options.flowCodeOrId ?? ""; + const code = options.flowCodeOrId; + const isDirectCode = !code || code.includes("-") || code.startsWith("ID01"); + if (code && !isDirectCode) { + try { + const source = await api.getWorkflowDebugSource(client, pipelineId, { + page: 1, + pageSize: 10, + keywords: code, + }); + const matched = source.items.find( + (item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code) + ); + if (matched) { + targetEntityId = matched.id; + } + } catch { + // 关键字搜索超时或失败时直接回退使用传入值 + } + } + + const jobId = await api.triggerWorkflowDebug(client, pipelineId, { + entityId: targetEntityId || undefined, + data: options.data, + autoPublish: options.autoPublish ?? false, + }); + + const timeoutMs = options.timeoutMs ?? 15000; + const pollIntervalMs = options.pollIntervalMs ?? 500; + const start = Date.now(); + const diagnosticsErrors: Array<{ source: string; message: string }> = []; + const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) }); + const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); + const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase(); + let finalJob: WorkflowJobDetail | undefined; + let pollingFailed = false; + + while (Date.now() - start < timeoutMs) { + try { + const job = await api.getJob(client, jobId); + finalJob = job; + if (terminal.has(jobState(job))) break; + } catch (error) { + // 任务刚创建可能存在短延时,继续轮询 + const status = (error as { status?: number; response?: { status?: number } } | null)?.status + ?? (error as { response?: { status?: number } } | null)?.response?.status; + if (status !== 404) { + recordError("job", error); + pollingFailed = true; + break; + } + } + await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start))))); + } + + if (!finalJob && !pollingFailed) { + try { finalJob = await api.getJob(client, jobId); } + catch (error) { recordError("job", error); pollingFailed = true; } + } + const timedOut = !pollingFailed && !terminal.has(jobState(finalJob)); + const [treeResult, failuresResult] = await Promise.allSettled([ + api.getJobExecutionTree(client, jobId), + api.getJobFailedExecutions(client, jobId), + ]); + const tree = treeResult.status === "fulfilled" ? treeResult.value : []; + const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : []; + if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason); + if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason); + + const rawFailed = extractFailureExecutions(tree, failedItems); + const diagnosticsComplete = diagnosticsErrors.length === 0; + const status = jobState(finalJob); + const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0; + let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete"; + if (timedOut) outcome = "timed_out"; + else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; + else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed"; + const conditionDiagnoses = explainConditionBranches(tree); + + return { + jobId, + pipelineId, + status, + outcome, + timedOut, + diagnosticsComplete, + diagnosticsErrors, + runType: finalJob?.runType || "DEBUG", + durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined, + targetEntityId, + triggerCategory: options.triggerCategory, + triggerType: options.triggerType, + triggerLabel: options.triggerLabel, + executionTree: tree, + failedExecutions: rawFailed, + conditionDiagnoses, + }; +} + + +export async function getWorkflowSampleData( + client: import("ky").KyInstance, + pipelineId: string, + type = "webhook" +): Promise { + return api.getWorkflowSampleData(client, pipelineId, type); +} diff --git a/src/domains/platform/workflow/diff.ts b/src/domains/platform/workflow/diff.ts new file mode 100644 index 0000000..94c49b2 --- /dev/null +++ b/src/domains/platform/workflow/diff.ts @@ -0,0 +1,298 @@ +import { indexExecutionContexts } from "./execution-context.js"; +import { WorkflowTask, WorkflowTaskExecution, WorkflowSnapshot, WorkflowSnapshotDiff, TaskConfigDiff, WorkflowJobDetail, WorkflowJobDiff, NodeExecutionDiff } from "./types.js"; +import { flattenWorkflowTasks } from "./execution.js"; + + +/** + * 快速生成标准 Unified Diff 文本 + */ +export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string { + if (a === b) return ""; + const linesA = a.split(/\r?\n/); + const linesB = b.split(/\r?\n/); + const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`]; + + let start = 0; + while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) { + start++; + } + let endA = linesA.length - 1; + let endB = linesB.length - 1; + while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) { + endA--; + endB--; + } + + const hunkStart = Math.max(0, start - 2); + const hunkEndA = Math.min(linesA.length, endA + 3); + const hunkEndB = Math.min(linesB.length, endB + 3); + + output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`); + for (let i = hunkStart; i < start; i++) { + output.push(` ${linesA[i]}`); + } + for (let i = start; i <= endA; i++) { + output.push(`- ${linesA[i]}`); + } + for (let i = start; i <= endB; i++) { + output.push(`+ ${linesB[i]}`); + } + for (let i = endA + 1; i < hunkEndA; i++) { + output.push(` ${linesA[i]}`); + } + return output.join("\n"); +} + + +/** + * 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异 + */ +export function diffWorkflowSnapshots( + snapshotA: WorkflowSnapshot, + snapshotB: WorkflowSnapshot +): WorkflowSnapshotDiff { + const tasksA = flattenWorkflowTasks(snapshotA.tasks); + const tasksB = flattenWorkflowTasks(snapshotB.tasks); + const indexPaths = (tasks: WorkflowTask[] = [], prefix = "tasks", paths = new Map()): Map => { + tasks.forEach((task, i) => { + const path = `${prefix}.${i}`; + if (task.name) paths.set(task.name, path); + if (task.tasks) indexPaths(task.tasks, `${path}.tasks`, paths); + }); + return paths; + }; + const pathsA = indexPaths(snapshotA.tasks || []); + const pathsB = indexPaths(snapshotB.tasks || []); + + const mapA = new Map(); + for (const t of tasksA) { + if (t?.name) mapA.set(t.name, t); + } + + const mapB = new Map(); + for (const t of tasksB) { + if (t?.name) mapB.set(t.name, t); + } + + const addedTasks: string[] = []; + const removedTasks: string[] = []; + const modifiedTasks: TaskConfigDiff[] = []; + + // 1. 查找新增节点 + for (const [name, tB] of mapB) { + if (!mapA.has(name)) { + addedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label, + type: tB.type, + changeType: "ADDED", + configChanges: [], + }); + } + } + + // 2. 查找删除与修改节点 + for (const [name, tA] of mapA) { + const tB = mapB.get(name); + if (!tB) { + removedTasks.push(name); + modifiedTasks.push({ + taskName: name, + displayName: tA.displayName || tA.label, + type: tA.type, + changeType: "REMOVED", + configChanges: [], + }); + continue; + } + + // 两者均存在,深度比较配置与代码 + const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = []; + let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined; + let filterDiff: { from?: unknown; to?: unknown } | undefined; + + // 代码脚本比较 + const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined; + const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined; + if (codeA !== codeB) { + codeDiff = { + from: codeA, + to: codeB, + unifiedDiff: generateTextDiff( + codeA || "", + codeB || "", + `${snapshotA.version || snapshotA.id}`, + `${snapshotB.version || snapshotB.id}` + ), + }; + } + + // 过滤条件比较 (combineFilters / filters) + const filtersA = (tA as any).combineFilters ?? (tA as any).filters; + const filtersB = (tB as any).combineFilters ?? (tB as any).filters; + if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) { + filterDiff = { from: filtersA, to: filtersB }; + } + + // 关键字段变动比较 + const checkFields = [...new Set([...Object.keys(tA), ...Object.keys(tB)])] + .filter(field => !["name", "tasks", "code", "combineFilters", "filters"].includes(field)); + if (pathsA.get(name) !== pathsB.get(name)) { + configChanges.push({ field: "$path", from: pathsA.get(name), to: pathsB.get(name) }); + } + for (const f of checkFields) { + const valA = (tA as any)[f]; + const valB = (tB as any)[f]; + if (JSON.stringify(valA) !== JSON.stringify(valB)) { + configChanges.push({ field: f, from: valA, to: valB }); + } + } + + if (codeDiff || filterDiff || configChanges.length > 0) { + modifiedTasks.push({ + taskName: name, + displayName: tB.displayName || tB.label || tA.displayName || tA.label, + type: tB.type || tA.type, + changeType: "MODIFIED", + codeDiff, + filterDiff, + configChanges, + }); + } + } + + return { + snapshotA: { + id: snapshotA.id, + version: snapshotA.version, + updateTime: snapshotA.updateTime, + staffName: snapshotA.staffName || snapshotA.staffId || undefined, + }, + snapshotB: { + id: snapshotB.id, + version: snapshotB.version, + updateTime: snapshotB.updateTime, + staffName: snapshotB.staffName || snapshotB.staffId || undefined, + }, + addedTasks, + removedTasks, + modifiedTasks, + summary: { + totalA: tasksA.length, + totalB: tasksB.length, + changedCount: modifiedTasks.length, + }, + }; +} + + +/** + * 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息 + */ +export function diffWorkflowJobs( + jobA: WorkflowJobDetail, + treeA: WorkflowTaskExecution[], + jobB: WorkflowJobDetail, + treeB: WorkflowTaskExecution[] +): WorkflowJobDiff { + const flatA = indexExecutionContexts(treeA); + const flatB = indexExecutionContexts(treeB); + const byKeyA = new Map(flatA.map(context => [context.key, context])); + const byKeyB = new Map(flatB.map(context => [context.key, context])); + const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]); + + const nodes: NodeExecutionDiff[] = []; + let divergedNodesCount = 0; + let statusDiffCount = 0; + + for (const key of allKeys) { + const contextA = byKeyA.get(key); + const contextB = byKeyB.get(key); + const nodeA = contextA?.node; + const nodeB = contextB?.node; + const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed"; + + const statusA = nodeA?.status; + const statusB = nodeB?.status; + const isStatusDiff = statusA !== statusB; + if (isStatusDiff) statusDiffCount++; + + // 比较 inputs + const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const payloadFields = (value: unknown): Record => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record : { $value: value }; + const inA = payloadFields(nodeA?.inputs); + const inB = payloadFields(nodeB?.inputs); + const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)])); + for (const k of inputKeys) { + if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) { + inputsDiff.push({ field: k, from: inA[k], to: inB[k] }); + } + } + + // 比较 outputs + const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; + const outA = payloadFields(nodeA?.outputs ?? nodeA?.output); + const outB = payloadFields(nodeB?.outputs ?? nodeB?.output); + const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)])); + for (const k of outputKeys) { + if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) { + outputsDiff.push({ field: k, from: outA[k], to: outB[k] }); + } + } + + const isDiverged = + !nodeA || + !nodeB || + isStatusDiff || + JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) || + inputsDiff.length > 0 || outputsDiff.length > 0; + + if (isDiverged) divergedNodesCount++; + + nodes.push({ + taskName: name, + instanceKey: key, + currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined, + displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined, + type: nodeB?.type || nodeA?.type, + statusA, + statusB, + durationMsA: nodeA?.executionTime, + durationMsB: nodeB?.executionTime, + errorA: nodeA?.error, + errorB: nodeB?.error, + inputsDiff, + outputsDiff, + diverged: isDiverged, + }); + } + + return { + jobA: { + id: jobA.id, + pipelineId: jobA.pipelineId, + state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined, + startTime: jobA.startTime ? String(jobA.startTime) : undefined, + durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined, + hasError: Boolean(jobA.hasError), + errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined, + }, + jobB: { + id: jobB.id, + pipelineId: jobB.pipelineId, + state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined, + startTime: jobB.startTime ? String(jobB.startTime) : undefined, + durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined, + hasError: Boolean(jobB.hasError), + errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined, + }, + nodes, + summary: { + totalNodesA: flatA.length, + totalNodesB: flatB.length, + divergedNodesCount, + statusDiffCount, + }, + }; +} diff --git a/src/domains/platform/workflow/execution.ts b/src/domains/platform/workflow/execution.ts new file mode 100644 index 0000000..b43a7e3 --- /dev/null +++ b/src/domains/platform/workflow/execution.ts @@ -0,0 +1,135 @@ +import { WorkflowTask, WorkflowTaskExecution } from "./types.js"; + + +/** + * 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组) + */ +export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] { + const result: WorkflowTaskExecution[] = []; + + function visit(node: any) { + if (!node || typeof node !== "object") return; + result.push(node as WorkflowTaskExecution); + + const children = node.children || node.tasks || node.subTasks || node.items; + if (Array.isArray(children)) { + for (const child of children) { + visit(child); + } + } + } + + for (const node of nodes) { + visit(node); + } + + return result; +} + + +/** + * 精准判定某个节点是否执行异常或报错 + */ +export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean { + if (!node) return false; + const anyNode = node as any; + + if (node.error?.message || anyNode.errorMessage) return true; + if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true; + if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true; + if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true; + if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true; + + return false; +} + + +/** + * 提取并去重执行树中的全部异常失败节点 + */ +export function extractFailureExecutions( + tree: WorkflowTaskExecution[], + failedItems: WorkflowTaskExecution[] = [] +): WorkflowTaskExecution[] { + const flattened = flattenExecutionTree(tree); + const map = new Map(); + + for (const item of failedItems) { + if (item?.id) { + map.set(item.id, item); + } + } + + for (const node of flattened) { + if (node?.id && isTaskExecutionFailed(node)) { + const existing = map.get(node.id); + if (!existing) { + map.set(node.id, node); + } else { + map.set(node.id, { + ...node, + ...existing, + error: existing.error ?? node.error, + inputs: existing.inputs ?? (node as any).inputs, + outputs: existing.outputs ?? (node as any).outputs, + }); + } + } + } + + return Array.from(map.values()); +} + + +/** + * 按 ID、name、displayName 或 label 查找节点 + */ +export function findExecutionNode( + tree: WorkflowTaskExecution[], + query: string +): WorkflowTaskExecution | undefined { + const flattened = flattenExecutionTree(tree); + const q = query.trim().toLowerCase(); + if (!q) return undefined; + + // 1. 精确匹配 ID 或 name + const exact = flattened.find( + (n) => + n.id?.toLowerCase() === q || + n.name?.toLowerCase() === q || + n.displayName?.toLowerCase() === q + ); + if (exact) return exact; + + // 2. 包含匹配 name、label、displayName + return flattened.find( + (n) => + n.name?.toLowerCase().includes(q) || + n.label?.toLowerCase().includes(q) || + n.displayName?.toLowerCase().includes(q) + ); +} + + +// ── 工作流快照与 Job 差异比对核心算法 ────────────────────────────────────────── + +/** + * 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点) + */ +export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] { + if (!tasks || !Array.isArray(tasks)) return []; + const result: WorkflowTask[] = []; + + function walk(list: WorkflowTask[]) { + for (const t of list) { + if (!t) continue; + result.push(t); + if (Array.isArray(t.tasks) && t.tasks.length > 0) { + walk(t.tasks); + } + } + } + + walk(tasks); + return result; +} diff --git a/src/domains/platform/workflow/queries.ts b/src/domains/platform/workflow/queries.ts new file mode 100644 index 0000000..0cdf8b2 --- /dev/null +++ b/src/domains/platform/workflow/queries.ts @@ -0,0 +1,206 @@ +import { listBasicPlatforms } from "../applications/services.js"; +import { KyInstance } from "ky"; +import { CorpConfig } from "../../../core/config/types.js"; +import * as api from "./api.js"; +import { WorkflowSummary, WorkflowListAllError, WorkflowTask, WorkflowWithMatches, TaskMatch } from "./types.js"; + + +export interface WorkflowClients { + corp: CorpConfig; + ekbClient: KyInstance; + easoClient: KyInstance; +} + + +export function listWorkflows(...args: Parameters) { + return api.listWorkflows(...args); +} + + +export function getWorkflowStats(...args: Parameters) { + return api.getWorkflowStats(...args); +} + + +export function getWorkflowCharge(...args: Parameters) { + return api.getWorkflowCharge(...args); +} + + +export function getWorkflowDetail(...args: Parameters) { + return api.getWorkflowDetail(...args); +} + + +export function listWorkflowSnapshots(...args: Parameters) { + return api.listWorkflowSnapshots(...args); +} + + +export function getWorkflowSnapshot(...args: Parameters) { + return api.getWorkflowSnapshot(...args); +} + + +export function listWorkflowLogs(...args: Parameters) { + return api.listWorkflowLogs(...args); +} + + +export function listRunningJobs(...args: Parameters) { + return api.listRunningJobs(...args); +} + + +export function getJob(...args: Parameters) { + return api.getJob(...args); +} + + +export function getJobExecutionTree(...args: Parameters) { + return api.getJobExecutionTree(...args); +} + + +export function getJobFailedExecutions(...args: Parameters) { + return api.getJobFailedExecutions(...args); +} + + +export function getJobExecutionLevel(...args: Parameters) { + return api.getJobExecutionLevel(...args); +} + + +export function getExecutionLogs(...args: Parameters) { + return api.getExecutionLogs(...args); +} + + +// ── 服务层:跨应用聚合 ─────────────────────────────────────────────────────── + +export interface ListAllWorkflowsOptions { + page?: number; + pageSize?: number; +} + + +export interface ListAllWorkflowsResult { + workflows: WorkflowSummary[]; + errors: WorkflowListAllError[]; +} + + +export async function listAllWorkflows( + clients: WorkflowClients, + options: ListAllWorkflowsOptions = {} +): Promise { + const { ekbClient, easoClient, corp } = clients; + const page = options.page ?? 1; + const pageSize = options.pageSize ?? 20; + + const platforms = await listBasicPlatforms(ekbClient, corp.credentials.corpId); + const enabledPlatforms = platforms.filter((p) => p.active !== false); + + const workflows: WorkflowSummary[] = []; + const errors: WorkflowListAllError[] = []; + + await Promise.all( + enabledPlatforms.map(async (platform) => { + try { + const pageResult = await api.listWorkflows( + easoClient, + platform.id, + page, + pageSize + ); + for (const workflow of pageResult.pipelineList) { + workflows.push({ + ...workflow, + platformId: platform.id, + platformName: platform.name, + }); + } + } catch (err) { + errors.push({ + platformId: platform.id, + platformName: platform.name, + error: err instanceof Error ? err.message : String(err), + }); + } + }) + ); + + return { workflows, errors }; +} + + +function collectTasksByType( + tasks: WorkflowTask[], + taskType: string, + matches: TaskMatch[] = [] +): TaskMatch[] { + for (const task of tasks) { + if (task.type === taskType) { + matches.push({ + taskName: task.name, + taskType: task.type, + levelIndex: task.levelIndex, + }); + } + if ("tasks" in task && Array.isArray(task.tasks)) { + collectTasksByType(task.tasks as WorkflowTask[], taskType, matches); + } + } + return matches; +} + + +export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions { + includeDetail?: boolean; +} + + +export interface FindWorkflowsByTaskTypeResult { + workflows: WorkflowWithMatches[]; + errors: WorkflowListAllError[]; +} + + +export async function findWorkflowsByTaskType( + clients: WorkflowClients, + taskType: string, + options: FindWorkflowsByTaskTypeOptions = {} +): Promise { + const { easoClient } = clients; + const { includeDetail, ...listOptions } = options; + + const all = await listAllWorkflows(clients, listOptions); + const matched: WorkflowWithMatches[] = []; + const detailErrors: WorkflowListAllError[] = []; + + for (const workflow of all.workflows) { + let tasks = workflow.tasks; + + if (includeDetail) { + try { + const detail = await api.getWorkflowDetail(easoClient, workflow.id); + tasks = detail.tasks; + } catch (err) { + detailErrors.push({ + platformId: workflow.platformId, + platformName: workflow.platformName, + error: err instanceof Error ? err.message : String(err), + }); + continue; + } + } + + const matchedTasks = collectTasksByType(tasks, taskType); + if (matchedTasks.length > 0) { + matched.push({ ...workflow, matchedTasks }); + } + } + + return { workflows: matched, errors: [...all.errors, ...detailErrors] }; +} diff --git a/src/domains/platform/workflow/services.ts b/src/domains/platform/workflow/services.ts index 60898c0..3e4d01a 100644 --- a/src/domains/platform/workflow/services.ts +++ b/src/domains/platform/workflow/services.ts @@ -1,963 +1,69 @@ -import { listBasicPlatforms } from "../applications/services.js"; -import { KyInstance } from "ky"; -import { CorpConfig } from "../../../core/config/types.js"; -import { WorkflowSavePartialError } from "./save-error.js"; -import * as api from "./api.js"; -import { PermissionError, ValidationError } from "../../../core/errors.js"; -import { explainConditionBranches } from "./branch/index.js"; -import { indexExecutionContexts } from "./execution-context.js"; -import { - WorkflowSummary, - WorkflowListAllError, - WorkflowTask, - WorkflowTaskExecution, - WorkflowWithMatches, - TaskMatch, - WorkflowSnapshot, - WorkflowSnapshotDiff, - TaskConfigDiff, - WorkflowJobDetail, - WorkflowJobDiff, - NodeExecutionDiff, -} from "./types.js"; - -export interface WorkflowClients { - corp: CorpConfig; - ekbClient: KyInstance; - easoClient: KyInstance; -} - -export function listWorkflows(...args: Parameters) { - return api.listWorkflows(...args); -} - -export function getWorkflowStats(...args: Parameters) { - return api.getWorkflowStats(...args); -} - -export function getWorkflowCharge(...args: Parameters) { - return api.getWorkflowCharge(...args); -} - -export function getWorkflowDetail(...args: Parameters) { - return api.getWorkflowDetail(...args); -} - -export function sanitizeWorkflowSnapshot( - detail: import("./types.js").WorkflowDetail -): import("./types.js").WorkflowDetail { - const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; - if (Array.isArray(cloned.$snapshot)) { - cloned.$snapshot = cloned.$snapshot.map((entry) => { - if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) { - return { - ...entry, - value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"), - }; - } - return entry; - }); - } - return cloned; -} - -export async function updateWorkflow( - client: KyInstance, - workflow: import("./types.js").WorkflowDetail, - platformId?: string -) { - // 前端保存时会带上触发输入 $platformId;缺少它会导致平台把内置节点 desc 重置为「」。 - const payload: import("./types.js").WorkflowDetail = platformId && !workflow.inputs?.length - ? { ...workflow, inputs: [{ key: "$platformId", value: platformId }] } - : workflow; - const sanitized = sanitizeWorkflowSnapshot(payload); - const updated = await api.updateWorkflow(client, sanitized); - // 复刻前端“保存更新”:主线 PUT 之后刷新 chooses。 - 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, - options: { label?: string; platformId?: string } = {} -): Promise { - const detail = await api.getWorkflowDetail(client, pipelineId); - const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail; - if (options.label) { - cloned.label = options.label; - } else if (!cloned.label.includes("副本")) { - cloned.label = `${cloned.label} 副本`; - } - if (options.platformId) { - cloned.platformId = options.platformId; - } - // 如果首节点是 Webhook,重新分配独立唯一的 urlPath,并清理历史脏样本 - if (cloned.tasks?.[0]?.type === "webhook") { - (cloned.tasks[0] as any).urlPath = crypto.randomUUID(); - delete (cloned.tasks[0] as any).sampleId; - } - const result = await api.copyWorkflow(client, pipelineId, cloned); - if (options.label && result.label !== options.label) { - result.label = options.label; - return updateWorkflow(client, result, options.platformId ?? (result as any).platformId); - } - return result; -} - -export interface CreateWorkflowOptions { - label?: string; - platformId?: string; - trigger?: "webhook" | "clock" | "flowform" | "datalink" | "none" | string; - file?: string; - workflow?: Record; - state?: number; - desc?: string; -} - -export function buildInitialTriggerTask(triggerType: string): WorkflowTask { - const norm = triggerType.toLowerCase().trim(); - switch (norm) { - case "webhook": - return { - name: "trigger_webhook", - type: "webhook", - label: "Webhook触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - urlPath: crypto.randomUUID(), - params: [], - }; - case "clock": - case "schedule": - case "timer": - return { - name: "trigger_clock", - type: "clock", - label: "定时触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - cron: "0 0 * * *", - timeZone: "Asia/Shanghai", - }; - case "datalink": - case "data-link": - case "entity": - return { - name: "trigger_datalink_create", - type: "ekuaibao-datalink-create-trigger", - label: "业务对象新增时触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - case "flowform": - case "flow": - case "bill": - return { - name: "trigger_flowform", - type: "ekuaibao-flowform-trigger", - label: "单据审批事件触发", - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - default: - return { - name: `trigger_${norm.replace(/-/g, "_")}`, - type: norm, - label: `${norm}触发`, - groupName: "trigger", - orderIndex: 0, - levelIndex: [0], - status: "active", - }; - } -} - -export async function createWorkflow( - client: import("ky").KyInstance, - options: CreateWorkflowOptions = {} -): Promise { - let base: Record = {}; - if (options.file) { - const fs = await import("fs/promises"); - const raw = await fs.readFile(options.file, "utf-8"); - base = JSON.parse(raw); - } else if (options.workflow) { - base = JSON.parse(JSON.stringify(options.workflow)); - } - - const payload: Record = { - ...base, - label: options.label || base.label || "未命名流程", - state: options.state ?? 0, // 强制初始状态为草稿未启用 (0),防御合思服务端默认 state=1 与模板继承 - }; - - if (options.platformId || base.platformId) { - payload.platformId = options.platformId || base.platformId; - } - if (options.desc || base.desc) { - payload.desc = options.desc || base.desc; - } - - // 触发器节点初始化 - if (!payload.tasks || payload.tasks.length === 0) { - if (options.trigger && options.trigger !== "none" && options.trigger !== "empty") { - payload.tasks = [buildInitialTriggerTask(options.trigger)]; - } else { - payload.tasks = []; - } - } else if (payload.tasks[0]?.type === "webhook") { - if (!payload.tasks[0].urlPath) { - payload.tasks[0].urlPath = crypto.randomUUID(); - } - } - - return api.createWorkflow(client, payload); -} - -export function deleteWorkflow(...args: Parameters) { - return api.deleteWorkflow(...args); -} - -export function listWorkflowSnapshots(...args: Parameters) { - return api.listWorkflowSnapshots(...args); -} - -export function getWorkflowSnapshot(...args: Parameters) { - return api.getWorkflowSnapshot(...args); -} - -export function listWorkflowLogs(...args: Parameters) { - return api.listWorkflowLogs(...args); -} - -export function toggleWorkflow(...args: Parameters) { - return api.toggleWorkflow(...args); -} - -export function listRunningJobs(...args: Parameters) { - return api.listRunningJobs(...args); -} - -export function getJob(...args: Parameters) { - return api.getJob(...args); -} - -export function getJobExecutionTree(...args: Parameters) { - return api.getJobExecutionTree(...args); -} - -export function getJobFailedExecutions(...args: Parameters) { - return api.getJobFailedExecutions(...args); -} - -export function getJobExecutionLevel(...args: Parameters) { - return api.getJobExecutionLevel(...args); -} - -export function getExecutionLogs(...args: Parameters) { - return api.getExecutionLogs(...args); -} - -export function listDsl(...args: Parameters) { - return api.listDsl(...args); -} - -export function listStaffs(...args: Parameters) { - return api.listStaffs(...args); -} - -export function getWebhookInfo(...args: Parameters) { - return api.getWebhookInfo(...args); -} - -export function sampleWorkflowData(...args: Parameters) { - return api.sampleWorkflowData(...args); -} - -// ── 服务层:跨应用聚合 ─────────────────────────────────────────────────────── - -export interface ListAllWorkflowsOptions { - page?: number; - pageSize?: number; -} - -export interface ListAllWorkflowsResult { - workflows: WorkflowSummary[]; - errors: WorkflowListAllError[]; -} - -export async function listAllWorkflows( - clients: WorkflowClients, - options: ListAllWorkflowsOptions = {} -): Promise { - const { ekbClient, easoClient, corp } = clients; - const page = options.page ?? 1; - const pageSize = options.pageSize ?? 20; - - const platforms = await listBasicPlatforms(ekbClient, corp.credentials.corpId); - const enabledPlatforms = platforms.filter((p) => p.active !== false); - - const workflows: WorkflowSummary[] = []; - const errors: WorkflowListAllError[] = []; - - await Promise.all( - enabledPlatforms.map(async (platform) => { - try { - const pageResult = await api.listWorkflows( - easoClient, - platform.id, - page, - pageSize - ); - for (const workflow of pageResult.pipelineList) { - workflows.push({ - ...workflow, - platformId: platform.id, - platformName: platform.name, - }); - } - } catch (err) { - errors.push({ - platformId: platform.id, - platformName: platform.name, - error: err instanceof Error ? err.message : String(err), - }); - } - }) - ); - - return { workflows, errors }; -} - -function collectTasksByType( - tasks: WorkflowTask[], - taskType: string, - matches: TaskMatch[] = [] -): TaskMatch[] { - for (const task of tasks) { - if (task.type === taskType) { - matches.push({ - taskName: task.name, - taskType: task.type, - levelIndex: task.levelIndex, - }); - } - if ("tasks" in task && Array.isArray(task.tasks)) { - collectTasksByType(task.tasks as WorkflowTask[], taskType, matches); - } - } - return matches; -} - -export interface FindWorkflowsByTaskTypeOptions extends ListAllWorkflowsOptions { - includeDetail?: boolean; -} - -export interface FindWorkflowsByTaskTypeResult { - workflows: WorkflowWithMatches[]; - errors: WorkflowListAllError[]; -} - -export async function findWorkflowsByTaskType( - clients: WorkflowClients, - taskType: string, - options: FindWorkflowsByTaskTypeOptions = {} -): Promise { - const { easoClient } = clients; - const { includeDetail, ...listOptions } = options; - - const all = await listAllWorkflows(clients, listOptions); - const matched: WorkflowWithMatches[] = []; - const detailErrors: WorkflowListAllError[] = []; - - for (const workflow of all.workflows) { - let tasks = workflow.tasks; - - if (includeDetail) { - try { - const detail = await api.getWorkflowDetail(easoClient, workflow.id); - tasks = detail.tasks; - } catch (err) { - detailErrors.push({ - platformId: workflow.platformId, - platformName: workflow.platformName, - error: err instanceof Error ? err.message : String(err), - }); - continue; - } - } - - const matchedTasks = collectTasksByType(tasks, taskType); - if (matchedTasks.length > 0) { - matched.push({ ...workflow, matchedTasks }); - } - } - - return { workflows: matched, errors: [...all.errors, ...detailErrors] }; -} - -/** - * 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组) - */ -export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] { - const result: WorkflowTaskExecution[] = []; - - function visit(node: any) { - if (!node || typeof node !== "object") return; - result.push(node as WorkflowTaskExecution); - - const children = node.children || node.tasks || node.subTasks || node.items; - if (Array.isArray(children)) { - for (const child of children) { - visit(child); - } - } - } - - for (const node of nodes) { - visit(node); - } - - return result; -} - -/** - * 精准判定某个节点是否执行异常或报错 - */ -export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean { - if (!node) return false; - const anyNode = node as any; - - if (node.error?.message || anyNode.errorMessage) return true; - if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true; - if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true; - if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true; - if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true; - - return false; -} - -/** - * 提取并去重执行树中的全部异常失败节点 - */ -export function extractFailureExecutions( - tree: WorkflowTaskExecution[], - failedItems: WorkflowTaskExecution[] = [] -): WorkflowTaskExecution[] { - const flattened = flattenExecutionTree(tree); - const map = new Map(); - - for (const item of failedItems) { - if (item?.id) { - map.set(item.id, item); - } - } - - for (const node of flattened) { - if (node?.id && isTaskExecutionFailed(node)) { - const existing = map.get(node.id); - if (!existing) { - map.set(node.id, node); - } else { - map.set(node.id, { - ...node, - ...existing, - error: existing.error ?? node.error, - inputs: existing.inputs ?? (node as any).inputs, - outputs: existing.outputs ?? (node as any).outputs, - }); - } - } - } - - return Array.from(map.values()); -} - -/** - * 按 ID、name、displayName 或 label 查找节点 - */ -export function findExecutionNode( - tree: WorkflowTaskExecution[], - query: string -): WorkflowTaskExecution | undefined { - const flattened = flattenExecutionTree(tree); - const q = query.trim().toLowerCase(); - if (!q) return undefined; - - // 1. 精确匹配 ID 或 name - const exact = flattened.find( - (n) => - n.id?.toLowerCase() === q || - n.name?.toLowerCase() === q || - n.displayName?.toLowerCase() === q - ); - if (exact) return exact; - - // 2. 包含匹配 name、label、displayName - return flattened.find( - (n) => - n.name?.toLowerCase().includes(q) || - n.label?.toLowerCase().includes(q) || - n.displayName?.toLowerCase().includes(q) - ); -} - -// ── 工作流快照与 Job 差异比对核心算法 ────────────────────────────────────────── - -/** - * 递归展开工作流配置节点(包括 condition 与 every 内嵌的子节点) - */ -export function flattenWorkflowTasks(tasks?: WorkflowTask[] | null): WorkflowTask[] { - if (!tasks || !Array.isArray(tasks)) return []; - const result: WorkflowTask[] = []; - - function walk(list: WorkflowTask[]) { - for (const t of list) { - if (!t) continue; - result.push(t); - if (Array.isArray(t.tasks) && t.tasks.length > 0) { - walk(t.tasks); - } - } - } - - walk(tasks); - return result; -} - -/** - * 快速生成标准 Unified Diff 文本 - */ -export function generateTextDiff(a: string, b: string, labelA = "from", labelB = "to"): string { - if (a === b) return ""; - const linesA = a.split(/\r?\n/); - const linesB = b.split(/\r?\n/); - const output: string[] = [`--- ${labelA}`, `+++ ${labelB}`]; - - let start = 0; - while (start < linesA.length && start < linesB.length && linesA[start] === linesB[start]) { - start++; - } - let endA = linesA.length - 1; - let endB = linesB.length - 1; - while (endA >= start && endB >= start && linesA[endA] === linesB[endB]) { - endA--; - endB--; - } - - const hunkStart = Math.max(0, start - 2); - const hunkEndA = Math.min(linesA.length, endA + 3); - const hunkEndB = Math.min(linesB.length, endB + 3); - - output.push(`@@ -${hunkStart + 1},${hunkEndA - hunkStart} +${hunkStart + 1},${hunkEndB - hunkStart} @@`); - for (let i = hunkStart; i < start; i++) { - output.push(` ${linesA[i]}`); - } - for (let i = start; i <= endA; i++) { - output.push(`- ${linesA[i]}`); - } - for (let i = start; i <= endB; i++) { - output.push(`+ ${linesB[i]}`); - } - for (let i = endA + 1; i < hunkEndA; i++) { - output.push(` ${linesA[i]}`); - } - return output.join("\n"); -} - -/** - * 对比两个历史快照的节点、脚本代码(MVEL/JS)与参数配置差异 - */ -export function diffWorkflowSnapshots( - snapshotA: WorkflowSnapshot, - snapshotB: WorkflowSnapshot -): WorkflowSnapshotDiff { - const tasksA = flattenWorkflowTasks(snapshotA.tasks); - const tasksB = flattenWorkflowTasks(snapshotB.tasks); - const indexPaths = (tasks: WorkflowTask[] = [], prefix = "tasks", paths = new Map()): Map => { - tasks.forEach((task, i) => { - const path = `${prefix}.${i}`; - if (task.name) paths.set(task.name, path); - if (task.tasks) indexPaths(task.tasks, `${path}.tasks`, paths); - }); - return paths; - }; - const pathsA = indexPaths(snapshotA.tasks || []); - const pathsB = indexPaths(snapshotB.tasks || []); - - const mapA = new Map(); - for (const t of tasksA) { - if (t?.name) mapA.set(t.name, t); - } - - const mapB = new Map(); - for (const t of tasksB) { - if (t?.name) mapB.set(t.name, t); - } - - const addedTasks: string[] = []; - const removedTasks: string[] = []; - const modifiedTasks: TaskConfigDiff[] = []; - - // 1. 查找新增节点 - for (const [name, tB] of mapB) { - if (!mapA.has(name)) { - addedTasks.push(name); - modifiedTasks.push({ - taskName: name, - displayName: tB.displayName || tB.label, - type: tB.type, - changeType: "ADDED", - configChanges: [], - }); - } - } - - // 2. 查找删除与修改节点 - for (const [name, tA] of mapA) { - const tB = mapB.get(name); - if (!tB) { - removedTasks.push(name); - modifiedTasks.push({ - taskName: name, - displayName: tA.displayName || tA.label, - type: tA.type, - changeType: "REMOVED", - configChanges: [], - }); - continue; - } - - // 两者均存在,深度比较配置与代码 - const configChanges: Array<{ field: string; from?: unknown; to?: unknown }> = []; - let codeDiff: { from?: string; to?: string; unifiedDiff?: string } | undefined; - let filterDiff: { from?: unknown; to?: unknown } | undefined; - - // 代码脚本比较 - const codeA = typeof (tA as any).code === "string" ? (tA as any).code : undefined; - const codeB = typeof (tB as any).code === "string" ? (tB as any).code : undefined; - if (codeA !== codeB) { - codeDiff = { - from: codeA, - to: codeB, - unifiedDiff: generateTextDiff( - codeA || "", - codeB || "", - `${snapshotA.version || snapshotA.id}`, - `${snapshotB.version || snapshotB.id}` - ), - }; - } - - // 过滤条件比较 (combineFilters / filters) - const filtersA = (tA as any).combineFilters ?? (tA as any).filters; - const filtersB = (tB as any).combineFilters ?? (tB as any).filters; - if (JSON.stringify(filtersA) !== JSON.stringify(filtersB)) { - filterDiff = { from: filtersA, to: filtersB }; - } - - // 关键字段变动比较 - const checkFields = [...new Set([...Object.keys(tA), ...Object.keys(tB)])] - .filter(field => !["name", "tasks", "code", "combineFilters", "filters"].includes(field)); - if (pathsA.get(name) !== pathsB.get(name)) { - configChanges.push({ field: "$path", from: pathsA.get(name), to: pathsB.get(name) }); - } - for (const f of checkFields) { - const valA = (tA as any)[f]; - const valB = (tB as any)[f]; - if (JSON.stringify(valA) !== JSON.stringify(valB)) { - configChanges.push({ field: f, from: valA, to: valB }); - } - } - - if (codeDiff || filterDiff || configChanges.length > 0) { - modifiedTasks.push({ - taskName: name, - displayName: tB.displayName || tB.label || tA.displayName || tA.label, - type: tB.type || tA.type, - changeType: "MODIFIED", - codeDiff, - filterDiff, - configChanges, - }); - } - } - - return { - snapshotA: { - id: snapshotA.id, - version: snapshotA.version, - updateTime: snapshotA.updateTime, - staffName: snapshotA.staffName || snapshotA.staffId || undefined, - }, - snapshotB: { - id: snapshotB.id, - version: snapshotB.version, - updateTime: snapshotB.updateTime, - staffName: snapshotB.staffName || snapshotB.staffId || undefined, - }, - addedTasks, - removedTasks, - modifiedTasks, - summary: { - totalA: tasksA.length, - totalB: tasksB.length, - changedCount: modifiedTasks.length, - }, - }; -} - -/** - * 对比两个 Job 的执行分支、入参 Payload、下游输出及报错信息 - */ -export function diffWorkflowJobs( - jobA: WorkflowJobDetail, - treeA: WorkflowTaskExecution[], - jobB: WorkflowJobDetail, - treeB: WorkflowTaskExecution[] -): WorkflowJobDiff { - const flatA = indexExecutionContexts(treeA); - const flatB = indexExecutionContexts(treeB); - const byKeyA = new Map(flatA.map(context => [context.key, context])); - const byKeyB = new Map(flatB.map(context => [context.key, context])); - const allKeys = new Set([...byKeyA.keys(), ...byKeyB.keys()]); - - const nodes: NodeExecutionDiff[] = []; - let divergedNodesCount = 0; - let statusDiffCount = 0; - - for (const key of allKeys) { - const contextA = byKeyA.get(key); - const contextB = byKeyB.get(key); - const nodeA = contextA?.node; - const nodeB = contextB?.node; - const name = nodeB?.name || nodeA?.name || nodeB?.type || nodeA?.type || "unnamed"; - - const statusA = nodeA?.status; - const statusB = nodeB?.status; - const isStatusDiff = statusA !== statusB; - if (isStatusDiff) statusDiffCount++; - - // 比较 inputs - const inputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; - const payloadFields = (value: unknown): Record => value === undefined ? {} : value !== null && typeof value === "object" ? value as Record : { $value: value }; - const inA = payloadFields(nodeA?.inputs); - const inB = payloadFields(nodeB?.inputs); - const inputKeys = Array.from(new Set([...Object.keys(inA), ...Object.keys(inB)])); - for (const k of inputKeys) { - if (JSON.stringify(inA[k]) !== JSON.stringify(inB[k])) { - inputsDiff.push({ field: k, from: inA[k], to: inB[k] }); - } - } - - // 比较 outputs - const outputsDiff: Array<{ field: string; from?: unknown; to?: unknown }> = []; - const outA = payloadFields(nodeA?.outputs ?? nodeA?.output); - const outB = payloadFields(nodeB?.outputs ?? nodeB?.output); - const outputKeys = Array.from(new Set([...Object.keys(outA), ...Object.keys(outB)])); - for (const k of outputKeys) { - if (JSON.stringify(outA[k]) !== JSON.stringify(outB[k])) { - outputsDiff.push({ field: k, from: outA[k], to: outB[k] }); - } - } - - const isDiverged = - !nodeA || - !nodeB || - isStatusDiff || - JSON.stringify(nodeA.error) !== JSON.stringify(nodeB.error) || - inputsDiff.length > 0 || outputsDiff.length > 0; - - if (isDiverged) divergedNodesCount++; - - nodes.push({ - taskName: name, - instanceKey: key, - currentLoopPath: contextB?.loopPath || contextA?.loopPath || undefined, - displayName: (nodeB?.displayName || nodeA?.displayName || nodeB?.label || nodeA?.label) ?? undefined, - type: nodeB?.type || nodeA?.type, - statusA, - statusB, - durationMsA: nodeA?.executionTime, - durationMsB: nodeB?.executionTime, - errorA: nodeA?.error, - errorB: nodeB?.error, - inputsDiff, - outputsDiff, - diverged: isDiverged, - }); - } - - return { - jobA: { - id: jobA.id, - pipelineId: jobA.pipelineId, - state: typeof jobA.state === "string" || typeof jobA.state === "number" ? jobA.state : undefined, - startTime: jobA.startTime ? String(jobA.startTime) : undefined, - durationTime: typeof jobA.durationTime === "number" ? jobA.durationTime : undefined, - hasError: Boolean(jobA.hasError), - errorCount: typeof (jobA as any).errorTaskCount === "number" ? (jobA as any).errorTaskCount : undefined, - }, - jobB: { - id: jobB.id, - pipelineId: jobB.pipelineId, - state: typeof jobB.state === "string" || typeof jobB.state === "number" ? jobB.state : undefined, - startTime: jobB.startTime ? String(jobB.startTime) : undefined, - durationTime: typeof jobB.durationTime === "number" ? jobB.durationTime : undefined, - hasError: Boolean(jobB.hasError), - errorCount: typeof (jobB as any).errorTaskCount === "number" ? (jobB as any).errorTaskCount : undefined, - }, - nodes, - summary: { - totalNodesA: flatA.length, - totalNodesB: flatB.length, - divergedNodesCount, - statusDiffCount, - }, - }; -} - -export function getWorkflowDebugSource(...args: Parameters) { - return api.getWorkflowDebugSource(...args); -} - -export function triggerWorkflowDebug(...args: Parameters) { - return api.triggerWorkflowDebug(...args); -} - -export async function runWorkflowDebugTest( - client: import("ky").KyInstance, - pipelineId: string, - options: { - flowCodeOrId?: string; - data?: Record; - triggerCategory?: import("./types.js").WorkflowTriggerCategory; - triggerType?: string; - triggerLabel?: string; - autoPublish?: boolean; - timeoutMs?: number; - pollIntervalMs?: number; - } = {} -): Promise { - if (!Number.isFinite(options.timeoutMs ?? 15000) || (options.timeoutMs ?? 15000) < 0 || !Number.isFinite(options.pollIntervalMs ?? 500) || (options.pollIntervalMs ?? 500) <= 0) { - throw new ValidationError("timeoutMs 必须为非负数,pollIntervalMs 必须为正数"); - } - let targetEntityId = options.flowCodeOrId ?? ""; - const code = options.flowCodeOrId; - const isDirectCode = !code || code.includes("-") || code.startsWith("ID01"); - if (code && !isDirectCode) { - try { - const source = await api.getWorkflowDebugSource(client, pipelineId, { - page: 1, - pageSize: 10, - keywords: code, - }); - const matched = source.items.find( - (item) => item.id === code || (item as any).code === code || item.title?.includes(code) || (item as any).name?.includes(code) - ); - if (matched) { - targetEntityId = matched.id; - } - } catch { - // 关键字搜索超时或失败时直接回退使用传入值 - } - } - - const jobId = await api.triggerWorkflowDebug(client, pipelineId, { - entityId: targetEntityId || undefined, - data: options.data, - autoPublish: options.autoPublish ?? false, - }); - - const timeoutMs = options.timeoutMs ?? 15000; - const pollIntervalMs = options.pollIntervalMs ?? 500; - const start = Date.now(); - const diagnosticsErrors: Array<{ source: string; message: string }> = []; - const recordError = (source: string, error: unknown) => diagnosticsErrors.push({ source, message: error instanceof Error ? error.message : String(error) }); - const terminal = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]); - const jobState = (job?: WorkflowJobDetail) => String(job?.status || job?.state || "UNKNOWN").toUpperCase(); - let finalJob: WorkflowJobDetail | undefined; - let pollingFailed = false; - - while (Date.now() - start < timeoutMs) { - try { - const job = await api.getJob(client, jobId); - finalJob = job; - if (terminal.has(jobState(job))) break; - } catch (error) { - // 任务刚创建可能存在短延时,继续轮询 - const status = (error as { status?: number; response?: { status?: number } } | null)?.status - ?? (error as { response?: { status?: number } } | null)?.response?.status; - if (status !== 404) { - recordError("job", error); - pollingFailed = true; - break; - } - } - await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(0, timeoutMs - (Date.now() - start))))); - } - - if (!finalJob && !pollingFailed) { - try { finalJob = await api.getJob(client, jobId); } - catch (error) { recordError("job", error); pollingFailed = true; } - } - const timedOut = !pollingFailed && !terminal.has(jobState(finalJob)); - const [treeResult, failuresResult] = await Promise.allSettled([ - api.getJobExecutionTree(client, jobId), - api.getJobFailedExecutions(client, jobId), - ]); - const tree = treeResult.status === "fulfilled" ? treeResult.value : []; - const failedItems = failuresResult.status === "fulfilled" ? failuresResult.value.items : []; - if (treeResult.status === "rejected") recordError("executionTree", treeResult.reason); - if (failuresResult.status === "rejected") recordError("failedExecutions", failuresResult.reason); - - const rawFailed = extractFailureExecutions(tree, failedItems); - const diagnosticsComplete = diagnosticsErrors.length === 0; - const status = jobState(finalJob); - const hasExecutionError = rawFailed.length > 0 || finalJob?.hasError === true || Number(finalJob?.errorTaskCount ?? 0) > 0; - let outcome: import("./types.js").WorkflowTestReport["outcome"] = "incomplete"; - if (timedOut) outcome = "timed_out"; - else if (terminal.has(status) && (status !== "COMPLETED" || hasExecutionError)) outcome = "failed"; - else if (status === "COMPLETED" && diagnosticsComplete) outcome = "completed"; - const conditionDiagnoses = explainConditionBranches(tree); - - return { - jobId, - pipelineId, - status, - outcome, - timedOut, - diagnosticsComplete, - diagnosticsErrors, - runType: finalJob?.runType || "DEBUG", - durationTime: typeof finalJob?.durationTime === "number" ? finalJob.durationTime : undefined, - targetEntityId, - triggerCategory: options.triggerCategory, - triggerType: options.triggerType, - triggerLabel: options.triggerLabel, - executionTree: tree, - failedExecutions: rawFailed, - conditionDiagnoses, - }; -} +// workflow 业务服务出口;具体实现按职责拆分,内部模块避免反向导入此门面。 +export { + listWorkflows, + getWorkflowStats, + getWorkflowCharge, + getWorkflowDetail, + listWorkflowSnapshots, + getWorkflowSnapshot, + listWorkflowLogs, + listRunningJobs, + getJob, + getJobExecutionTree, + getJobFailedExecutions, + getJobExecutionLevel, + getExecutionLogs, + listAllWorkflows, + findWorkflowsByTaskType, +} from "./queries.js"; +export type { + WorkflowClients, + ListAllWorkflowsOptions, + ListAllWorkflowsResult, + FindWorkflowsByTaskTypeOptions, + FindWorkflowsByTaskTypeResult, +} from "./queries.js"; +export { + sanitizeWorkflowSnapshot, + updateWorkflow, + refreshWorkflowChooses, + copyWorkflow, + buildInitialTriggerTask, + createWorkflow, + deleteWorkflow, + toggleWorkflow, +} from "./configuration.js"; +export type { + CreateWorkflowOptions, +} from "./configuration.js"; +export { + listDsl, + listStaffs, + getWorkflowEnumOptions, + resolveWorkflowEnumOptions, + getWorkflowAvailableNodes, + grantWorkflowNodes, +} from "./catalog.js"; +export { + getWebhookInfo, + sampleWorkflowData, + getWorkflowDebugSource, + triggerWorkflowDebug, + runWorkflowDebugTest, + getWorkflowSampleData, +} from "./debug.js"; +export { + flattenExecutionTree, + isTaskExecutionFailed, + extractFailureExecutions, + findExecutionNode, + flattenWorkflowTasks, +} from "./execution.js"; +export { + generateTextDiff, + diffWorkflowSnapshots, + diffWorkflowJobs, +} from "./diff.js"; export { explainConditionBranches, @@ -972,119 +78,4 @@ export { type WorkflowSampleDataResult, } from "./types.js"; -export async function getWorkflowSampleData( - client: import("ky").KyInstance, - pipelineId: string, - type = "webhook" -): Promise { - return api.getWorkflowSampleData(client, pipelineId, type); -} - -export function getWorkflowEnumOptions(...args: Parameters) { - return api.getWorkflowEnumOptions(...args); -} - -export async function resolveWorkflowEnumOptions( - client?: import("ky").KyInstance, - thirdId = "action", - platformId?: string -): Promise> { - if (client) { - try { - const remote = await api.getWorkflowEnumOptions(client, thirdId, platformId); - if (remote && remote.length > 0) { - return remote.map((item) => ({ - code: item.code, - label: item.label, - name: item.name || item.label, - })); - } - } catch { - // 远程调用失败(如无权限/网络异常)时 Fallback 到内置字典 - } - } - - if (thirdId.toLowerCase() === "action") { - const { SYSTEM_WORKFLOW_ACTION_ENUMS } = await import("./enums.js"); - return SYSTEM_WORKFLOW_ACTION_ENUMS.map((item) => ({ - code: item.code, - label: item.label, - name: item.name, - description: item.description, - })); - } - - return []; -} - -// ── 工作流企业可用节点探针与灰度开通 ────────────────────────────────────────── - -export async function getWorkflowAvailableNodes( - client: KyInstance -): Promise { - const catalog = await api.listDslCatalog(client); - const allTypes = new Set(); - - for (const item of catalog.action) { - if (item.type) allTypes.add(item.type); - } - for (const item of catalog.control) { - if (item.type) allTypes.add(item.type); - } - for (const item of catalog.trigger) { - if (item.type) allTypes.add(item.type); - } - - return { - allTypes, - actionNodes: catalog.action, - controlNodes: catalog.control, - triggerNodes: catalog.trigger, - }; -} - -export async function grantWorkflowNodes( - corp: CorpConfig, - options: import("./types.js").GrantWorkflowNodesOptions -): Promise { - if (!options.nodes || options.nodes.length === 0) { - throw new ValidationError("必须指定至少一个需要开通的节点名称或类型"); - } - - // 1. 管理员密码保护预留设计 - const adminPassword = process.env.HOSE_ADMIN_PASSWORD; - if (adminPassword) { - if (!options.password || options.password !== adminPassword) { - throw new PermissionError( - "灰度节点开通功能已启用管理员保护,请通过 --password 或配置输入正确的管理员密码" - ); - } - } - - // 2. 节点清洗与归一化(将可能传入的中文名映射为标准的 node type) - const { findGrayNode } = await import("./nodes/gray-nodes-catalog.js"); - const normalizedNodes = options.nodes.map((node) => { - const matched = findGrayNode(node); - return matched ? matched.type : node.trim(); - }); - - const token = corp.credentials?.accessToken; - const corpId = corp.corpId || corp.credentials?.corpId || corp.id; - const baseUrl = corp.baseUrl; - - if (!token) { - throw new ValidationError("当前企业缺少 accessToken,无法发起节点开通申请"); - } - - // 3. 调用开通 API - const result = await api.grantWorkflowNodesApi({ - token, - corpId, - nodes: normalizedNodes, - baseUrl, - }); - - return result; -} - export * from "./index.js"; diff --git a/src/domains/platform/workflow/types.ts b/src/domains/platform/workflow/types.ts index f6e8961..78ce4fd 100644 --- a/src/domains/platform/workflow/types.ts +++ b/src/domains/platform/workflow/types.ts @@ -705,7 +705,7 @@ export interface WorkflowTestReport { triggerLabel?: string; executionTree: WorkflowTaskExecution[]; failedExecutions: WorkflowTaskExecution[]; - conditionDiagnoses: import("./branch/index.js").ConditionBranchExplanation[]; + conditionDiagnoses: import("./branch/types.js").ConditionBranchExplanation[]; } // ── 触发器元类型分类与智能路径路由 ─────────────────────────────────────────────── diff --git a/src/domains/platform/workflow/watch/README.watch.md b/src/domains/platform/workflow/watch/README.watch.md index 18b3bf0..0ef22d4 100644 --- a/src/domains/platform/workflow/watch/README.watch.md +++ b/src/domains/platform/workflow/watch/README.watch.md @@ -8,7 +8,7 @@ |---|---| | [pipeline-watcher.ts](./pipeline-watcher.ts) | `watchWorkflowPipeline`,发现和跟踪工作流执行,管理监听范围 | | [single-job.ts](./single-job.ts) | `watchSingleJob`,读取单个 Job 与节点执行变化 | -| [tracker.ts](./tracker.ts) | 节点执行变化跟踪和事件去重 | +| [tracker.ts](./tracker.ts) | 节点执行变化跟踪和事件去重,直接使用上级 execution 模块 | | [helpers.ts](./helpers.ts) | 状态归一化、终态判断和错误提取 | | [formatter.ts](./formatter.ts) | 将事件格式化为文本 | | [types.ts](./types.ts)、[index.ts](./index.ts) | 事件、监听选项、结果类型及统一导出 | diff --git a/src/domains/platform/workflow/watch/tracker.ts b/src/domains/platform/workflow/watch/tracker.ts index faa5422..aa54e87 100644 --- a/src/domains/platform/workflow/watch/tracker.ts +++ b/src/domains/platform/workflow/watch/tracker.ts @@ -1,5 +1,5 @@ import type { WorkflowTaskExecution } from "../types.js"; -import { flattenExecutionTree, isTaskExecutionFailed } from "../services.js"; +import { flattenExecutionTree, isTaskExecutionFailed } from "../execution.js"; import type { WorkflowWatchEvent } from "./types.js"; import { extractTaskErrorMessage } from "./helpers.js";