From 4dc3c24999eac45ea46a56ebbb08e01fe9fa6eb7 Mon Sep 17 00:00:00 2001 From: rulego-team Date: Sat, 5 Sep 2026 14:54:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 2 +- README.md | 249 ++++++++++++++++++----------------- README_EN.md | 296 ++++++++++++++++++++++++++++++++++++++++++ README_ZH.md | 279 --------------------------------------- docs/README.md | 2 +- docs/dsl-reference.md | 2 +- 6 files changed, 426 insertions(+), 404 deletions(-) create mode 100644 README_EN.md delete mode 100644 README_ZH.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 115312b..32f113e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,7 @@ GFlow Engine 是**以 Go 库形式被宿主应用嵌入**的审批工作流引 ## 交流语言 -Issue、PR、commit、代码注释、docs/ 目录文档均使用中文;代码标识符、错误消息使用英文。README.md(英文)与 README_ZH.md(中文)成对维护,改动需同步。 +Issue、PR、commit、代码注释、docs/ 目录文档均使用中文;代码标识符、错误消息使用英文。README.md(中文)与 README_EN.md(英文)成对维护,改动需同步。 ## 开发环境 diff --git a/README.md b/README.md index 6605608..c8760c2 100644 --- a/README.md +++ b/README.md @@ -3,68 +3,80 @@ [![GoDoc](https://pkg.go.dev/badge/github.com/rulego/gflow-engine)](https://pkg.go.dev/github.com/rulego/gflow-engine) [![Go Report](https://goreportcard.com/badge/github.com/rulego/gflow-engine)](https://goreportcard.com/report/github.com/rulego/gflow-engine) -English | [简体中文](README_ZH.md) +[English](README_EN.md) | 简体中文 -> **GFlow** — approval at the speed of wind +> **GFlow** —— AI 先审 · 人再签 · 签完自动办 > -> **GFlow Engine** — the embeddable approval workflow engine at the core of the GFlow product family (open-source edition). -> It ships as a Go library: no UI, no HTTP server — you drive it from your own application. +> **GFlow Engine**——GFlow 产品家族的核心,可嵌入的审批工作流引擎(开源版)。 +> 以 Go 库形式发布,不含界面、不提供 HTTP 服务,由宿主应用集成驱动。 > -> Need something ready to run? **GFlow Platform(极风工作流)** is the GFlow Enterprise Edition, -> with a flow designer, form designer, approval UI and AI review built in. -> Site: · Live demo: (`admin` / `admin123`) +> 需要开箱即用?**GFlow Platform(极风工作流)** 即 GFlow 企业版, +> 提供流程设计器、表单设计器、审批界面与 AI 审批。 +> 官网 · 在线演示 (`admin` / `admin123`) -`GFlow Engine` is a lightweight, embeddable approval workflow engine built on [RuleGo](https://github.com/rulego/rulego). Process definitions reuse the `RuleGo` rule-chain DSL (JSON), while tasks, process instances and history are persisted to a relational database by the engine itself — no separate process middleware to deploy. +`GFlow Engine` 是一个基于 [RuleGo](https://github.com/rulego/rulego) 的轻量级、可嵌入审批工作流引擎。流程定义复用 `RuleGo` 规则链 DSL(JSON),审批任务、流程实例、历史归档等状态由引擎持久化到关系数据库,无需部署独立的流程中间件。审批节点与自动化节点(规则链、HTTP、AI 智能体、子流程)在同一条流程 DSL 里混排——审批通过即可自动执行后续动作;或签、会签、动态加签/减签、退回等中国式审批语义开箱即用。 -> Note: the DSL is a BPMN-style approval flow in JSON form; it does not parse BPMN 2.0 XML. +> 注意:DSL 为 JSON 格式的类 BPMN 审批流,不解析 BPMN 2.0 XML。 -## Features +## 特性 -* **Rule chain as process:** the DSL is a `RuleGo` rule chain. Native nodes such as gateways (`switch`) and parallel branches (`fork`/`inclusive`/`join`) can be mixed into approval flows directly. -* **Full approval semantics:** single sign-off, countersign (parallel/sequential, all/majority), dynamic add/remove signers, transfer, delegation, claim, return, withdraw, suspend/resume, overdue handling. -* **Candidate-group tasks:** tasks can be offered to users, roles or departments; the candidate pool (`wf_task_assignee`) is stored separately and expanded through `IdentityService` at query time. -* **Sub-processes:** the `subProcess` node starts an independent child instance and returns to the parent flow on completion. -* **Rule-engine integration:** `serviceTask` calls Go functions, `automation` invokes `RuleGo` rule chains, `aiAgent` talks to agent rule chains ([rulego-components-ai](https://github.com/rulego/rulego-components-ai)), and `httpCall` performs synchronous HTTP calls. -* **Runtime/history split:** in-flight data and archived data live in separate tables, so reporting and audits never contend with the hot path. -* **Multi-tenancy:** `tenant_id` isolation end to end, with per-tenant rule-engine pools. -* **Pluggable identity:** implement `IdentityService` to resolve approvers from your real user/role/department data (by role, department, group or manager hierarchy). The built-in mock is for tests only. -* **Pluggable SQL dialects:** PostgreSQL / MySQL out of the box; register others (SQLite, Dameng, Kingbase, ...) via `DialectProvider` — see the examples directory. -* **Versioned definitions:** each `process_key` keeps multiple published versions; running instances continue on the version they started with. -* **Approval comments:** task comments live in `wf_task_comment` and survive task archival; approval actions record their comment in the same transaction. -* **Event hooks:** 17 task lifecycle events (started/assigned/candidateCreated/claimed/unclaimed/approved/rejected/forwarded/addSign/reduceSign/resolved/returned/withdrawn/suspended/activated/completed/terminated) dispatched after commit; register one or many listeners via the builder. Platform hooks: cross-tenant overdue scan (`ScanOverdueTasks`) and batch claimable-instance lookup (`GetClaimableInstanceIDs`). -* **Lightweight:** no mandatory external middleware (a local in-memory lock is built in; distributed locking is pluggable). Fits embedding into existing applications. +* **流程即规则链,审批与自动化同链** + * **规则链即流程:** 流程 DSL 复用 `RuleGo` 规则链,网关(`switch` 条件分支)、并行分支(`fork`/`inclusive`/`join`)等原生节点可直接编排,流程即规则、规则即流程。 + * **审批与自动化同链编排:** `serviceTask` 调用 Go 函数,`automation` 节点调用 `RuleGo` 规则链,`aiAgent` 节点对接智能体规则链([rulego-components-ai](https://github.com/rulego/rulego-components-ai)),`httpCall` 节点同步调用外部接口。 + * **子流程:** `subProcess` 节点启动独立子流程实例,嵌套审批闭环。 +* **中国式审批语义与流程模型** + * **中国式审批语义:** 或签(or)、会签(并行/顺序,全票/多数)、动态加签/减签、转办、委托、签收/抢单、退回、撤回、挂起/恢复、超时催办,开箱即用无需二次开发。 + * **候选组待办:** 任务可按人员/角色/部门发起,候选人池(`wf_task_assignee`)独立存储,查询时经 `IdentityService` 展开。 + * **审批意见:** 评论存于 `wf_task_comment`,任务归档后仍可读写;审批动作与意见在同一事务落库。 + * **流程定义版本化:** 同一 `process_key` 按 `version` 递增保留多个发布版本,存量实例继续运行旧版本。 +* **集成与扩展** + * **可插拔身份体系:** 实现 `IdentityService` 对接真实的用户/角色/部门数据(按角色、部门、组、多级主管解析审批人);内置 Mock 实现仅用于测试。 + * **事件钩子:** 17 个任务全生命周期事件在事务提交后派发,完整目录见 [docs/events.md](docs/events.md);构建器支持注册一个或多个监听器。平台级钩子:跨租户逾期扫描(`ScanOverdueTasks`)、批量可认领实例判断(`GetClaimableInstanceIDs`)。 + * **可插拔数据库方言:** 内置 PostgreSQL / MySQL,通过 `DialectProvider` 可扩展其它数据库(SQLite、达梦、人大金仓等,见 examples 目录)。 +* **架构与部署** + * **运行时/历史双表:** 进行中数据与归档数据分离,报表和审计查询不拖累运行时。 + * **多租户:** 全链路 `tenant_id` 隔离,规则链执行池按租户划分。 + * **轻量部署:** 无必须的外部中间件(内置本地内存锁,分布式锁可插拔),适合嵌入现有应用。 -## Installation +## 安装 ```bash go get github.com/rulego/gflow-engine ``` -Requires Go 1.24+ and RuleGo v0.37+. Initialize the workflow tables with `scripts/00.init_bpm_pg.sql` (PostgreSQL) or `scripts/00.init_bpm_mysql.sql` (MySQL); initialization and upgrade guidance lives in [docs/migration.md](docs/migration.md). +要求 Go 1.24+、RuleGo v0.37+。数据库表初始化脚本为 `scripts/00.init_bpm_pg.sql`(PostgreSQL)与 `scripts/00.init_bpm_mysql.sql`(MySQL),初始化与升级说明见 [docs/migration.md](docs/migration.md)。 -## Database setup +## 初始化数据库 -The engine manages only its own workflow tables; users, roles and departments belong to the host application. +引擎只维护自己的工作流表,用户/角色/部门等系统表由宿主应用负责。 -**PostgreSQL:** +**PostgreSQL:** ```bash -createdb gflow # create the database first (or: psql -c "CREATE DATABASE gflow") +createdb gflow # 首次使用先建库(或 psql -c "CREATE DATABASE gflow") psql -d gflow -f scripts/00.init_bpm_pg.sql ``` -**MySQL:** +**MySQL:** ```bash mysql -u root -p -e "CREATE DATABASE gflow DEFAULT CHARACTER SET utf8mb4" mysql -u root -p gflow < scripts/00.init_bpm_mysql.sql ``` -Tables created: `wf_process` (definitions), `wf_instance` / `wf_hi_instance` (runtime/history instances), `wf_task` / `wf_hi_task` (runtime/history tasks), `wf_task_assignee` (candidate pool), `wf_task_comment` (approval comments). +建表清单:`wf_process`(流程定义)、`wf_instance` / `wf_hi_instance`(实例运行时/历史)、`wf_task` / `wf_hi_task`(任务运行时/历史)、`wf_task_assignee`(候选人池)、`wf_task_comment`(审批意见)。 -> The init scripts are idempotent (`CREATE TABLE IF NOT EXISTS`) — re-running them on an existing database never deletes or modifies data. Unit tests run on an in-memory SQLite database and need no scripts. The optional real-database lock test (`TestWithInstanceTx_RealDB_ForUpdateSerializes`) runs only when `TEST_PG_DSN` or `TEST_MYSQL_DSN` points to an existing database; it creates and drops its own `gflow_locktest` scratch database. +> 初始化脚本为幂等设计(`CREATE TABLE IF NOT EXISTS`),在已有库上重跑不会删除/改写任何数据。单元测试使用 SQLite 内存库,无需执行脚本;可选的真实库行锁测试(`TestWithInstanceTx_RealDB_ForUpdateSerializes`)仅在设置 `TEST_PG_DSN` 或 `TEST_MYSQL_DSN`(指向任意现存库)时运行,会自建并清理 `gflow_locktest` 临时库。 -## Quick start +## 快速开始 + +建议先跑通完整示例再动手集成(部署 → 发起 → 审批 → 查询实例状态一条龙,内存 SQLite 零依赖): + +```bash +go run ./examples/leave_approval +``` + +最小集成代码: ```go package main @@ -82,7 +94,7 @@ import ( func main() { ctx := context.Background() - // 1. Configure the database and start the engine + // 1. 数据库配置并启动引擎 cfg := &config.Config{ Database: &config.DatabaseConfig{ Driver: "postgres", @@ -98,52 +110,47 @@ func main() { log.Fatalf("build engine: %v", err) } if err := engine.Start(ctx); err != nil { - log.Fatalf("start engine: %v", err) + log.Fatalf("启动引擎失败: %v", err) } defer engine.Stop(ctx) - // 2. Register workflow node components (userTask/serviceTask/automation/...) - // Dependencies are pulled from the engine itself; host service functions - // are registered via WithServiceFuncs (metadata feeds the designer catalog, - // implementations feed the runtime — see docs/components.md). - // Note: engine.Start must have succeeded first, otherwise registration - // fails fast with an error. + // 2. 注册工作流节点组件(userTask/serviceTask/automation/...) + // 依赖由引擎自取;宿主自己的服务函数经 WithServiceFuncs 注册,见 docs/components.md。 + // 注意:必须先 engine.Start 成功,否则注册会报错拦截。 if err := components.RegisterFromEngine(engine); err != nil { - log.Fatalf("register components: %v", err) + log.Fatalf("注册组件失败: %v", err) } - // 3. Deploy a process definition (the DSL is a rulego rule chain JSON, - // see examples/leave_approval). All mutating operations take an explicit - // actor — the operator identity used for auditing and permission checks. + // 3. 部署流程定义(DSL 为 rulego 规则链 JSON,见 examples/leave_approval)。 + // 所有变更类操作的第一个业务参数都是显式 actor——用于审计与权限校验的操作人。 admin := service.Actor{UserID: "admin", UserName: "admin", TenantID: "default"} _, err = engine.GetProcessService().Deploy(ctx, admin, &model.WfProcess{ ProcessKey: "leave_approval", - Name: "Leave Approval", - DefinitionJSON: leaveApprovalDSL, // process DSL JSON + Name: "请假审批", + DefinitionJSON: leaveApprovalDSL, // 流程 DSL JSON,内容参考 examples/leave_approval/dsl.json TenantID: "default", CreatedBy: "admin", }, true) if err != nil { - log.Fatalf("deploy process: %v", err) + log.Fatalf("部署流程失败: %v", err) } - // 4. Start a process instance (pass service.WithDraft() as a variadic - // option to start in draft mode; omit it for a normal start) + // 4. 发起流程实例(追加可变参数 service.WithDraft() 即草稿模式;普通启动不传) instanceID, err := engine.GetRuntimeService().StartProcessInstanceByKey( ctx, - service.Actor{UserID: "emp001", UserName: "Zhang San", TenantID: "default"}, + service.Actor{UserID: "emp001", UserName: "张三", TenantID: "default"}, "leave_approval", - "leave_emp001_1", // business key - map[string]interface{}{"days": 5, "managerId": "mgr001", "reason": "family affairs"}, + "leave_emp001_1", // 业务键 + map[string]interface{}{"days": 5, "managerId": "mgr001", "reason": "家中事务"}, ) if err != nil { - log.Fatalf("start instance: %v", err) + log.Fatalf("发起流程失败: %v", err) } - _ = instanceID + log.Printf("实例已发起: %s", instanceID) } ``` -Handling a pending task (also import `github.com/rulego/gflow-engine/types/dto` and `.../types/enums`): +审批人处理待办(需额外引入 `github.com/rulego/gflow-engine/types/dto` 与 `.../types/enums`): ```go tasks, _, err := engine.GetTaskService().GetTaskList(ctx, service.Actor{ @@ -166,32 +173,31 @@ err = engine.GetTaskService().CompleteWithApproval(ctx, service.Actor{ }, &service.ApprovalRequest{ TaskID: tasks[0].ID, ApprovalResult: enums.ApprovalResultApproved, - Comment: "approved", + Comment: "同意", }) ``` -> **Security note — the operator is the explicit `actor Actor` parameter:** all approval -> and mutation operations (`CompleteWithApproval`, `Approve`, `Reject`, `Claim`, `Unclaim`, -> `Transfer`, `Reassign`, `Return`, `Withdraw`, `WithdrawByInstance`, `DeleteTask`, ...) -> receive the operator as an explicit `actor service.Actor` parameter; the engine checks -> assignee permission against `actor.UserID`. A call with no operator identity is rejected -> with `ErrAuthenticationRequired`, and an operator who is not the task assignee gets -> `ErrPermissionDenied`. Construct the `Actor` on the server side from your authentication -> layer (session/token) — never trust client input directly. +> **安全说明——操作人由显式 `actor Actor` 参数传入:** +> 所有审批/变更类操作(`CompleteWithApproval`/`Approve`/`Reject`/`Claim`/`Unclaim`/ +> `Transfer`/`Reassign`/`Return`/`Withdraw`/`WithdrawByInstance`/`DeleteTask` 等)的 +> 操作人都是显式 `actor service.Actor` 参数,引擎以 `actor.UserID` 校验 assignee 权限。 +> 没有任何操作人身份的调用会以 `ErrAuthenticationRequired` 拒绝;操作人不是任务 +> 办理人则以 `ErrPermissionDenied` 拒绝。`Actor` 必须由宿主服务端从认证层 +> (session/token)构造,绝不直接透传客户端输入。 -A complete runnable example (single sign-off, parallel and sequential countersign) lives in [examples/leave_approval](examples/leave_approval) — it runs zero-dependency on an in-memory SQLite database by default (`GFLOW_DSN` switches to PostgreSQL/MySQL). An `httpCall` + `switch` combination example (query an external API, map the response into process variables, route by the result) lives in [examples/http_call](examples/http_call). +完整可运行示例(单签、并行会签、顺序会签)见 [examples/leave_approval](examples/leave_approval)——默认跑在内存 SQLite 上,零依赖直接运行(`GFLOW_DSN` 可切 PostgreSQL/MySQL);`httpCall` + `switch` 组合示例(查询外部接口 → 响应映射进流程变量 → 按结果路由)见 [examples/http_call](examples/http_call)。引擎默认内置内存 Mock 身份服务(仅用于测试),生产集成请按下一节注入自己的 `IdentityService`。 -## Identity integration (organizational data) +## 接入组织架构(IdentityService) -The engine does not bind to any user system. Tasks offered to roles, departments or managers resolve their assignees through the `service.IdentityService` interface — in production you must inject an implementation backed by your own user/role/department tables (the built-in in-memory mock is for tests only): +引擎不绑定任何用户体系。按角色/部门/主管发起的审批任务,办理人统一通过 `service.IdentityService` 接口解析——生产环境必须注入宿主应用自己的实现(对接真实的用户/角色/部门表),内置的内存 Mock 仅供测试: ```go -// Implement all 9 methods of service.IdentityService against your org tables +// 实现 service.IdentityService 的全部 9 个方法,对接你自己的组织架构表 type OrgIdentityService struct { - db *gorm.DB // host application data source + db *gorm.DB // 宿主应用数据源 } -// Users by role (role candidate tasks); the other methods follow the same pattern +// 按角色查用户(role 候选任务展开),其余方法同理 func (s *OrgIdentityService) GetUserIDsByRoleID(ctx context.Context, tenantID, roleID string) ([]string, error) { var userIDs []string err := s.db.WithContext(ctx). @@ -201,18 +207,18 @@ func (s *OrgIdentityService) GetUserIDsByRoleID(ctx context.Context, tenantID, r return userIDs, err } -// Remaining methods and their purpose: -// GetUserIDsByDepartmentID users by department (dept candidate tasks) -// GetDepartmentManagerUserID department manager (dept candidate tasks) -// GetUserManagerID direct manager (direct_manager candidate tasks) -// GetUserManagerHierarchy manager hierarchy (multi_level_manager candidate tasks) -// GetUserDepartmentID department of a user -// GetRoleIDsByUserID roles of a user (todo visibility for role candidates) -// GetDepartmentIDsByUserID departments of a user (todo visibility for dept candidates) -// GetUserIDsByGroupID users by custom group (reserved extension) +// 其余待实现方法与用途: +// GetUserIDsByDepartmentID 按部门查用户(dept 候选任务) +// GetDepartmentManagerUserID 查部门主管(dept 候选任务) +// GetUserManagerID 查直接主管(direct_manager 候选任务) +// GetUserManagerHierarchy 查多级主管(multi_level_manager 候选任务) +// GetUserDepartmentID 按用户反查部门 +// GetRoleIDsByUserID 按用户反查角色(role 候选任务的待办可见性) +// GetDepartmentIDsByUserID 按用户反查部门列表(dept 候选任务的待办可见性) +// GetUserIDsByGroupID 按自定义组查用户(预留扩展) ``` -Inject it through the builder: +通过 Builder 注入: ```go engine, err := service.NewWorkflowEngineBuilder(). @@ -222,64 +228,63 @@ engine, err := service.NewWorkflowEngineBuilder(). Build() ``` -Mapping from candidate configuration (`candidateType`) to interface methods: +候选人配置(`candidateType`)与接口方法的对应关系: -| candidateType | Resolving methods | +| candidateType | 解析用的接口方法 | |---|---| -| `user` | none (user IDs given directly via `candidateUsers`) | -| `role` | `GetUserIDsByRoleID`; todo visibility via `GetRoleIDsByUserID` | -| `dept` | `GetUserIDsByDepartmentID` / `GetDepartmentManagerUserID`; todo visibility via `GetDepartmentIDsByUserID` | +| `user` | 无需身份服务(`candidateUsers` 直接给用户 ID) | +| `role` | `GetUserIDsByRoleID`;待办可见性走 `GetRoleIDsByUserID` | +| `dept` | `GetUserIDsByDepartmentID` / `GetDepartmentManagerUserID`;待办可见性走 `GetDepartmentIDsByUserID` | | `direct_manager` | `GetUserManagerID` | | `multi_level_manager` | `GetUserManagerHierarchy` | -| `initiator_select` / `initiator_self` | none (chosen by initiator / the initiator) | +| `initiator_select` / `initiator_self` | 无需身份服务(发起人自选 / 发起人本人) | -> Optional hardening: if the implementation also implements `TenantMembershipChecker` (`IsUserInTenant`), the engine verifies that transfer/delegation/reassign targets belong to the task's tenant and blocks cross-tenant reassignment; without it the check is skipped (with a warning logged). +> 可选加固:宿主实现若同时实现 `TenantMembershipChecker` 接口(`IsUserInTenant`),引擎会在转办/委派/改派时校验目标用户属于任务租户,阻断跨租户转派;未实现时跳过校验并告警留痕。 -## Process DSL +## 流程 DSL -A process definition is a `RuleGo` rule chain: `nodes` describe the steps, `connections` describe the flow, and approval configuration lives in each node's `configuration`. The BPM extension nodes: +流程定义是一条 `RuleGo` 规则链:`nodes` 描述节点,`connections` 描述流转边,表单和审批配置写在节点 `configuration` 中。BPM 扩展节点如下: -| Node type | Description | +| 节点 type | 说明 | |---|---| -| `startTask` | Start node: marks the process entry point; no auth checks (handled by the initiator layer) | -| `userTask` | Human approval task: single/countersign, candidates (user/role/department), form (`formKey` passed through to `wf_task.form_key`), priority, due date; `configuration.taskName`/`taskDescription` override the node name/description | -| `ccTask` | CC task: creates a CC record and notifies the host app via `CCTaskCreatedListener` | -| `serviceTask` | Service task: invokes a Go function (registered via `action.Functions`) | -| `automation` | Automation node: invokes a `RuleGo` rule chain | -| `subProcess` | Sub-process: starts an independent child instance, then returns to the parent flow | -| `aiAgent` | AI agent node: invokes an agent rule chain and routes the output | -| `httpCall` | HTTP call: synchronous external request, response merged into process variables | -| `startProcess` | Rule-chain-only: starts a BPM process instance from within a rule chain (e.g. scheduled auto-start of approvals) | +| `startTask` | 发起节点:流程起点标记,不做鉴权 | +| `userTask` | 用户审批任务:或签/会签、候选人(人员/角色/部门)、表单(`formKey` 透传到 `wf_task.form_key`)、优先级、截止时间;`configuration.taskName`/`taskDescription` 可覆盖节点名与描述 | +| `ccTask` | 抄送任务:生成抄送记录并通过 `CCTaskCreatedListener` 回调宿主应用 | +| `serviceTask` | 服务任务:调用 Go 函数(经 `action.Functions` 注册) | +| `automation` | 自动化节点:调用 `RuleGo` 规则链 | +| `subProcess` | 子流程:启动独立子流程实例,结束后回到主流程 | +| `aiAgent` | AI 智能体节点:调用智能体规则链并路由输出 | +| `httpCall` | HTTP 调用:同步请求外部接口,响应按映射合并进流程变量 | +| `startProcess` | 规则链专用:链内发起 BPM 流程实例(如定时自动发起审批) | -Native `RuleGo` nodes (`switch` gateways, `fork`/`inclusive`/`join` parallel joins, ...) can be used directly — see the [RuleGo standard components](https://rulego.cc/pages/standard-components/). +`RuleGo` 原生节点(`switch` 条件分支、`fork`/`inclusive`/`join` 并行汇聚等)可直接参与编排,详见 [RuleGo 标准组件](https://rulego.cc/pages/standard-components/)。 -For the full node reference (configuration fields, approval modes, reject strategies, `httpCall` SSRF protection) see [docs/components.md](docs/components.md). The complete documentation set for embedders — task lifecycle, events, persistence model — is indexed in [docs/README.md](docs/README.md). +各节点的完整参考(配置字段、审批模式、驳回策略、`httpCall` SSRF 防护)见 [docs/components.md](docs/components.md)。面向集成者的完整文档(任务生命周期、事件、数据模型)索引见 [docs/README.md](docs/README.md)。 -## Extension points +## 扩展点 -* **Identity:** implement `service.IdentityService` to resolve approvers by role, department, group or manager hierarchy. -* **SQL dialect:** implement `service.DialectProvider` to support additional databases — see [examples/custom_dialect](examples/custom_dialect) (Dameng, Kingbase). -* **Distributed locking:** the engine ships a built-in local in-memory lock (`lock.NewLocalLock`). For multi-instance deployments, implement the `lock.Locker` interface (e.g. Redis `SET NX` with a Lua-script release) and inject it via `WorkflowEngineBuilder.SetLocker`. -* **Task events:** `TaskEventListener` / `CCTaskCreatedListener` receive task lifecycle events to drive notifications and other side effects — see [docs/events.md](docs/events.md) for the full event catalog, payload fields and integration guide. +* **身份服务:** 实现 `service.IdentityService`,按角色/部门/组/多级主管解析审批人。 +* **数据库方言:** 实现 `service.DialectProvider` 注册新数据库,见 [examples/custom_dialect](examples/custom_dialect)(达梦、人大金仓)。 +* **分布式锁:** 引擎内置本地内存锁(`lock.NewLocalLock`);多实例部署请自行实现 `lock.Locker` 接口(如基于 Redis 的 SET NX + Lua 脚本释放),并经 `WorkflowEngineBuilder.SetLocker` 注入。 +* **任务事件:** `TaskEventListener` / `CCTaskCreatedListener` 接收任务生命周期事件,驱动站内通知等副作用;完整事件目录、载荷字段与对接示例见 [docs/events.md](docs/events.md)。 -## Ecosystem +## 生态 -- [RuleGo](https://github.com/rulego/rulego) — the underlying rule engine -- Documentation: -- GFlow Engine source: [Gitee](https://gitee.com/rulego/gflow-engine) · [GitHub](https://github.com/rulego/gflow-engine) -- **GFlow Platform**(极风工作流)— the GFlow Enterprise Edition, a ready-to-run approval platform built on GFlow Engine (backend + UI + designers); site: , live demo at +- [RuleGo](https://github.com/rulego/rulego) :底层规则引擎 +- 文档: +- GFlow Engine 源码:[Gitee](https://gitee.com/rulego/gflow-engine) · [GitHub](https://github.com/rulego/gflow-engine) +- **GFlow Platform**(极风工作流):GFlow 企业版,基于 GFlow Engine 的开箱即用审批工作流平台(服务端 + 前端 + 设计器),官网 ,在线演示 -## Contact & commercial licensing +## 联系与商业授权 -GFlow Engine is free and open source (Apache-2.0). If you need the Enterprise Edition — -**GFlow Platform**(极风工作流)with source-code delivery (flow/form designers, approval UI, -AI review) — or commercial support, see or reach us through -any of these channels (please mention your purpose when adding): +GFlow Engine 按 Apache-2.0 开源免费使用。如需源码交付、开箱即用的企业版 +**GFlow Platform**(极风工作流,含流程/表单设计器、审批界面、AI 审批)或商业支持, +请访问 ,或通过以下方式联系(添加烦请注明来意): -- QQ: [2215016127](tencent://message/?uin=2215016127&Site=&Menu=yes) -- WeChat: `rulegoteam` -- Email: [rulego@outlook.com](mailto:rulego@outlook.com) +- QQ:[2215016127](tencent://message/?uin=2215016127&Site=&Menu=yes) +- 微信:`rulegoteam` +- 邮件:[rulego@outlook.com](mailto:rulego@outlook.com) -## License +## 许可 -`GFlow Engine` is licensed under Apache 2.0. See the [LICENSE](LICENSE) file for details. +`GFlow Engine` 使用 Apache 2.0 许可证,详情请参见 [LICENSE](LICENSE) 文件。 diff --git a/README_EN.md b/README_EN.md new file mode 100644 index 0000000..0f91d92 --- /dev/null +++ b/README_EN.md @@ -0,0 +1,296 @@ +# GFlow Engine + +[![GoDoc](https://pkg.go.dev/badge/github.com/rulego/gflow-engine)](https://pkg.go.dev/github.com/rulego/gflow-engine) +[![Go Report](https://goreportcard.com/badge/github.com/rulego/gflow-engine)](https://goreportcard.com/report/github.com/rulego/gflow-engine) + +English | [简体中文](README.md) + +> **GFlow** — AI pre-screens · Humans approve · Automation follows +> +> **GFlow Engine** — the embeddable approval workflow engine at the core of the GFlow product family (open-source edition). +> It ships as a Go library: no UI, no HTTP server — you drive it from your own application. +> +> Need something ready to run? **GFlow Platform(极风工作流)** is the GFlow Enterprise Edition, +> with a flow designer, form designer, approval UI and AI review built in. +> Site: · Live demo: (`admin` / `admin123`) + +`GFlow Engine` is a lightweight, embeddable approval workflow engine built on [RuleGo](https://github.com/rulego/rulego). Process definitions reuse the `RuleGo` rule-chain DSL (JSON), while tasks, process instances and history are persisted to a relational database by the engine itself — no separate process middleware to deploy. Approval nodes and automation nodes (rule chains, HTTP calls, AI agents, sub-processes) live in the same process DSL — downstream actions run automatically once approved; Chinese-style approval semantics (or-sign, countersign, dynamic add/remove signers, return) work out of the box. + +> Note: the DSL is a BPMN-style approval flow in JSON form; it does not parse BPMN 2.0 XML. + +## Features + +* **Rule chain as process, approval + automation in one DSL** + * **Rule chain as process:** the DSL is a `RuleGo` rule chain. Native nodes such as gateways (`switch`) and parallel branches (`fork`/`inclusive`/`join`) can be mixed into approval flows directly. + * **Approval and automation in one chain:** `serviceTask` calls Go functions, `automation` invokes `RuleGo` rule chains, `aiAgent` talks to agent rule chains ([rulego-components-ai](https://github.com/rulego/rulego-components-ai)), and `httpCall` performs synchronous HTTP calls. + * **Sub-processes:** the `subProcess` node starts an independent child instance and returns to the parent flow on completion. +* **Chinese-style approval semantics & process model** + * **Chinese-style approval semantics:** single sign-off, countersign (parallel/sequential, all/majority), dynamic add/remove signers, transfer, delegation, claim, return, withdraw, suspend/resume, overdue handling — out of the box, no extra development. + * **Candidate-group tasks:** tasks can be offered to users, roles or departments; the candidate pool (`wf_task_assignee`) is stored separately and expanded through `IdentityService` at query time. + * **Approval comments:** task comments live in `wf_task_comment` and survive task archival; approval actions record their comment in the same transaction. + * **Versioned definitions:** each `process_key` keeps multiple published versions; running instances continue on the version they started with. +* **Integration & extension** + * **Pluggable identity:** implement `IdentityService` to resolve approvers from your real user/role/department data (by role, department, group or manager hierarchy). The built-in mock is for tests only. + * **Event hooks:** 17 task lifecycle events dispatched after commit (full catalog in [docs/events.md](docs/events.md)); register one or many listeners via the builder. Platform hooks: cross-tenant overdue scan (`ScanOverdueTasks`) and batch claimable-instance lookup (`GetClaimableInstanceIDs`). + * **Pluggable SQL dialects:** PostgreSQL / MySQL out of the box; register others (SQLite, Dameng, Kingbase, ...) via `DialectProvider` — see the examples directory. +* **Architecture & deployment** + * **Runtime/history split:** in-flight data and archived data live in separate tables, so reporting and audits never contend with the hot path. + * **Multi-tenancy:** `tenant_id` isolation end to end, with per-tenant rule-engine pools. + * **Lightweight:** no mandatory external middleware (a local in-memory lock is built in; distributed locking is pluggable). Fits embedding into existing applications. + +## Installation + +```bash +go get github.com/rulego/gflow-engine +``` + +Requires Go 1.24+ and RuleGo v0.37+. Initialize the workflow tables with `scripts/00.init_bpm_pg.sql` (PostgreSQL) or `scripts/00.init_bpm_mysql.sql` (MySQL); initialization and upgrade guidance lives in [docs/migration.md](docs/migration.md). + +## Database setup + +The engine manages only its own workflow tables; users, roles and departments belong to the host application. + +**PostgreSQL:** + +```bash +createdb gflow # create the database first (or: psql -c "CREATE DATABASE gflow") +psql -d gflow -f scripts/00.init_bpm_pg.sql +``` + +**MySQL:** + +```bash +mysql -u root -p -e "CREATE DATABASE gflow DEFAULT CHARACTER SET utf8mb4" +mysql -u root -p gflow < scripts/00.init_bpm_mysql.sql +``` + +Tables created: `wf_process` (definitions), `wf_instance` / `wf_hi_instance` (runtime/history instances), `wf_task` / `wf_hi_task` (runtime/history tasks), `wf_task_assignee` (candidate pool), `wf_task_comment` (approval comments). + +> The init scripts are idempotent (`CREATE TABLE IF NOT EXISTS`) — re-running them on an existing database never deletes or modifies data. Unit tests run on an in-memory SQLite database and need no scripts. The optional real-database lock test (`TestWithInstanceTx_RealDB_ForUpdateSerializes`) runs only when `TEST_PG_DSN` or `TEST_MYSQL_DSN` points to an existing database; it creates and drops its own `gflow_locktest` scratch database. + +## Quick start + +Run the complete example before integrating it yourself (deploy → start → approve → inspect instance status in one go, zero-dependency on in-memory SQLite): + +```bash +go run ./examples/leave_approval +``` + +Minimal integration code: + +```go +package main + +import ( + "context" + "log" + + "github.com/rulego/gflow-engine/components" + "github.com/rulego/gflow-engine/config" + "github.com/rulego/gflow-engine/model" + "github.com/rulego/gflow-engine/service" +) + +func main() { + ctx := context.Background() + + // 1. Configure the database and start the engine + cfg := &config.Config{ + Database: &config.DatabaseConfig{ + Driver: "postgres", + Dsn: "host=127.0.0.1 user=postgres password=postgres dbname=gflow port=5432 sslmode=disable", + }, + } + engine, err := service.NewWorkflowEngineBuilder(). + SetName("demo"). + SetConfig(cfg). + SetIDGenerator(service.NewIDGenerator()). + Build() + if err != nil { + log.Fatalf("build engine: %v", err) + } + if err := engine.Start(ctx); err != nil { + log.Fatalf("start engine: %v", err) + } + defer engine.Stop(ctx) + + // 2. Register workflow node components (userTask/serviceTask/automation/...) + // Dependencies are pulled from the engine itself; register your host service + // functions via WithServiceFuncs — see docs/components.md. + // Note: engine.Start must have succeeded first, otherwise registration + // fails fast with an error. + if err := components.RegisterFromEngine(engine); err != nil { + log.Fatalf("register components: %v", err) + } + + // 3. Deploy a process definition (the DSL is a rulego rule chain JSON, + // see examples/leave_approval). All mutating operations take an explicit + // actor — the operator identity used for auditing and permission checks. + admin := service.Actor{UserID: "admin", UserName: "admin", TenantID: "default"} + _, err = engine.GetProcessService().Deploy(ctx, admin, &model.WfProcess{ + ProcessKey: "leave_approval", + Name: "Leave Approval", + DefinitionJSON: leaveApprovalDSL, // process DSL JSON; see examples/leave_approval/dsl.json for reference + TenantID: "default", + CreatedBy: "admin", + }, true) + if err != nil { + log.Fatalf("deploy process: %v", err) + } + + // 4. Start a process instance (pass service.WithDraft() as a variadic + // option to start in draft mode; omit it for a normal start) + instanceID, err := engine.GetRuntimeService().StartProcessInstanceByKey( + ctx, + service.Actor{UserID: "emp001", UserName: "Zhang San", TenantID: "default"}, + "leave_approval", + "leave_emp001_1", // business key + map[string]interface{}{"days": 5, "managerId": "mgr001", "reason": "family affairs"}, + ) + if err != nil { + log.Fatalf("start instance: %v", err) + } + log.Printf("instance started: %s", instanceID) +} +``` + +Handling a pending task (also import `github.com/rulego/gflow-engine/types/dto` and `.../types/enums`): + +```go +tasks, _, err := engine.GetTaskService().GetTaskList(ctx, service.Actor{ + UserID: "mgr001", + TenantID: "default", +}, &dto.TaskQuery{ + Assignee: "mgr001", + PageRequest: dto.PageRequest{ + Status: []string{string(enums.TaskStatusPending), string(enums.TaskStatusActive)}, + PageSize: 10, + }, +}) +if err != nil || len(tasks) == 0 { + return +} + +err = engine.GetTaskService().CompleteWithApproval(ctx, service.Actor{ + UserID: "mgr001", + TenantID: "default", +}, &service.ApprovalRequest{ + TaskID: tasks[0].ID, + ApprovalResult: enums.ApprovalResultApproved, + Comment: "approved", +}) +``` + +> **Security note — the operator is the explicit `actor Actor` parameter:** all approval +> and mutation operations (`CompleteWithApproval`, `Approve`, `Reject`, `Claim`, `Unclaim`, +> `Transfer`, `Reassign`, `Return`, `Withdraw`, `WithdrawByInstance`, `DeleteTask`, ...) +> receive the operator as an explicit `actor service.Actor` parameter; the engine checks +> assignee permission against `actor.UserID`. A call with no operator identity is rejected +> with `ErrAuthenticationRequired`, and an operator who is not the task assignee gets +> `ErrPermissionDenied`. Construct the `Actor` on the server side from your authentication +> layer (session/token) — never trust client input directly. + +A complete runnable example (single sign-off, parallel and sequential countersign) lives in [examples/leave_approval](examples/leave_approval) — it runs zero-dependency on an in-memory SQLite database by default (`GFLOW_DSN` switches to PostgreSQL/MySQL). An `httpCall` + `switch` combination example (query an external API, map the response into process variables, route by the result) lives in [examples/http_call](examples/http_call). The engine ships with an in-memory mock identity service for tests only — inject your own `IdentityService` as described in the next section for production. + +## Identity integration (organizational data) + +The engine does not bind to any user system. Tasks offered to roles, departments or managers resolve their assignees through the `service.IdentityService` interface — in production you must inject an implementation backed by your own user/role/department tables (the built-in in-memory mock is for tests only): + +```go +// Implement all 9 methods of service.IdentityService against your org tables +type OrgIdentityService struct { + db *gorm.DB // host application data source +} + +// Users by role (role candidate tasks); the other methods follow the same pattern +func (s *OrgIdentityService) GetUserIDsByRoleID(ctx context.Context, tenantID, roleID string) ([]string, error) { + var userIDs []string + err := s.db.WithContext(ctx). + Table("user_roles"). + Where("tenant_id = ? AND role_id = ?", tenantID, roleID). + Pluck("user_id", &userIDs).Error + return userIDs, err +} + +// Remaining methods and their purpose: +// GetUserIDsByDepartmentID users by department (dept candidate tasks) +// GetDepartmentManagerUserID department manager (dept candidate tasks) +// GetUserManagerID direct manager (direct_manager candidate tasks) +// GetUserManagerHierarchy manager hierarchy (multi_level_manager candidate tasks) +// GetUserDepartmentID department of a user +// GetRoleIDsByUserID roles of a user (todo visibility for role candidates) +// GetDepartmentIDsByUserID departments of a user (todo visibility for dept candidates) +// GetUserIDsByGroupID users by custom group (reserved extension) +``` + +Inject it through the builder: + +```go +engine, err := service.NewWorkflowEngineBuilder(). + SetName("demo"). + SetConfig(cfg). + SetIdentityService(&OrgIdentityService{db: gormDB}). + Build() +``` + +Mapping from candidate configuration (`candidateType`) to interface methods: + +| candidateType | Resolving methods | +|---|---| +| `user` | none (user IDs given directly via `candidateUsers`) | +| `role` | `GetUserIDsByRoleID`; todo visibility via `GetRoleIDsByUserID` | +| `dept` | `GetUserIDsByDepartmentID` / `GetDepartmentManagerUserID`; todo visibility via `GetDepartmentIDsByUserID` | +| `direct_manager` | `GetUserManagerID` | +| `multi_level_manager` | `GetUserManagerHierarchy` | +| `initiator_select` / `initiator_self` | none (chosen by initiator / the initiator) | + +> Optional hardening: if the implementation also implements `TenantMembershipChecker` (`IsUserInTenant`), the engine verifies that transfer/delegation/reassign targets belong to the task's tenant and blocks cross-tenant reassignment; without it the check is skipped (with a warning logged). + +## Process DSL + +A process definition is a `RuleGo` rule chain: `nodes` describe the steps, `connections` describe the flow, and approval configuration lives in each node's `configuration`. The BPM extension nodes: + +| Node type | Description | +|---|---| +| `startTask` | Start node: marks the process entry point; no auth checks (handled by the initiator layer) | +| `userTask` | Human approval task: single/countersign, candidates (user/role/department), form (`formKey` passed through to `wf_task.form_key`), priority, due date; `configuration.taskName`/`taskDescription` override the node name/description | +| `ccTask` | CC task: creates a CC record and notifies the host app via `CCTaskCreatedListener` | +| `serviceTask` | Service task: invokes a Go function (registered via `action.Functions`) | +| `automation` | Automation node: invokes a `RuleGo` rule chain | +| `subProcess` | Sub-process: starts an independent child instance, then returns to the parent flow | +| `aiAgent` | AI agent node: invokes an agent rule chain and routes the output | +| `httpCall` | HTTP call: synchronous external request, response merged into process variables | +| `startProcess` | Rule-chain-only: starts a BPM process instance from within a rule chain (e.g. scheduled auto-start of approvals) | + +Native `RuleGo` nodes (`switch` gateways, `fork`/`inclusive`/`join` parallel joins, ...) can be used directly — see the [RuleGo standard components](https://rulego.cc/pages/standard-components/). + +For the full node reference (configuration fields, approval modes, reject strategies, `httpCall` SSRF protection) see [docs/components.md](docs/components.md). The complete documentation set for embedders — task lifecycle, events, persistence model — is indexed in [docs/README.md](docs/README.md). + +## Extension points + +* **Identity:** implement `service.IdentityService` to resolve approvers by role, department, group or manager hierarchy. +* **SQL dialect:** implement `service.DialectProvider` to support additional databases — see [examples/custom_dialect](examples/custom_dialect) (Dameng, Kingbase). +* **Distributed locking:** the engine ships a built-in local in-memory lock (`lock.NewLocalLock`). For multi-instance deployments, implement the `lock.Locker` interface (e.g. Redis `SET NX` with a Lua-script release) and inject it via `WorkflowEngineBuilder.SetLocker`. +* **Task events:** `TaskEventListener` / `CCTaskCreatedListener` receive task lifecycle events to drive notifications and other side effects — see [docs/events.md](docs/events.md) for the full event catalog, payload fields and integration guide. + +## Ecosystem + +- [RuleGo](https://github.com/rulego/rulego) — the underlying rule engine +- Documentation: +- GFlow Engine source: [Gitee](https://gitee.com/rulego/gflow-engine) · [GitHub](https://github.com/rulego/gflow-engine) +- **GFlow Platform**(极风工作流)— the GFlow Enterprise Edition, a ready-to-run approval platform built on GFlow Engine (backend + UI + designers); site: , live demo at + +## Contact & commercial licensing + +GFlow Engine is free and open source (Apache-2.0). If you need the Enterprise Edition — +**GFlow Platform**(极风工作流)with source-code delivery (flow/form designers, approval UI, +AI review) — or commercial support, see or reach us through +any of these channels (please mention your purpose when adding): + +- QQ: [2215016127](tencent://message/?uin=2215016127&Site=&Menu=yes) +- WeChat: `rulegoteam` +- Email: [rulego@outlook.com](mailto:rulego@outlook.com) + +## License + +`GFlow Engine` is licensed under Apache 2.0. See the [LICENSE](LICENSE) file for details. diff --git a/README_ZH.md b/README_ZH.md deleted file mode 100644 index e0f0f1a..0000000 --- a/README_ZH.md +++ /dev/null @@ -1,279 +0,0 @@ -# GFlow Engine - -[![GoDoc](https://pkg.go.dev/badge/github.com/rulego/gflow-engine)](https://pkg.go.dev/github.com/rulego/gflow-engine) -[![Go Report](https://goreportcard.com/badge/github.com/rulego/gflow-engine)](https://goreportcard.com/report/github.com/rulego/gflow-engine) - -[English](README.md) | 简体中文 - -> **GFlow** · 审批如风,极速流转 -> -> **GFlow Engine**——GFlow 产品家族的核心,可嵌入的审批工作流引擎(开源版)。 -> 以 Go 库形式发布,不含界面、不提供 HTTP 服务,由宿主应用集成驱动。 -> -> 需要开箱即用?**GFlow Platform(极风工作流)** 即 GFlow 企业版, -> 提供流程设计器、表单设计器、审批界面与 AI 审批。 -> 官网 · 在线演示 (`admin` / `admin123`) - -`GFlow Engine` 是一个基于 [RuleGo](https://github.com/rulego/rulego) 的轻量级、可嵌入审批工作流引擎。流程定义复用 `RuleGo` 规则链 DSL(JSON),审批任务、流程实例、历史归档等状态由引擎持久化到关系数据库,无需部署独立的流程中间件。 - -> 注意:DSL 为 JSON 格式的类 BPMN 审批流,不解析 BPMN 2.0 XML。 - -## 特性 - -* **规则链即流程:** 流程 DSL 复用 `RuleGo` 规则链,网关(`switch` 条件分支)、并行分支(`fork`/`inclusive`/`join`)等原生节点可直接编排,流程即规则、规则即流程。 -* **完整审批语义:** 或签(or)、会签(并行/顺序,全票/多数)、动态加签/减签、转办、委托、签收/抢单、退回、撤回、挂起/恢复、超时催办。 -* **候选组待办:** 任务可按人员/角色/部门发起,候选人池(`wf_task_assignee`)独立存储,查询时经 `IdentityService` 展开。 -* **子流程:** `subProcess` 节点启动独立子流程实例,嵌套审批闭环。 -* **与规则引擎联动:** `serviceTask` 调用 Go 函数,`automation` 节点调用 `RuleGo` 规则链,`aiAgent` 节点对接智能体规则链([rulego-components-ai](https://github.com/rulego/rulego-components-ai)),`httpCall` 节点同步调用外部接口。 -* **运行时/历史双表:** 进行中数据与归档数据分离,报表和审计查询不拖累运行时。 -* **多租户:** 全链路 `tenant_id` 隔离,规则链执行池按租户划分。 -* **可插拔身份体系:** 实现 `IdentityService` 对接真实的用户/角色/部门数据(按角色、部门、组、多级主管解析审批人);内置 Mock 实现仅用于测试。 -* **可插拔数据库方言:** 内置 PostgreSQL / MySQL,通过 `DialectProvider` 可扩展其它数据库(SQLite、达梦、人大金仓等,见 examples 目录)。 -* **流程定义版本化:** 同一 `process_key` 按 `version` 递增保留多个发布版本,存量实例继续运行旧版本。 -* **审批意见:** 评论存于 `wf_task_comment`,任务归档后仍可读写;审批动作与意见在同一事务落库。 -* **事件钩子:** 17 个任务全生命周期事件(发起/分配/候选创建/认领/取消认领/通过/驳回/转办/加签/减签/委派归还/退回/撤回/挂起/恢复/完成/终止)均在事务提交后派发;构建器支持注册一个或多个监听器。平台级钩子:跨租户逾期扫描(`ScanOverdueTasks`)、批量可认领实例判断(`GetClaimableInstanceIDs`)。 -* **轻量部署:** 无必须的外部中间件(内置本地内存锁,分布式锁可插拔),适合嵌入现有应用。 - -## 安装 - -```bash -go get github.com/rulego/gflow-engine -``` - -要求 Go 1.24+、RuleGo v0.37+。数据库表初始化脚本为 `scripts/00.init_bpm_pg.sql`(PostgreSQL)与 `scripts/00.init_bpm_mysql.sql`(MySQL),初始化与升级说明见 [docs/migration.md](docs/migration.md)。 - -## 初始化数据库 - -引擎只维护自己的工作流表,用户/角色/部门等系统表由宿主应用负责。 - -**PostgreSQL:** - -```bash -createdb gflow # 首次使用先建库(或 psql -c "CREATE DATABASE gflow") -psql -d gflow -f scripts/00.init_bpm_pg.sql -``` - -**MySQL:** - -```bash -mysql -u root -p -e "CREATE DATABASE gflow DEFAULT CHARACTER SET utf8mb4" -mysql -u root -p gflow < scripts/00.init_bpm_mysql.sql -``` - -建表清单:`wf_process`(流程定义)、`wf_instance` / `wf_hi_instance`(实例运行时/历史)、`wf_task` / `wf_hi_task`(任务运行时/历史)、`wf_task_assignee`(候选人池)、`wf_task_comment`(审批意见)。 - -> 初始化脚本为幂等设计(`CREATE TABLE IF NOT EXISTS`),在已有库上重跑不会删除/改写任何数据。单元测试使用 SQLite 内存库,无需执行脚本;可选的真实库行锁测试(`TestWithInstanceTx_RealDB_ForUpdateSerializes`)仅在设置 `TEST_PG_DSN` 或 `TEST_MYSQL_DSN`(指向任意现存库)时运行,会自建并清理 `gflow_locktest` 临时库。 - -## 快速开始 - -```go -package main - -import ( - "context" - "log" - - "github.com/rulego/gflow-engine/components" - "github.com/rulego/gflow-engine/config" - "github.com/rulego/gflow-engine/model" - "github.com/rulego/gflow-engine/service" -) - -func main() { - ctx := context.Background() - - // 1. 数据库配置并启动引擎 - cfg := &config.Config{ - Database: &config.DatabaseConfig{ - Driver: "postgres", - Dsn: "host=127.0.0.1 user=postgres password=postgres dbname=gflow port=5432 sslmode=disable", - }, - } - engine, err := service.NewWorkflowEngineBuilder(). - SetName("demo"). - SetConfig(cfg). - SetIDGenerator(service.NewIDGenerator()). - Build() - if err != nil { - log.Fatalf("build engine: %v", err) - } - if err := engine.Start(ctx); err != nil { - log.Fatalf("启动引擎失败: %v", err) - } - defer engine.Stop(ctx) - - // 2. 注册工作流节点组件(userTask/serviceTask/automation/...) - // 依赖由引擎自取;服务函数经 WithServiceFuncs 随引导注册(元数据进 - // 设计器目录,实现进运行时,用法见 docs/components.md)。 - // 注意:必须先 engine.Start 成功,否则注册会报错拦截。 - if err := components.RegisterFromEngine(engine); err != nil { - log.Fatalf("注册组件失败: %v", err) - } - - // 3. 部署流程定义(DSL 为 rulego 规则链 JSON,见 examples/leave_approval)。 - // 所有变更类操作的第一个业务参数都是显式 actor——用于审计与权限校验的操作人。 - admin := service.Actor{UserID: "admin", UserName: "admin", TenantID: "default"} - _, err = engine.GetProcessService().Deploy(ctx, admin, &model.WfProcess{ - ProcessKey: "leave_approval", - Name: "请假审批", - DefinitionJSON: leaveApprovalDSL, // 流程 DSL JSON - TenantID: "default", - CreatedBy: "admin", - }, true) - if err != nil { - log.Fatalf("部署流程失败: %v", err) - } - - // 4. 发起流程实例(追加可变参数 service.WithDraft() 即草稿模式;普通启动不传) - instanceID, err := engine.GetRuntimeService().StartProcessInstanceByKey( - ctx, - service.Actor{UserID: "emp001", UserName: "张三", TenantID: "default"}, - "leave_approval", - "leave_emp001_1", // 业务键 - map[string]interface{}{"days": 5, "managerId": "mgr001", "reason": "家中事务"}, - ) - if err != nil { - log.Fatalf("发起流程失败: %v", err) - } - _ = instanceID -} -``` - -审批人处理待办(需额外引入 `github.com/rulego/gflow-engine/types/dto` 与 `.../types/enums`): - -```go -tasks, _, err := engine.GetTaskService().GetTaskList(ctx, service.Actor{ - UserID: "mgr001", - TenantID: "default", -}, &dto.TaskQuery{ - Assignee: "mgr001", - PageRequest: dto.PageRequest{ - Status: []string{string(enums.TaskStatusPending), string(enums.TaskStatusActive)}, - PageSize: 10, - }, -}) -if err != nil || len(tasks) == 0 { - return -} - -err = engine.GetTaskService().CompleteWithApproval(ctx, service.Actor{ - UserID: "mgr001", - TenantID: "default", -}, &service.ApprovalRequest{ - TaskID: tasks[0].ID, - ApprovalResult: enums.ApprovalResultApproved, - Comment: "同意", -}) -``` - -> **安全说明——操作人由显式 `actor Actor` 参数传入:** -> 所有审批/变更类操作(`CompleteWithApproval`/`Approve`/`Reject`/`Claim`/`Unclaim`/ -> `Transfer`/`Reassign`/`Return`/`Withdraw`/`WithdrawByInstance`/`DeleteTask` 等)的 -> 操作人都是显式 `actor service.Actor` 参数,引擎以 `actor.UserID` 校验 assignee 权限。 -> 没有任何操作人身份的调用会以 `ErrAuthenticationRequired` 拒绝;操作人不是任务 -> 办理人则以 `ErrPermissionDenied` 拒绝。`Actor` 必须由宿主服务端从认证层 -> (session/token)构造,绝不直接透传客户端输入。 - -完整可运行示例(单签、并行会签、顺序会签)见 [examples/leave_approval](examples/leave_approval)——默认跑在内存 SQLite 上,零依赖直接运行(`GFLOW_DSN` 可切 PostgreSQL/MySQL);`httpCall` + `switch` 组合示例(查询外部接口 → 响应映射进流程变量 → 按结果路由)见 [examples/http_call](examples/http_call)。 - -## 接入组织架构(IdentityService) - -引擎不绑定任何用户体系。按角色/部门/主管发起的审批任务,办理人统一通过 `service.IdentityService` 接口解析——生产环境必须注入宿主应用自己的实现(对接真实的用户/角色/部门表),内置的内存 Mock 仅供测试: - -```go -// 实现 service.IdentityService 的全部 9 个方法,对接你自己的组织架构表 -type OrgIdentityService struct { - db *gorm.DB // 宿主应用数据源 -} - -// 按角色查用户(role 候选任务展开),其余方法同理 -func (s *OrgIdentityService) GetUserIDsByRoleID(ctx context.Context, tenantID, roleID string) ([]string, error) { - var userIDs []string - err := s.db.WithContext(ctx). - Table("user_roles"). - Where("tenant_id = ? AND role_id = ?", tenantID, roleID). - Pluck("user_id", &userIDs).Error - return userIDs, err -} - -// 其余待实现方法与用途: -// GetUserIDsByDepartmentID 按部门查用户(dept 候选任务) -// GetDepartmentManagerUserID 查部门主管(dept 候选任务) -// GetUserManagerID 查直接主管(direct_manager 候选任务) -// GetUserManagerHierarchy 查多级主管(multi_level_manager 候选任务) -// GetUserDepartmentID 按用户反查部门 -// GetRoleIDsByUserID 按用户反查角色(role 候选任务的待办可见性) -// GetDepartmentIDsByUserID 按用户反查部门列表(dept 候选任务的待办可见性) -// GetUserIDsByGroupID 按自定义组查用户(预留扩展) -``` - -通过 Builder 注入: - -```go -engine, err := service.NewWorkflowEngineBuilder(). - SetName("demo"). - SetConfig(cfg). - SetIdentityService(&OrgIdentityService{db: gormDB}). - Build() -``` - -候选人配置(`candidateType`)与接口方法的对应关系: - -| candidateType | 解析用的接口方法 | -|---|---| -| `user` | 无需身份服务(`candidateUsers` 直接给用户 ID) | -| `role` | `GetUserIDsByRoleID`;待办可见性走 `GetRoleIDsByUserID` | -| `dept` | `GetUserIDsByDepartmentID` / `GetDepartmentManagerUserID`;待办可见性走 `GetDepartmentIDsByUserID` | -| `direct_manager` | `GetUserManagerID` | -| `multi_level_manager` | `GetUserManagerHierarchy` | -| `initiator_select` / `initiator_self` | 无需身份服务(发起人自选 / 发起人本人) | - -> 可选加固:宿主实现若同时实现 `TenantMembershipChecker` 接口(`IsUserInTenant`),引擎会在转办/委派/改派时校验目标用户属于任务租户,阻断跨租户转派;未实现时跳过校验并告警留痕。 - -## 流程 DSL - -流程定义是一条 `RuleGo` 规则链:`nodes` 描述节点,`connections` 描述流转边,表单和审批配置写在节点 `configuration` 中。BPM 扩展节点如下: - -| 节点 type | 说明 | -|---|---| -| `startTask` | 发起节点:流程起点标记,不做鉴权 | -| `userTask` | 用户审批任务:或签/会签、候选人(人员/角色/部门)、表单(`formKey` 透传到 `wf_task.form_key`)、优先级、截止时间;`configuration.taskName`/`taskDescription` 可覆盖节点名与描述 | -| `ccTask` | 抄送任务:生成抄送记录并通过 `CCTaskCreatedListener` 回调宿主应用 | -| `serviceTask` | 服务任务:调用 Go 函数(经 `action.Functions` 注册) | -| `automation` | 自动化节点:调用 `RuleGo` 规则链 | -| `subProcess` | 子流程:启动独立子流程实例,结束后回到主流程 | -| `aiAgent` | AI 智能体节点:调用智能体规则链并路由输出 | -| `httpCall` | HTTP 调用:同步请求外部接口,响应按映射合并进流程变量 | -| `startProcess` | 规则链专用:链内发起 BPM 流程实例(如定时自动发起审批) | - -`RuleGo` 原生节点(`switch` 条件分支、`fork`/`inclusive`/`join` 并行汇聚等)可直接参与编排,详见 [RuleGo 标准组件](https://rulego.cc/pages/standard-components/)。 - -各节点的完整参考(配置字段、审批模式、驳回策略、`httpCall` SSRF 防护)见 [docs/components.md](docs/components.md)。面向集成者的完整文档(任务生命周期、事件、数据模型)索引见 [docs/README.md](docs/README.md)。 - -## 扩展点 - -* **身份服务:** 实现 `service.IdentityService`,按角色/部门/组/多级主管解析审批人。 -* **数据库方言:** 实现 `service.DialectProvider` 注册新数据库,见 [examples/custom_dialect](examples/custom_dialect)(达梦、人大金仓)。 -* **分布式锁:** 引擎内置本地内存锁(`lock.NewLocalLock`);多实例部署请自行实现 `lock.Locker` 接口(如基于 Redis 的 SET NX + Lua 脚本释放),并经 `WorkflowEngineBuilder.SetLocker` 注入。 -* **任务事件:** `TaskEventListener` / `CCTaskCreatedListener` 接收任务生命周期事件,驱动站内通知等副作用;完整事件目录、载荷字段与对接示例见 [docs/events.md](docs/events.md)。 - -## 生态 - -- [RuleGo](https://github.com/rulego/rulego) :底层规则引擎 -- 文档: -- GFlow Engine 源码:[Gitee](https://gitee.com/rulego/gflow-engine) · [GitHub](https://github.com/rulego/gflow-engine) -- **GFlow Platform**(极风工作流):GFlow 企业版,基于 GFlow Engine 的开箱即用审批工作流平台(服务端 + 前端 + 设计器),官网 ,在线演示 - -## 联系与商业授权 - -GFlow Engine 按 Apache-2.0 开源免费使用。如需源码交付、开箱即用的企业版 -**GFlow Platform**(极风工作流,含流程/表单设计器、审批界面、AI 审批)或商业支持, -请访问 ,或通过以下方式联系(添加烦请注明来意): - -- QQ:[2215016127](tencent://message/?uin=2215016127&Site=&Menu=yes) -- 微信:`rulegoteam` -- 邮件:[rulego@outlook.com](mailto:rulego@outlook.com) - -## 许可 - -`GFlow Engine` 使用 Apache 2.0 许可证,详情请参见 [LICENSE](LICENSE) 文件。 diff --git a/docs/README.md b/docs/README.md index 31970f4..2c9db67 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,7 +4,7 @@ GFlow Engine 是基于 RuleGo 的可嵌入式工作流(审批流)引擎。 | 文档 | 内容 | 适合谁 | |---|---|---| -| [README.md](../README.md) / [README_ZH.md](../README_ZH.md) | 安装、数据库初始化、快速开始、IdentityService 接入、扩展点 | 所有集成者(从这里开始) | +| [README.md](../README.md) / [README_EN.md](../README_EN.md) | 安装、数据库初始化、快速开始、IdentityService 接入、扩展点 | 所有集成者(从这里开始) | | [components.md](components.md) | 9 种流程节点的机制参考:注册与生命周期、审批模式、驳回策略、httpCall SSRF 防护 | 引擎集成者 | | [dsl-reference.md](dsl-reference.md) | 流程 DSL 编写参考:顶层结构(ruleChain/metadata/additionalInfo)、逐节点 configuration 字段表与 JSON 示例、组件清单接口 | 流程设计器实现方、DSL 编写者 | | [task-lifecycle.md](task-lifecycle.md) | 任务状态机、认领/转办/委托/完成操作、会签父子结构、历史归档 | 待办/审批界面实现方 | diff --git a/docs/dsl-reference.md b/docs/dsl-reference.md index 35b3ff0..fef1441 100644 --- a/docs/dsl-reference.md +++ b/docs/dsl-reference.md @@ -211,7 +211,7 @@ robfig/cron WithSeconds 约定)。**触发器是链级配置,不出现在画 触发时刻的动态值**(如"上个月的月份")——由链上首个 `jsTransform` 节点用 `new Date()` 计算(「定时发起审批」纯配置模式自动生成该节点)。 -> 已知限制(根 [README](../README_ZH.md#已知限制)「已知限制」小节有索引):**集群模式下 +> 已知限制:**集群模式下 > 定时触发不可用**,详见下段。 运行条件与链生命周期一致:单机部署 endpoint 框架默认开启,链**部署**后 cron 即生效,