mirror of
https://github.com/rulego/gflow-engine.git
synced 2026-12-05 16:02:03 +00:00
feat: 审批人收回,终态实例窗口期内可整单重审
This commit is contained in:
1 parent
d454f99019
commit
1afd3ab5ce
8 files changed
+1557
No files matched your search
@@ -324,6 +324,20 @@ func (s *RuntimeServiceImpl) GetProcessInstanceDetail(ctx context.Context, actor
|
||||
}
|
||||
}
|
||||
|
||||
// 审批人收回:运行中实例=本人存在可收回记录且守卫通过;已完成实例=发起人在
|
||||
// 窗口期内可整单重开(末节点重审)。守卫与 Recall 写路径同口径。
|
||||
if instance.Status == string(enums.InstanceStatusActive) && !designerDisabled(starterActionPermissions, "recall") {
|
||||
if t := findRecallableCompletedTask(tasks, currentUserId); t != nil {
|
||||
if evaluateRecallGuard(tasks, t, ruleChain) == nil {
|
||||
resp.ActionPermissions["recall"] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if instance.Status == string(enums.InstanceStatusCompleted) && !designerDisabled(starterActionPermissions, "recall") &&
|
||||
(instance.StartUserID == currentUserId || isWorkflowAdmin(&actor)) && withinRecallWindow(starterActionPermissions, instance.EndedAt) {
|
||||
resp.ActionPermissions["recall"] = true
|
||||
}
|
||||
|
||||
if currentUserTask != nil {
|
||||
switch currentUserTaskStatus {
|
||||
case string(enums.TaskStatusActive):
|
||||
|
||||
@@ -21,6 +21,7 @@ const (
|
||||
TaskEventSuspended TaskEventType = "suspended" // 实例挂起
|
||||
TaskEventActivated TaskEventType = "activated" // 实例恢复(含草稿激活)
|
||||
TaskEventWithdrawn TaskEventType = "withdrawn" // 发起人撤回实例
|
||||
TaskEventRecalled TaskEventType = "recalled" // 审批人收回(ToUsers 为被终止前沿任务的办理人)
|
||||
TaskEventStarted TaskEventType = "started" // 流程实例发起
|
||||
TaskEventReturned TaskEventType = "returned" // 任务退回到指定节点
|
||||
TaskEventAddSign TaskEventType = "addSign" // 加签(Reason 携带原因)
|
||||
|
||||
@@ -207,6 +207,11 @@ type TaskService interface {
|
||||
// Return 退回(将任务退回到指定节点)
|
||||
Return(ctx context.Context, actor Actor, taskID, targetActivityID, reason string) error
|
||||
|
||||
// Recall 收回(审批人撤销自己最近一条已通过的审批,重建自己的待审任务)。
|
||||
// 收回守卫见 task_service_recall.go:实例运行中、本人办理、无更晚办理记录、
|
||||
// 推进路径无自动化节点、流程停泊在人工任务上、流程级开关 recall 已开启。
|
||||
Recall(ctx context.Context, actor Actor, instanceID, reason string) error
|
||||
|
||||
// ========== 节点审批人管理 ==========
|
||||
|
||||
// GetNodeApprovalStatus 获取节点审批状态信息(actor 含租户时做任务归属校验,跨租户拒绝)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/rulego/gflow-engine/model"
|
||||
"github.com/rulego/gflow-engine/types/constants"
|
||||
"github.com/rulego/gflow-engine/types/enums"
|
||||
"github.com/rulego/rulego/api/types"
|
||||
)
|
||||
|
||||
// resolveNodeActionPermissions 返回某节点 additionalInfo.actionPermissions。
|
||||
@@ -65,6 +66,40 @@ func resolveNodeActionPermissions(ctx context.Context, engine WorkflowEngine, in
|
||||
return v
|
||||
}
|
||||
|
||||
// resolveProcessActionPermissions 读取流程级 actionPermissions
|
||||
// (ruleChain.additionalInfo,即设计器「高级设置」面板写入的发起人/审批人开关)。
|
||||
// 附带返回解析后的链定义,供收回路径守卫复用,避免二次解析。
|
||||
func resolveProcessActionPermissions(ctx context.Context, engine WorkflowEngine, processID string) (map[string]interface{}, *types.RuleChain, error) {
|
||||
if engine == nil || processID == "" {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: invalid engine/process")
|
||||
}
|
||||
processService := engine.GetProcessService()
|
||||
if processService == nil {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: process service not injected")
|
||||
}
|
||||
procDef, err := processService.Get(ctx, processID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: get process: %w", err)
|
||||
}
|
||||
if procDef == nil {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: process not found")
|
||||
}
|
||||
rc, err := procDef.ToRuleChain()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: parse rule chain: %w", err)
|
||||
}
|
||||
if rc == nil {
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: rule chain is nil")
|
||||
}
|
||||
if ap, ok := rc.RuleChain.GetAdditionalInfo("actionPermissions"); ok {
|
||||
if v, ok := ap.(map[string]interface{}); ok {
|
||||
return v, rc, nil
|
||||
}
|
||||
return nil, nil, fmt.Errorf("resolve process action permissions: invalid actionPermissions type")
|
||||
}
|
||||
return map[string]interface{}{}, rc, nil
|
||||
}
|
||||
|
||||
// resolveNodeActionPermissionsStrict 与上方的 lenient 版同源,但解析失败返回 error
|
||||
// 而非空 map。仅供 requireActionEnabled 做 fail-closed 校验:解析不出来说明无法判断
|
||||
// 设计器是否显式禁用了某动作,此时拒绝执行,避免解析失败绕过设计器的显式 disable。
|
||||
|
||||
@@ -0,0 +1,675 @@
|
||||
// This file implements Recall (审批人收回): an approver revokes their own
|
||||
// latest completed approval and gets a fresh pending task at the same node.
|
||||
// Unlike Withdraw (发起人撤回, terminates the whole instance), recall only
|
||||
// voids the recaller's own vote; peer countersign votes stay intact.
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rulego/gflow-engine/model"
|
||||
"github.com/rulego/gflow-engine/query"
|
||||
"github.com/rulego/gflow-engine/types/constants"
|
||||
"github.com/rulego/gflow-engine/types/dto"
|
||||
"github.com/rulego/gflow-engine/types/enums"
|
||||
"github.com/rulego/rulego/api/types"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// recallTransparentNodeTypes 收回路径检查中可穿越的节点类型:路由网关与
|
||||
// fork/join 走向取决于运行期条件但本身无业务副作用(fork/join 见
|
||||
// user_task_reject.go 的类型判定,链定义中真实存在);ccTask 是信息类
|
||||
// (抄送已发不构成业务动作)。
|
||||
var recallTransparentNodeTypes = map[string]bool{
|
||||
constants.NodeTypeSwitch: true,
|
||||
constants.NodeTypeJsSwitch: true,
|
||||
constants.NodeTypeMsgTypeSwitch: true,
|
||||
constants.NodeTypeInclusive: true,
|
||||
constants.NodeTypeRouteGateway: true,
|
||||
"condition": true,
|
||||
"fork": true,
|
||||
"join": true,
|
||||
constants.TaskTypeCCTask: true,
|
||||
constants.NodeTypeStart: true,
|
||||
"startTask": true,
|
||||
}
|
||||
|
||||
// Recall 收回(审批人撤销自己最近一条已通过的审批,重建自己的待审任务)。
|
||||
// 已完成(通过)实例走 recallCompleted:窗口期内发起人/管理员整单重开,末节点重审。
|
||||
func (s *TaskServiceImpl) Recall(ctx context.Context, actor Actor, instanceID, reason string) error {
|
||||
ctx = bindActor(ctx, actor)
|
||||
if instanceID == "" || actor.UserID == "" {
|
||||
return fmt.Errorf("instance ID and user ID cannot be empty")
|
||||
}
|
||||
|
||||
// 流程定义与开关解析放在锁外——WithInstanceTx 回调内只允许经 scope 访问 DB,
|
||||
// 而定义解析要读流程表。先无锁读实例拿 processID,锁内再以行锁快照复核状态与归属。
|
||||
inst, err := s.workflowEngine.GetRuntimeService().GetProcessInstance(ctx, ActorFromCtx(ctx), instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get process instance: %w", err)
|
||||
}
|
||||
if inst == nil {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
if u := GetUserFromCtx(ctx); u != nil && inst.TenantID != u.TenantID {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
|
||||
switch inst.Status {
|
||||
case string(enums.InstanceStatusActive):
|
||||
// 在途收回:走行锁事务
|
||||
case string(enums.InstanceStatusSuspended):
|
||||
return fmt.Errorf("%w: 流程已挂起,无法收回", ErrValidation)
|
||||
case string(enums.InstanceStatusCompleted):
|
||||
// 终态收回:实例已归档,窗口期内发起人/管理员整单重开
|
||||
return s.recallCompleted(ctx, actor, inst, instanceID, reason)
|
||||
default:
|
||||
return fmt.Errorf("%w: 流程已结束,无法收回", ErrValidation)
|
||||
}
|
||||
|
||||
ap, chain, err := resolveProcessActionPermissions(ctx, s.workflowEngine, inst.ProcessID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: 流程定义不可用,无法收回", ErrValidation)
|
||||
}
|
||||
if designerDisabled(ap, "recall") {
|
||||
return fmt.Errorf("%w: 该流程已关闭审批人收回", ErrPermissionDenied)
|
||||
}
|
||||
|
||||
return WithInstanceTx(ctx, s.taskDAO.Query, instanceID, func(scope *InstanceScope) error {
|
||||
return s.recallInternal(ctx, scope, chain, actor.UserID, instanceID, reason)
|
||||
})
|
||||
}
|
||||
|
||||
// defaultRecallWindowDays 终态收回窗口默认天数:窗口封顶"审批完成后下游已消费"的业务风险
|
||||
const defaultRecallWindowDays = 7
|
||||
|
||||
// withinRecallWindow 判断已完成实例是否仍在可收回窗口内(天数按流程级
|
||||
// recallWindowDays 覆盖,缺省 7 天)。
|
||||
func withinRecallWindow(ap map[string]interface{}, endedAt *time.Time) bool {
|
||||
if endedAt == nil {
|
||||
return false
|
||||
}
|
||||
return time.Since(*endedAt) <= time.Duration(recallWindowDays(ap))*24*time.Hour
|
||||
}
|
||||
|
||||
// recallWindowDays 从流程级配置解析终态收回窗口天数,非法或缺省回落 7 天。
|
||||
func recallWindowDays(ap map[string]interface{}) int {
|
||||
if v, ok := ap["recallWindowDays"].(float64); ok && v > 0 && v <= 365 {
|
||||
return int(v)
|
||||
}
|
||||
return defaultRecallWindowDays
|
||||
}
|
||||
|
||||
// recallCompleted 终态收回:已完成(通过)实例在窗口期内由发起人或管理员整单重开——
|
||||
// 实例复活为运行中,末节点经 ExecuteNext 重入按审批形态重建任务、整轮重审。
|
||||
// 不做"只撤自己一票"的变体:实例已归档,逐票回迁的复杂度换不来场景收益,
|
||||
// 末节点整轮重审对发起人反悔(主场景)语义更直白。
|
||||
func (s *TaskServiceImpl) recallCompleted(ctx context.Context, actor Actor, hi *model.WfInstance, instanceID, reason string) error {
|
||||
userID := actor.UserID
|
||||
if hi.StartUserID != userID && !isWorkflowAdmin(&actor) {
|
||||
return fmt.Errorf("%w: 已完成的审批仅发起人或管理员可收回", ErrPermissionDenied)
|
||||
}
|
||||
|
||||
ap, _, err := resolveProcessActionPermissions(ctx, s.workflowEngine, hi.ProcessID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: 流程定义不可用,无法收回", ErrValidation)
|
||||
}
|
||||
if designerDisabled(ap, "recall") {
|
||||
return fmt.Errorf("%w: 该流程已关闭审批人收回", ErrPermissionDenied)
|
||||
}
|
||||
if !withinRecallWindow(ap, hi.EndedAt) {
|
||||
return fmt.Errorf("%w: 超过可收回窗口(%d 天),无法收回", ErrValidation, recallWindowDays(ap))
|
||||
}
|
||||
|
||||
lastNode, voters, err := latestCompletedNodeInHistory(ctx, s.taskDAO.Query, instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to resolve last node: %w", err)
|
||||
}
|
||||
if lastNode == "" {
|
||||
return fmt.Errorf("%w: 实例无可重开的审批节点", ErrValidation)
|
||||
}
|
||||
|
||||
// 重入通道必须先确认可用:复活成功而重入失败会留下 active 但零任务的僵尸实例
|
||||
internal := s.workflowEngine.GetRuntimeServiceInternal()
|
||||
if internal == nil {
|
||||
return fmt.Errorf("%w: 引擎内部服务未注入,无法重开已完成实例", ErrValidation)
|
||||
}
|
||||
|
||||
// 复活实例:同 PK 回插运行表并移除归档行,并发双收回靠主键冲突天然互斥
|
||||
err = s.taskDAO.Query.Transaction(func(tx *query.Query) error {
|
||||
revived := &model.WfInstance{
|
||||
ID: hi.ID,
|
||||
ProcessID: hi.ProcessID,
|
||||
BusinessKey: hi.BusinessKey,
|
||||
Name: hi.Name,
|
||||
Status: string(enums.InstanceStatusActive),
|
||||
Variables: hi.Variables,
|
||||
CurrentActivity: hi.CurrentActivity,
|
||||
Priority: hi.Priority,
|
||||
ParentID: hi.ParentID,
|
||||
TenantID: hi.TenantID,
|
||||
CreatedBy: hi.CreatedBy,
|
||||
CreatedAt: hi.CreatedAt,
|
||||
StartUserID: hi.StartUserID,
|
||||
}
|
||||
if err := tx.WfInstance.WithContext(ctx).Create(revived); err != nil {
|
||||
return fmt.Errorf("failed to revive instance: %w", err)
|
||||
}
|
||||
if _, err := tx.WfHiInstance.WithContext(ctx).Where(tx.WfHiInstance.ID.Eq(instanceID)).Delete(); err != nil {
|
||||
return fmt.Errorf("failed to remove archived instance: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to reopen completed instance: %w", err)
|
||||
}
|
||||
|
||||
// 末节点投票人收到作废通知;重入后的新任务由组件派发 assigned 事件
|
||||
if listener := s.workflowEngine.GetTaskEventListener(); listener != nil {
|
||||
DispatchTaskEvent(listener, TaskEvent{
|
||||
Type: TaskEventRecalled,
|
||||
InstanceID: instanceID,
|
||||
ProcessID: hi.ProcessID,
|
||||
TenantID: hi.TenantID,
|
||||
ToUsers: voters,
|
||||
FromUser: userID,
|
||||
Reason: reason,
|
||||
Timestamp: time.Now(),
|
||||
}, ctx)
|
||||
}
|
||||
|
||||
// 重入末节点重建任务。失败则整体退回归档态补偿——不补偿会留下
|
||||
// active 但零任务的僵尸实例,且在途收回通道救不了它(无 completed 任务可寻)
|
||||
if err := internal.ExecuteNext(ctx, instanceID, lastNode, nil); err != nil {
|
||||
if cerr := s.rearchiveCompletedInstance(ctx, s.taskDAO.Query, hi, instanceID); cerr != nil {
|
||||
return fmt.Errorf("末节点重入失败且补偿失败,实例 %s 可能停留为无任务运行态需人工处理: 重入错误=%v 补偿错误=%w", instanceID, err, cerr)
|
||||
}
|
||||
return fmt.Errorf("%w: 末节点重入失败,已回滚为已完成态: %v", ErrValidation, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rearchiveCompletedInstance 终态收回的补偿:把复活后的实例连同重入期间
|
||||
// 可能建出的任务一并退回归档态,恢复到收回前的样子。
|
||||
func (s *TaskServiceImpl) rearchiveCompletedInstance(ctx context.Context, q *query.Query, hi *model.WfInstance, instanceID string) error {
|
||||
return q.Transaction(func(tx *query.Query) error {
|
||||
tasks, err := tx.WfTask.WithContext(ctx).Where(tx.WfTask.ProcessInstanceID.Eq(instanceID)).Find()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list tasks: %w", err)
|
||||
}
|
||||
if len(tasks) > 0 {
|
||||
now := time.Now()
|
||||
rollbackReason := "收回重开失败回滚"
|
||||
his := make([]*model.WfHiTask, 0, len(tasks))
|
||||
taskIDs := make([]string, 0, len(tasks))
|
||||
for _, tk := range tasks {
|
||||
if tk.Status == string(enums.TaskStatusActive) ||
|
||||
tk.Status == string(enums.TaskStatusPending) ||
|
||||
tk.Status == string(enums.TaskStatusSuspended) {
|
||||
tk.Status = string(enums.TaskStatusTerminated)
|
||||
tk.EndedAt = &now
|
||||
tk.EndReason = &rollbackReason
|
||||
}
|
||||
his = append(his, taskToHiTask(tk))
|
||||
taskIDs = append(taskIDs, tk.ID)
|
||||
}
|
||||
if err := tx.WfHiTask.WithContext(ctx).CreateInBatches(his, archiveBatchSize); err != nil {
|
||||
return fmt.Errorf("failed to archive tasks: %w", err)
|
||||
}
|
||||
if _, err := tx.WfTaskAssignee.WithContext(ctx).Where(tx.WfTaskAssignee.TaskID.In(taskIDs...)).Delete(); err != nil {
|
||||
logrus.Warnf("recall rollback: failed to clean task assignees: %v", err)
|
||||
}
|
||||
if _, err := tx.WfTask.WithContext(ctx).Where(tx.WfTask.ProcessInstanceID.Eq(instanceID)).Delete(); err != nil {
|
||||
return fmt.Errorf("failed to delete tasks: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.WfInstance.WithContext(ctx).Where(tx.WfInstance.ID.Eq(instanceID)).Delete(); err != nil {
|
||||
return fmt.Errorf("failed to delete revived instance: %w", err)
|
||||
}
|
||||
// hi 参数是运行表模型,归档表按完结归档的字段映射重建
|
||||
hiRow := &model.WfHiInstance{
|
||||
ID: hi.ID,
|
||||
ProcessID: hi.ProcessID,
|
||||
BusinessKey: hi.BusinessKey,
|
||||
Name: hi.Name,
|
||||
Status: hi.Status,
|
||||
Variables: hi.Variables,
|
||||
CurrentActivity: hi.CurrentActivity,
|
||||
Priority: hi.Priority,
|
||||
ParentID: hi.ParentID,
|
||||
TenantID: hi.TenantID,
|
||||
CreatedBy: hi.CreatedBy,
|
||||
CreatedAt: hi.CreatedAt,
|
||||
UpdatedBy: hi.UpdatedBy,
|
||||
UpdatedAt: hi.UpdatedAt,
|
||||
EndReason: hi.EndReason,
|
||||
Duration: hi.Duration,
|
||||
EndedAt: hi.EndedAt,
|
||||
StartUserID: hi.StartUserID,
|
||||
}
|
||||
if err := tx.WfHiInstance.WithContext(ctx).Create(hiRow); err != nil {
|
||||
return fmt.Errorf("failed to restore archived instance: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// latestCompletedNodeInHistory 在历史任务里找最近完成的 userTask 节点(末节点)
|
||||
// 及该节点全部投票人(去重,供作废通知)。
|
||||
func latestCompletedNodeInHistory(ctx context.Context, q *query.Query, instanceID string) (string, []string, error) {
|
||||
wt := q.WfHiTask
|
||||
var last model.WfHiTask
|
||||
err := wt.WithContext(ctx).
|
||||
Where(wt.ProcessInstanceID.Eq(instanceID)).
|
||||
Where(wt.TaskType.Eq(constants.TaskTypeUserTask)).
|
||||
Where(wt.Status.Eq(string(enums.TaskStatusCompleted))).
|
||||
Order(wt.EndedAt.Desc()).
|
||||
Limit(1).
|
||||
Scan(&last)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to query last completed node: %w", err)
|
||||
}
|
||||
if last.ID == "" || last.TaskDefKey == nil || *last.TaskDefKey == "" {
|
||||
return "", nil, nil
|
||||
}
|
||||
var rows []model.WfHiTask
|
||||
err = wt.WithContext(ctx).
|
||||
Where(wt.ProcessInstanceID.Eq(instanceID)).
|
||||
Where(wt.TaskDefKey.Eq(*last.TaskDefKey)).
|
||||
Where(wt.Status.Eq(string(enums.TaskStatusCompleted))).
|
||||
Where(wt.Assignee.IsNotNull()).
|
||||
Where(wt.Assignee.Neq("")).
|
||||
Scan(&rows)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("failed to query last node voters: %w", err)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
voters := make([]string, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
if r.Assignee == nil || seen[*r.Assignee] {
|
||||
continue
|
||||
}
|
||||
seen[*r.Assignee] = true
|
||||
voters = append(voters, *r.Assignee)
|
||||
}
|
||||
return *last.TaskDefKey, voters, nil
|
||||
}
|
||||
|
||||
// recallInternal 在已持有实例行锁的事务内执行 Recall 实际逻辑。
|
||||
// 顺序:守卫全部通过后才动数据(终止前沿 → 归档 T → 回置父任务 → 重建任务)。
|
||||
func (s *TaskServiceImpl) recallInternal(ctx context.Context, scope *InstanceScope, chain *types.RuleChain, userID, instanceID, reason string) error {
|
||||
instance, err := scope.Instances().Get(ctx, instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get process instance: %w", err)
|
||||
}
|
||||
if instance == nil {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
if u := GetUserFromCtx(ctx); u != nil && instance.TenantID != u.TenantID {
|
||||
return fmt.Errorf("%w: process instance", ErrNotFound)
|
||||
}
|
||||
if instance.Status != string(enums.InstanceStatusActive) {
|
||||
return fmt.Errorf("%w: 流程已结束,无法收回", ErrValidation)
|
||||
}
|
||||
|
||||
taskDAO := scope.Tasks()
|
||||
hiTaskDAO := scope.HiTasks()
|
||||
tasks, _, err := taskDAO.List(ctx, &dto.TaskQuery{InstanceID: &instanceID})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list instance tasks: %w", err)
|
||||
}
|
||||
|
||||
t := findRecallableCompletedTask(tasks, userID)
|
||||
if t == nil {
|
||||
return fmt.Errorf("%w: 当前没有可收回的审批记录", ErrValidation)
|
||||
}
|
||||
// completed 但 ended_at 为空的异常行无法与任何记录比先后,终止方向也会失向
|
||||
// (前沿任务不被终止 → 双停泊),直接拒绝
|
||||
if t.EndedAt == nil {
|
||||
return fmt.Errorf("%w: 当前没有可收回的审批记录", ErrValidation)
|
||||
}
|
||||
if err := evaluateRecallGuard(tasks, t, chain); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
username := ""
|
||||
if u := GetUserFromCtx(ctx); u != nil {
|
||||
username = u.UserName
|
||||
}
|
||||
|
||||
// 终止前沿任务:T 完成之后创建的全部在途任务(下一节点的待办、顺序会签
|
||||
// 的在途子任务)。created_at 用 >= 是防 datetime(3) 同毫秒截断——本节点
|
||||
// 旧任务都创建于 T 完成之前,>= 不会误伤。
|
||||
// 两段式执行:先定终止集,再豁免"同节点存活同伴的加签子任务"——同伴的
|
||||
// 任务创建于 T 之前不在终止集,其加签子任务虽 created_at 晚于 T,但归属
|
||||
// 同伴的在途审批,不随本次收回作废。
|
||||
endReason := constants.EndReasonPrefixRecall
|
||||
if reason != "" {
|
||||
endReason = fmt.Sprintf("%s:%s", constants.EndReasonPrefixRecall, reason)
|
||||
}
|
||||
termIDs := map[string]bool{}
|
||||
for _, x := range tasks {
|
||||
if x.ID == t.ID || (x.Status != string(enums.TaskStatusActive) && x.Status != string(enums.TaskStatusPending)) {
|
||||
continue
|
||||
}
|
||||
if t.EndedAt == nil || x.CreatedAt.Before(*t.EndedAt) {
|
||||
continue
|
||||
}
|
||||
termIDs[x.ID] = true
|
||||
}
|
||||
for _, x := range tasks {
|
||||
if !termIDs[x.ID] || x.ParentID == nil || *x.ParentID == "" {
|
||||
continue
|
||||
}
|
||||
for _, p := range tasks {
|
||||
if p.ID == *x.ParentID && !termIDs[p.ID] && p.TaskDefKey == t.TaskDefKey {
|
||||
delete(termIDs, x.ID)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
notifyUsers := make([]string, 0)
|
||||
for _, x := range tasks {
|
||||
if !termIDs[x.ID] {
|
||||
continue
|
||||
}
|
||||
if x.Assignee != nil && *x.Assignee != "" {
|
||||
notifyUsers = append(notifyUsers, *x.Assignee)
|
||||
}
|
||||
x.Status = string(enums.TaskStatusTerminated)
|
||||
x.EndedAt = &now
|
||||
x.EndReason = &endReason
|
||||
x.UpdatedBy = &username
|
||||
x.UpdatedAt = &now
|
||||
if err := taskDAO.Update(ctx, x); err != nil {
|
||||
return fmt.Errorf("failed to terminate frontier task: %w", err)
|
||||
}
|
||||
if herr := hiTaskDAO.Create(ctx, taskToHiTask(x)); herr != nil {
|
||||
return fmt.Errorf("failed to archive frontier task: %w", herr)
|
||||
}
|
||||
if err := taskDAO.Delete(ctx, x.ID); err != nil {
|
||||
return fmt.Errorf("failed to delete frontier task: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// T 归档:status 保持 completed、end_reason 置 recalled——审批历史据此显示
|
||||
// 「已收回」,与通过/拒绝同属 end_reason 口径
|
||||
recallMark := string(enums.EndReasonRecalled)
|
||||
t.EndReason = &recallMark
|
||||
t.UpdatedBy = &username
|
||||
t.UpdatedAt = &now
|
||||
if herr := hiTaskDAO.Create(ctx, taskToHiTask(t)); herr != nil {
|
||||
return fmt.Errorf("failed to archive recalled task: %w", herr)
|
||||
}
|
||||
if err := taskDAO.Delete(ctx, t.ID); err != nil {
|
||||
return fmt.Errorf("failed to delete recalled task: %w", err)
|
||||
}
|
||||
|
||||
// 会签/票签父任务在节点完成时被置 completed;收回后节点重新未决,回置 active。
|
||||
// ended_at/end_reason 要清成 NULL,GORM 结构体更新不写零值字段,须用 map Updates
|
||||
if t.ParentID != nil && *t.ParentID != "" {
|
||||
if p, perr := taskDAO.Get(ctx, *t.ParentID); perr == nil && p != nil &&
|
||||
p.Status == string(enums.TaskStatusCompleted) {
|
||||
updates := map[string]interface{}{
|
||||
"status": string(enums.TaskStatusActive),
|
||||
"ended_at": nil,
|
||||
"end_reason": nil,
|
||||
"updated_by": username,
|
||||
"updated_at": now,
|
||||
}
|
||||
if _, uerr := scope.Tx().WfTask.WithContext(ctx).
|
||||
Where(scope.Tx().WfTask.ID.Eq(*t.ParentID)).
|
||||
Updates(updates); uerr != nil {
|
||||
return fmt.Errorf("failed to revert parent task: %w", uerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重建收回人的待审任务;重审完成走节点既有完成判定推进,无需链路跳转
|
||||
recreated := buildRecalledTask(s.idGenerator, t, userID, username, now)
|
||||
if err := taskDAO.Create(ctx, recreated); err != nil {
|
||||
return fmt.Errorf("failed to recreate recalled task: %w", err)
|
||||
}
|
||||
|
||||
listener := s.workflowEngine.GetTaskEventListener()
|
||||
if listener != nil {
|
||||
evtTaskID := recreated.ID
|
||||
evtDefKey := recreated.TaskDefKey
|
||||
evtParentID := ""
|
||||
if recreated.ParentID != nil {
|
||||
evtParentID = *recreated.ParentID
|
||||
}
|
||||
evtName := recreated.Name
|
||||
evtProcessID := recreated.ProcessID
|
||||
evtTenantID := instance.TenantID
|
||||
evtToUsers := notifyUsers
|
||||
evtFrom := userID
|
||||
scope.AfterCommit(func() error {
|
||||
DispatchTaskEvent(listener, TaskEvent{
|
||||
Type: TaskEventRecalled,
|
||||
TaskID: evtTaskID,
|
||||
TaskDefKey: evtDefKey,
|
||||
ParentTaskID: evtParentID,
|
||||
InstanceID: instanceID,
|
||||
ProcessID: evtProcessID,
|
||||
TenantID: evtTenantID,
|
||||
TaskName: evtName,
|
||||
ToUsers: evtToUsers,
|
||||
FromUser: evtFrom,
|
||||
Reason: reason,
|
||||
Timestamp: time.Now(),
|
||||
}, ctx)
|
||||
// 重建任务沿用 assigned 事件,通知口径与新建任务一致
|
||||
DispatchTaskEvent(listener, TaskEvent{
|
||||
Type: TaskEventAssigned,
|
||||
TaskID: evtTaskID,
|
||||
TaskDefKey: evtDefKey,
|
||||
ParentTaskID: evtParentID,
|
||||
InstanceID: instanceID,
|
||||
ProcessID: evtProcessID,
|
||||
TenantID: evtTenantID,
|
||||
TaskName: evtName,
|
||||
ToUsers: []string{evtFrom},
|
||||
FromUser: evtFrom,
|
||||
Timestamp: time.Now(),
|
||||
}, ctx)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// findRecallableCompletedTask 返回 userID 最近一条已完成的 userTask 办理记录
|
||||
// (会签/票签为子任务,父任务行无办理人天然不会命中)。
|
||||
func findRecallableCompletedTask(tasks []*model.WfTask, userID string) *model.WfTask {
|
||||
var latest *model.WfTask
|
||||
for _, t := range tasks {
|
||||
if t == nil || t.TaskType != constants.TaskTypeUserTask ||
|
||||
t.Status != string(enums.TaskStatusCompleted) {
|
||||
continue
|
||||
}
|
||||
if t.Assignee == nil || *t.Assignee != userID {
|
||||
continue
|
||||
}
|
||||
if latest == nil || endedAtAfter(t, latest) {
|
||||
latest = t
|
||||
}
|
||||
}
|
||||
return latest
|
||||
}
|
||||
|
||||
// evaluateRecallGuard 收回守卫(写路径与详情权限位共用,只读不改数据):
|
||||
// 更晚办理记录 → 停泊 → 自动化路径,任一不过即拒绝。
|
||||
func evaluateRecallGuard(tasks []*model.WfTask, t *model.WfTask, chain *types.RuleChain) error {
|
||||
for _, x := range tasks {
|
||||
if x == nil || x.ID == t.ID {
|
||||
continue
|
||||
}
|
||||
if x.TaskType != constants.TaskTypeUserTask || x.Status != string(enums.TaskStatusCompleted) {
|
||||
continue
|
||||
}
|
||||
if !endedAtAfter(x, t) {
|
||||
continue
|
||||
}
|
||||
if inSameCountersignRound(t, x) {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("%w: 存在更晚的办理记录,无法收回", ErrValidation)
|
||||
}
|
||||
|
||||
parked := false
|
||||
for _, x := range tasks {
|
||||
if x != nil && x.TaskType == constants.TaskTypeUserTask &&
|
||||
(x.Status == string(enums.TaskStatusActive) || x.Status == string(enums.TaskStatusPending)) {
|
||||
// 候选池待认领同样是合法停泊(下一节点"无人办理"含未认领);
|
||||
// 自动化在途窗口无任何任务行,仍被此校验挡住
|
||||
parked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !parked {
|
||||
return fmt.Errorf("%w: 流程未停留在审批节点,无法收回", ErrValidation)
|
||||
}
|
||||
|
||||
return checkRecallPath(chain, t.TaskDefKey)
|
||||
}
|
||||
|
||||
// inSameCountersignRound 判断 x 是否与 T 同属一个会签轮次:同父的并行同侪子任务,
|
||||
// 或 T 自己的父任务行(父任务归档时间晚于子任务,完成时间不代表有人办理)。
|
||||
func inSameCountersignRound(t, x *model.WfTask) bool {
|
||||
if t.ParentID == nil || *t.ParentID == "" {
|
||||
return false
|
||||
}
|
||||
if x.ID == *t.ParentID {
|
||||
return true
|
||||
}
|
||||
return x.ParentID != nil && *x.ParentID == *t.ParentID
|
||||
}
|
||||
|
||||
func endedAtAfter(a, b *model.WfTask) bool {
|
||||
if a.EndedAt == nil {
|
||||
return false
|
||||
}
|
||||
if b.EndedAt == nil {
|
||||
return true
|
||||
}
|
||||
return a.EndedAt.After(*b.EndedAt)
|
||||
}
|
||||
|
||||
// checkRecallPath 从 T 的节点沿 Success 边向前遍历链定义,T 完成后链路已推进,
|
||||
// 停泊点之前若途经自动化节点说明机器动作已发生,收回会造成副作用重放。
|
||||
// userTask/end 截断;路由与抄送穿越;未知类型 fail-closed 拒绝。
|
||||
func checkRecallPath(chain *types.RuleChain, fromDefKey string) error {
|
||||
if chain == nil || len(chain.Metadata.Nodes) == 0 {
|
||||
return fmt.Errorf("%w: 流程定义不可用,无法收回", ErrValidation)
|
||||
}
|
||||
nodeByID := make(map[string]*types.RuleNode, len(chain.Metadata.Nodes))
|
||||
for _, n := range chain.Metadata.Nodes {
|
||||
nodeByID[n.Id] = n
|
||||
}
|
||||
if _, ok := nodeByID[fromDefKey]; !ok {
|
||||
return fmt.Errorf("%w: 流程定义不可用,无法收回", ErrValidation)
|
||||
}
|
||||
successors := make(map[string][]string)
|
||||
for _, conn := range chain.Metadata.Connections {
|
||||
if conn.Type == types.Success || conn.Type == "" {
|
||||
successors[conn.FromId] = append(successors[conn.FromId], conn.ToId)
|
||||
}
|
||||
}
|
||||
|
||||
visited := map[string]bool{fromDefKey: true}
|
||||
queue := make([]string, 0, len(successors[fromDefKey]))
|
||||
for _, id := range successors[fromDefKey] {
|
||||
if !visited[id] {
|
||||
visited[id] = true
|
||||
queue = append(queue, id)
|
||||
}
|
||||
}
|
||||
for len(queue) > 0 {
|
||||
id := queue[0]
|
||||
queue = queue[1:]
|
||||
node, ok := nodeByID[id]
|
||||
if !ok {
|
||||
// 连接指向不存在的节点属畸形定义,fail-closed
|
||||
return fmt.Errorf("%w: 流程定义不可用,无法收回", ErrValidation)
|
||||
}
|
||||
switch {
|
||||
case node.Type == constants.NodeTypeUserTask || node.Type == constants.NodeTypeEnd:
|
||||
// 停泊点或终点:流程停在人工任务上,该路径安全
|
||||
case recallTransparentNodeTypes[node.Type]:
|
||||
for _, next := range successors[id] {
|
||||
if !visited[next] {
|
||||
visited[next] = true
|
||||
queue = append(queue, next)
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("%w: 审批之后存在自动化节点,无法收回", ErrValidation)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildRecalledTask 从 T 的快照重建收回人的待审任务。到期时间沿用 T(与加签
|
||||
// 继承同口径);variables 剔除 approved/comment 约定键——Complete 会消费它们,
|
||||
// 残留会让重建任务带着旧投票结果被静默自动通过;_sequentialAssignees 缓存
|
||||
// 保留,顺序会签推进依赖。
|
||||
func buildRecalledTask(gen IDGenerator, t *model.WfTask, userID, username string, now time.Time) *model.WfTask {
|
||||
assignee := userID
|
||||
return &model.WfTask{
|
||||
ID: gen.GenerateTaskID(),
|
||||
ProcessInstanceID: t.ProcessInstanceID,
|
||||
ProcessID: t.ProcessID,
|
||||
ParentID: t.ParentID,
|
||||
TaskDefKey: t.TaskDefKey,
|
||||
Name: t.Name,
|
||||
Description: t.Description,
|
||||
FormKey: t.FormKey,
|
||||
TaskType: t.TaskType,
|
||||
Status: string(enums.TaskStatusActive),
|
||||
Assignee: &assignee,
|
||||
Owner: t.Owner,
|
||||
Priority: t.Priority,
|
||||
DueDate: t.DueDate,
|
||||
Variables: stripApprovalResultKeys(t.Variables),
|
||||
SequenceOrder: t.SequenceOrder,
|
||||
ApprovalType: t.ApprovalType,
|
||||
ApprovalRule: t.ApprovalRule,
|
||||
TenantID: t.TenantID,
|
||||
CreatedBy: username,
|
||||
CreatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
func stripApprovalResultKeys(vars *string) *string {
|
||||
m, err := ParseVariablesJSON(vars)
|
||||
// 解析失败宁可丢掉全部变量(顺序缓存可由候选人配置重解析兜底),
|
||||
// 也不能原样放行——残留 approved=true 会让重建任务被旧投票静默自动通过
|
||||
if err != nil || len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
changed := false
|
||||
for _, key := range []string{constants.VarsApproved, constants.VarsComment} {
|
||||
if _, ok := m[key]; ok {
|
||||
delete(m, key)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return vars
|
||||
}
|
||||
if len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
out, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
s := string(out)
|
||||
return &s
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
package service
|
||||
|
||||
// Tests for task_service_recall.go: 守卫矩阵 + 重建任务字段 + 前沿任务终止。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/rulego/gflow-engine/dao"
|
||||
"github.com/rulego/gflow-engine/model"
|
||||
"github.com/rulego/gflow-engine/query"
|
||||
"github.com/rulego/gflow-engine/types/constants"
|
||||
"github.com/rulego/gflow-engine/types/enums"
|
||||
"github.com/rulego/rulego/api/types"
|
||||
)
|
||||
|
||||
// ---- 夹具 ----
|
||||
|
||||
// recallEngineDouble 在 testEngineDouble 之上注入流程定义与实例读取,
|
||||
// 供流程级开关与路径守卫解析(Recall 在锁外经 runtime 读实例拿 processID)。
|
||||
type recallEngineDouble struct {
|
||||
testEngineDouble
|
||||
proc ProcessService
|
||||
q *query.Query
|
||||
internal *recallInternalDouble
|
||||
}
|
||||
|
||||
func (e *recallEngineDouble) GetProcessService() ProcessService { return e.proc }
|
||||
|
||||
func (e *recallEngineDouble) GetRuntimeService() RuntimeService {
|
||||
return &recallRuntimeDouble{testRuntimeDouble: testRuntimeDouble{}, q: e.q}
|
||||
}
|
||||
|
||||
func (e *recallEngineDouble) GetRuntimeServiceInternal() RuntimeServiceInternal { return e.internal }
|
||||
|
||||
// recallInternalDouble 补齐内部接口,记录 ExecuteNext 重入节点供断言
|
||||
type recallInternalDouble struct {
|
||||
testRuntimeDouble
|
||||
execNextNode string
|
||||
}
|
||||
|
||||
func (d *recallInternalDouble) GetExecution(context.Context, string) (types.RuleEngine, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (d *recallInternalDouble) PreloadChain(string, string, string) error { return nil }
|
||||
func (d *recallInternalDouble) EvictStaleChain(context.Context, string, string) {
|
||||
}
|
||||
func (d *recallInternalDouble) ResolveSubProcessTarget(string, string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
func (d *recallInternalDouble) StartSubProcessInstance(context.Context, string, string, string, map[string]interface{}) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
func (d *recallInternalDouble) SubProcessChildState(context.Context, string) (bool, bool, error) {
|
||||
return false, false, nil
|
||||
}
|
||||
func (d *recallInternalDouble) SubProcessChildTerminated(context.Context, string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
func (d *recallInternalDouble) ExecuteNext(_ context.Context, _, node string, _ map[string]interface{}) error {
|
||||
d.execNextNode = node
|
||||
return nil
|
||||
}
|
||||
|
||||
type recallRuntimeDouble struct {
|
||||
testRuntimeDouble
|
||||
q *query.Query
|
||||
}
|
||||
|
||||
func (r *recallRuntimeDouble) GetProcessInstance(_ context.Context, _ Actor, id string) (*model.WfInstance, error) {
|
||||
// 与生产 GetProcessInstance 同口径:活表优先,历史表回退
|
||||
if inst, err := r.q.WfInstance.WithContext(context.Background()).Where(r.q.WfInstance.ID.Eq(id)).First(); err == nil {
|
||||
return inst, nil
|
||||
}
|
||||
return dao.NewHiInstanceDAOWithQuery(r.q).Get(context.Background(), id)
|
||||
}
|
||||
|
||||
type recallProcessFake struct {
|
||||
noopSecFixProcessService
|
||||
def string
|
||||
}
|
||||
|
||||
func (f recallProcessFake) Get(context.Context, string) (*model.WfProcess, error) {
|
||||
return &model.WfProcess{DefinitionJSON: f.def}, nil
|
||||
}
|
||||
|
||||
func recallNode(id, typ string) string { return fmt.Sprintf(`{"id":%q,"type":%q}`, id, typ) }
|
||||
func recallConn(from, to string) string {
|
||||
return fmt.Sprintf(`{"fromId":%q,"toId":%q,"type":"Success"}`, from, to)
|
||||
}
|
||||
|
||||
func recallDefinition(recallOn bool, nodes, conns []string) string {
|
||||
on := "false"
|
||||
if recallOn {
|
||||
on = "true"
|
||||
}
|
||||
join := func(items []string) string {
|
||||
out := ""
|
||||
for i, s := range items {
|
||||
if i > 0 {
|
||||
out += ","
|
||||
}
|
||||
out += s
|
||||
}
|
||||
return out
|
||||
}
|
||||
return fmt.Sprintf(`{"ruleChain":{"additionalInfo":{"actionPermissions":{"recall":%s}}},"metadata":{"nodes":[%s],"connections":[%s]}}`,
|
||||
on, join(nodes), join(conns))
|
||||
}
|
||||
|
||||
func newRecallSvc(q *query.Query, def string, listener TaskEventListener) (*TaskServiceImpl, *recallEngineDouble) {
|
||||
eng := &recallEngineDouble{
|
||||
testEngineDouble: testEngineDouble{listener: listener},
|
||||
proc: recallProcessFake{def: def},
|
||||
q: q,
|
||||
internal: &recallInternalDouble{},
|
||||
}
|
||||
svc := &TaskServiceImpl{
|
||||
taskDAO: dao.NewTaskDAOWithQuery(q),
|
||||
hiTaskDAO: dao.NewHiTaskDAOWithQuery(q),
|
||||
workflowEngine: eng,
|
||||
idGenerator: DefaultIDGenerator,
|
||||
}
|
||||
return svc, eng
|
||||
}
|
||||
|
||||
func recallSeedInstance(t *testing.T, q *query.Query, id, status string) {
|
||||
t.Helper()
|
||||
require.NoError(t, q.WfInstance.Create(&model.WfInstance{
|
||||
ID: id,
|
||||
ProcessID: "proc-1",
|
||||
Name: "recall-test",
|
||||
Status: status,
|
||||
TenantID: "t1",
|
||||
CreatedBy: "system",
|
||||
StartUserID: "starter",
|
||||
CreatedAt: time.Now(),
|
||||
}))
|
||||
}
|
||||
|
||||
func recallSeedTask(t *testing.T, q *query.Query, id, instID, defKey, typ, status, assignee string, createdAt, endedAt time.Time, vars string) {
|
||||
t.Helper()
|
||||
task := &model.WfTask{
|
||||
ID: id,
|
||||
ProcessInstanceID: secFixStrPtr(instID),
|
||||
ProcessID: "proc-1",
|
||||
TaskDefKey: defKey,
|
||||
Name: defKey,
|
||||
TaskType: typ,
|
||||
Status: status,
|
||||
TenantID: "t1",
|
||||
CreatedBy: "system",
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
if assignee != "" {
|
||||
task.Assignee = secFixStrPtr(assignee)
|
||||
}
|
||||
if !endedAt.IsZero() {
|
||||
task.EndedAt = &endedAt
|
||||
task.EndReason = secFixStrPtr(string(enums.ApprovalResultApproved))
|
||||
}
|
||||
if vars != "" {
|
||||
task.Variables = secFixStrPtr(vars)
|
||||
}
|
||||
require.NoError(t, q.WfTask.Create(task))
|
||||
}
|
||||
|
||||
func recallTaskByID(t *testing.T, q *query.Query, id string) *model.WfTask {
|
||||
t.Helper()
|
||||
row, err := q.WfTask.WithContext(context.Background()).Where(q.WfTask.ID.Eq(id)).First()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
// ---- 守卫矩阵 ----
|
||||
|
||||
// 单人审批:A(甲) 通过 → B(乙) 待审,甲收回后乙待办作废、甲重建待审、旧投票变量剔除。
|
||||
func TestRecall_SingleApproval_RecreatesTask(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-1", string(enums.InstanceStatusActive))
|
||||
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-1", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), `{"_sequentialAssignees":["jia","yi"],"approved":true,"comment":"ok"}`)
|
||||
recallSeedTask(t, q, "t-b", "inst-1", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
|
||||
evtCh := make(chan TaskEvent, 8)
|
||||
svc, _ := newRecallSvc(q, def, func(_ context.Context, evt TaskEvent) { evtCh <- evt })
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-1", "填错了"))
|
||||
|
||||
// 前沿任务终止并归档
|
||||
require.Nil(t, recallTaskByID(t, q, "t-b"), "B 待办应从运行表删除")
|
||||
require.EqualValues(t, 1, countHi(t, q, "t-b"), "B 待办应归档 hi 表")
|
||||
// 原投票归档为 recalled
|
||||
require.Nil(t, recallTaskByID(t, q, "t-a"), "原任务应从运行表删除")
|
||||
require.EqualValues(t, 1, countHi(t, q, "t-a"), "原任务应归档 hi 表")
|
||||
// 重建任务
|
||||
recreated := q.WfTask.WithContext(ctx)
|
||||
rows, err := recreated.Where(q.WfTask.ProcessInstanceID.Eq("inst-1")).Find()
|
||||
require.NoError(t, err)
|
||||
require.Len(t, rows, 1)
|
||||
nt := rows[0]
|
||||
require.Equal(t, "a", nt.TaskDefKey)
|
||||
require.NotNil(t, nt.Assignee)
|
||||
require.Equal(t, "jia", *nt.Assignee)
|
||||
require.Equal(t, string(enums.TaskStatusActive), nt.Status)
|
||||
require.Nil(t, nt.EndedAt)
|
||||
// 变量:保留顺序缓存,剔除旧投票结果
|
||||
require.NotNil(t, nt.Variables)
|
||||
var vars map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal([]byte(*nt.Variables), &vars))
|
||||
require.Contains(t, vars, constants.KeySequentialAssignees)
|
||||
require.NotContains(t, vars, constants.VarsApproved)
|
||||
require.NotContains(t, vars, constants.VarsComment)
|
||||
|
||||
// 事件:recalled(ToUsers=乙)+ assigned(重建任务)
|
||||
done := time.After(3 * time.Second)
|
||||
var gotRecalled, gotAssigned bool
|
||||
for !gotRecalled || !gotAssigned {
|
||||
select {
|
||||
case evt := <-evtCh:
|
||||
switch evt.Type {
|
||||
case TaskEventRecalled:
|
||||
gotRecalled = true
|
||||
require.Equal(t, nt.ID, evt.TaskID)
|
||||
require.Contains(t, evt.ToUsers, "yi")
|
||||
case TaskEventAssigned:
|
||||
gotAssigned = true
|
||||
require.Equal(t, []string{"jia"}, evt.ToUsers)
|
||||
}
|
||||
case <-done:
|
||||
t.Fatalf("事件未派发齐: recalled=%v assigned=%v", gotRecalled, gotAssigned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func countHi(t *testing.T, q *query.Query, id string) int64 {
|
||||
t.Helper()
|
||||
n, err := q.WfHiTask.WithContext(context.Background()).Where(q.WfHiTask.ID.Eq(id)).Count()
|
||||
require.NoError(t, err)
|
||||
return n
|
||||
}
|
||||
|
||||
// 顺序会签:只有最后一位已签署者能收回;中间签署者被更晚办理记录挡住。
|
||||
func TestRecall_Sequential_OnlyLastSigner(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-2", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-jia", "inst-2", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-yi", "inst-2", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"yi", base.Add(2*time.Minute), base.Add(3*time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-2", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"bing", base.Add(4*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-2", "")
|
||||
require.Error(t, err, "中间签署者收回必须拒绝")
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
|
||||
require.NoError(t, svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "yi", TenantID: "t1", UserName: "乙"}),
|
||||
Actor{UserID: "yi", TenantID: "t1"}, "inst-2", ""), "最后一位签署者可收回")
|
||||
require.Nil(t, recallTaskByID(t, q, "t-b"), "B 待办应随收回终止")
|
||||
}
|
||||
|
||||
// 顺序会签在途:最后一位未签时,最后一位已签署者收回会终止在途子任务。
|
||||
func TestRecall_Sequential_MidFlightRecyclesInFlight(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true, []string{recallNode("a", "userTask")}, nil)
|
||||
recallSeedInstance(t, q, "inst-3", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-jia", "inst-3", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-yi", "inst-3", "a", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-3", ""))
|
||||
require.Nil(t, recallTaskByID(t, q, "t-yi"), "在途后续子任务应随收回终止")
|
||||
rows, _ := q.WfTask.WithContext(ctx).Where(q.WfTask.ProcessInstanceID.Eq("inst-3")).Find()
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, "jia", *rows[0].Assignee)
|
||||
}
|
||||
|
||||
// 会签:同父同侪的更晚投票不阻断收回,父任务行从 completed 回置 active。
|
||||
func TestRecall_Countersign_PeerExemptAndParentRevert(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-4", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-parent", "inst-4", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"", base, base.Add(3*time.Minute), "")
|
||||
recallSeedTask(t, q, "t-c1", "inst-4", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
if _, err := q.WfTask.WithContext(ctx).Where(q.WfTask.ID.Eq("t-c1")).
|
||||
UpdateSimple(q.WfTask.ParentID.Value("t-parent")); err != nil {
|
||||
t.Fatalf("set parent: %v", err)
|
||||
}
|
||||
recallSeedTask(t, q, "t-c2", "inst-4", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"yi", base, base.Add(2*time.Minute), "")
|
||||
if _, err := q.WfTask.WithContext(ctx).Where(q.WfTask.ID.Eq("t-c2")).
|
||||
UpdateSimple(q.WfTask.ParentID.Value("t-parent")); err != nil {
|
||||
t.Fatalf("set parent: %v", err)
|
||||
}
|
||||
recallSeedTask(t, q, "t-b", "inst-4", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"bing", base.Add(4*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-4", ""))
|
||||
require.Nil(t, recallTaskByID(t, q, "t-c1"))
|
||||
parent := recallTaskByID(t, q, "t-parent")
|
||||
require.NotNil(t, parent)
|
||||
require.Equal(t, string(enums.TaskStatusActive), parent.Status, "父任务应回置 active")
|
||||
require.Nil(t, parent.EndedAt)
|
||||
rows, _ := q.WfTask.WithContext(ctx).Where(q.WfTask.ParentID.Eq("t-parent")).Find()
|
||||
require.Len(t, rows, 2, "父任务下应剩同侪乙的票 + 重建的甲的子任务")
|
||||
for _, r := range rows {
|
||||
if r.Status == string(enums.TaskStatusActive) {
|
||||
require.Equal(t, "jia", *r.Assignee, "重建的应是自己那票的子任务")
|
||||
}
|
||||
}
|
||||
// 同侪乙的票保留
|
||||
require.NotNil(t, recallTaskByID(t, q, "t-c2"))
|
||||
}
|
||||
|
||||
// 下一节点已办理(存在更晚 completed 记录)→ 拒绝。
|
||||
func TestRecall_Blocked_LaterCompletion(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-5", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-5", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-5", "b", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"yi", base.Add(2*time.Minute), base.Add(3*time.Minute), "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-5", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
}
|
||||
|
||||
// 推进路径含自动化节点(A→serviceTask→B)→ 拒绝。
|
||||
func TestRecall_Blocked_AutomationPath(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("s", "serviceTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "s"), recallConn("s", "b")})
|
||||
recallSeedInstance(t, q, "inst-6", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-6", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-6", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-6", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
require.Contains(t, err.Error(), "自动化")
|
||||
}
|
||||
|
||||
// 无停泊任务(自动化在途执行窗口)→ 拒绝。
|
||||
func TestRecall_Blocked_NoParked(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("s", "serviceTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "s"), recallConn("s", "b")})
|
||||
recallSeedInstance(t, q, "inst-7", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-7", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-7", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
}
|
||||
|
||||
// 流程未开启收回开关 → 403 口径拒绝。
|
||||
func TestRecall_Blocked_SwitchOff(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(false,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-8", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-8", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-8", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-8", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrPermissionDenied))
|
||||
}
|
||||
|
||||
// 非办理人 / 重复收回 → 无可收回记录;实例终态 → 拒绝。
|
||||
func TestRecall_Blocked_NonAssignee_Duplicate_Terminal(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-9", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-9", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-9", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
// 乙没有自己已通过的记录 → E1
|
||||
err := svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "yi", TenantID: "t1", UserName: "乙"}),
|
||||
Actor{UserID: "yi", TenantID: "t1"}, "inst-9", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
|
||||
// 甲收回成功后再次收回 → E1(幂等拒绝)
|
||||
jiaCtx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
require.NoError(t, svc.Recall(jiaCtx, Actor{UserID: "jia", TenantID: "t1"}, "inst-9", ""))
|
||||
err = svc.Recall(jiaCtx, Actor{UserID: "jia", TenantID: "t1"}, "inst-9", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
|
||||
// 非完成终态(已终止)→ 已结束,无法收回
|
||||
recallSeedInstance(t, q, "inst-10", string(enums.InstanceStatusTerminated))
|
||||
recallSeedTask(t, q, "t-a2", "inst-10", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
err = svc.Recall(jiaCtx, Actor{UserID: "jia", TenantID: "t1"}, "inst-10", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
require.Contains(t, err.Error(), "已结束")
|
||||
}
|
||||
|
||||
// 路由网关与抄送节点可穿越:A→switch→cc→B 不阻断收回。
|
||||
func TestRecall_PathTransparentThroughRoutersAndCC(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("sw", "switch"), recallNode("cc", "ccTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "sw"), recallConn("sw", "cc"), recallConn("cc", "b")})
|
||||
recallSeedInstance(t, q, "inst-cc", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-cc", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-cc", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-cc", ""))
|
||||
}
|
||||
|
||||
// 未知节点类型 fail-closed 拒绝。
|
||||
func TestRecall_Blocked_UnknownNodeType(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("x", "mysteryNode"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "x"), recallConn("x", "b")})
|
||||
recallSeedInstance(t, q, "inst-unk", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-unk", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-unk", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-unk", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
}
|
||||
|
||||
// 重建任务沿用原任务属性字段;归档口径:本人原票 end_reason=recalled,前沿任务带审批人收回前缀。
|
||||
func TestRecall_RebuildCarriesFields_AndArchiveReasons(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-fld", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
due := base.Add(48 * time.Hour)
|
||||
require.NoError(t, q.WfTask.Create(&model.WfTask{
|
||||
ID: "t-a",
|
||||
ProcessInstanceID: secFixStrPtr("inst-fld"),
|
||||
ProcessID: "proc-1",
|
||||
TaskDefKey: "a",
|
||||
Name: "甲节点",
|
||||
TaskType: constants.TaskTypeUserTask,
|
||||
Status: string(enums.TaskStatusCompleted),
|
||||
Assignee: secFixStrPtr("jia"),
|
||||
DueDate: &due,
|
||||
SequenceOrder: 7,
|
||||
ApprovalType: string(enums.ApprovalTypeSingle),
|
||||
FormKey: secFixStrPtr("frm-1"),
|
||||
Description: secFixStrPtr("节点说明"),
|
||||
TenantID: "t1",
|
||||
CreatedBy: "system",
|
||||
CreatedAt: base,
|
||||
EndedAt: func() *time.Time { t2 := base.Add(time.Minute); return &t2 }(),
|
||||
EndReason: secFixStrPtr(string(enums.ApprovalResultApproved)),
|
||||
}))
|
||||
recallSeedTask(t, q, "t-b", "inst-fld", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-fld", ""))
|
||||
|
||||
rows, _ := q.WfTask.WithContext(ctx).Where(q.WfTask.ProcessInstanceID.Eq("inst-fld")).Find()
|
||||
require.Len(t, rows, 1)
|
||||
nt := rows[0]
|
||||
require.NotNil(t, nt.FormKey)
|
||||
require.Equal(t, "frm-1", *nt.FormKey)
|
||||
require.NotNil(t, nt.DueDate)
|
||||
require.True(t, nt.DueDate.Equal(due), "到期时间应沿用原任务")
|
||||
require.EqualValues(t, 7, nt.SequenceOrder)
|
||||
require.Equal(t, string(enums.ApprovalTypeSingle), nt.ApprovalType)
|
||||
require.NotNil(t, nt.Description)
|
||||
require.Equal(t, "节点说明", *nt.Description)
|
||||
|
||||
hiA, err := q.WfHiTask.WithContext(ctx).Where(q.WfHiTask.ID.Eq("t-a")).First()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "recalled", *hiA.EndReason)
|
||||
hiB, err := q.WfHiTask.WithContext(ctx).Where(q.WfHiTask.ID.Eq("t-b")).First()
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, *hiB.EndReason, "审批人收回")
|
||||
}
|
||||
|
||||
// 候选池待认领也是合法停泊:下一节点 pending 任务不阻断收回。
|
||||
func TestRecall_ParkedByCandidatePool(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedInstance(t, q, "inst-pool", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-pool", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
// 候选池任务:pending、无 assignee
|
||||
recallSeedTask(t, q, "t-b", "inst-pool", "b", constants.TaskTypeUserTask, string(enums.TaskStatusPending),
|
||||
"", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-pool", ""))
|
||||
require.Nil(t, recallTaskByID(t, q, "t-b"), "候选池待办应随收回作废")
|
||||
}
|
||||
|
||||
// 同节点存活同伴的加签子任务不随收回作废:并行会签中途,甲收回自己的票,
|
||||
// 乙的在途任务与其加签人丙的子任务都保留。
|
||||
func TestRecall_SweepSparesPeerAddSignChildren(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true, []string{recallNode("a", "userTask")}, nil)
|
||||
recallSeedInstance(t, q, "inst-sign", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-parent", "inst-sign", "a", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"", base, time.Time{}, "")
|
||||
recallSeedTask(t, q, "t-c1", "inst-sign", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
if _, err := q.WfTask.WithContext(ctx).Where(q.WfTask.ID.Eq("t-c1")).
|
||||
UpdateSimple(q.WfTask.ParentID.Value("t-parent")); err != nil {
|
||||
t.Fatalf("set parent: %v", err)
|
||||
}
|
||||
recallSeedTask(t, q, "t-c2", "inst-sign", "a", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base, time.Time{}, "")
|
||||
if _, err := q.WfTask.WithContext(ctx).Where(q.WfTask.ID.Eq("t-c2")).
|
||||
UpdateSimple(q.WfTask.ParentID.Value("t-parent")); err != nil {
|
||||
t.Fatalf("set parent: %v", err)
|
||||
}
|
||||
// 乙的加签人丙:任务创建于甲完成之后(晚于 T.ended_at)
|
||||
recallSeedTask(t, q, "t-s1", "inst-sign", "a", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"bing", base.Add(5*time.Minute), time.Time{}, "")
|
||||
if _, err := q.WfTask.WithContext(ctx).Where(q.WfTask.ID.Eq("t-s1")).
|
||||
UpdateSimple(q.WfTask.ParentID.Value("t-c2")); err != nil {
|
||||
t.Fatalf("set parent: %v", err)
|
||||
}
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-sign", ""))
|
||||
|
||||
// 同伴乙与其加签人丙都保留
|
||||
require.NotNil(t, recallTaskByID(t, q, "t-c2"), "同伴在途任务应保留")
|
||||
require.NotNil(t, recallTaskByID(t, q, "t-s1"), "存活同伴的加签子任务不应被清扫")
|
||||
// 甲的票归档重建
|
||||
require.Nil(t, recallTaskByID(t, q, "t-c1"))
|
||||
rows, _ := q.WfTask.WithContext(ctx).Where(q.WfTask.ParentID.Eq("t-parent")).Find()
|
||||
require.Len(t, rows, 2, "父任务下应为 重建的甲票与乙票两行")
|
||||
}
|
||||
|
||||
// 全节点类型分类表驱动:阻断集(自动化/子流程/延时,机器动作已发生)必须拒,
|
||||
// 穿越集(路由/fork/join/抄送/起点,无业务副作用)必须放行。
|
||||
// 未归类的未来新增节点类型落入 default 被 fail-closed 拒绝——新增类型时须
|
||||
// 显式归入穿越集并在此表补行。
|
||||
func TestRecall_NodeTypeClassification(t *testing.T) {
|
||||
blocking := []string{"serviceTask", "httpCall", "automation", "aiAgent", "delay", "subProcess", "startProcess"}
|
||||
transparent := []string{"switch", "jsSwitch", "msgTypeSwitch", "inclusive", "condition", "routeGateway", "fork", "join", "ccTask", "start", "startTask"}
|
||||
|
||||
newFixture := func(t *testing.T, midType string) (*query.Query, context.Context, *TaskServiceImpl, string) {
|
||||
t.Helper()
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("m", midType), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "m"), recallConn("m", "b")})
|
||||
recallSeedInstance(t, q, "inst-cls", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-cls", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-cls", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
return q, ctx, svc, "inst-cls"
|
||||
}
|
||||
|
||||
for _, typ := range blocking {
|
||||
t.Run("阻断/"+typ, func(t *testing.T) {
|
||||
q, ctx, svc, inst := newFixture(t, typ)
|
||||
err := svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, inst, "")
|
||||
require.Error(t, err, "%s 应阻断收回", typ)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
require.NotNil(t, recallTaskByID(t, q, "t-a"), "阻断时不得动数据")
|
||||
})
|
||||
}
|
||||
for _, typ := range transparent {
|
||||
t.Run("穿越/"+typ, func(t *testing.T) {
|
||||
_, ctx, svc, inst := newFixture(t, typ)
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, inst, ""), "%s 应穿越", typ)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 终态收回(已完成实例窗口期内发起人/管理员整单重开) ----
|
||||
|
||||
// recallSeedHiInstance 造已完成归档实例(终端收回的前置形态:活表无行)。
|
||||
func recallSeedHiInstance(t *testing.T, q *query.Query, id, status string, endedAt time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, q.WfHiInstance.Create(&model.WfHiInstance{
|
||||
ID: id,
|
||||
ProcessID: "proc-1",
|
||||
Name: "recall-term",
|
||||
Status: status,
|
||||
TenantID: "t1",
|
||||
CreatedBy: "system",
|
||||
StartUserID: "starter",
|
||||
CreatedAt: endedAt.Add(-time.Hour),
|
||||
EndedAt: &endedAt,
|
||||
}))
|
||||
}
|
||||
|
||||
// recallSeedHiTask 造归档任务行(终态收回的末节点判定与投票人来源)。
|
||||
func recallSeedHiTask(t *testing.T, q *query.Query, id, instID, defKey, assignee string, endedAt time.Time) {
|
||||
t.Helper()
|
||||
row := &model.WfHiTask{
|
||||
ID: id,
|
||||
ProcessInstanceID: secFixStrPtr(instID),
|
||||
ProcessID: "proc-1",
|
||||
TaskDefKey: &defKey,
|
||||
TaskType: constants.TaskTypeUserTask,
|
||||
Status: string(enums.TaskStatusCompleted),
|
||||
TenantID: "t1",
|
||||
CreatedAt: endedAt.Add(-time.Minute),
|
||||
EndedAt: &endedAt,
|
||||
}
|
||||
if assignee != "" {
|
||||
row.Assignee = secFixStrPtr(assignee)
|
||||
}
|
||||
require.NoError(t, q.WfHiTask.Create(row))
|
||||
}
|
||||
|
||||
// 发起人在窗口期内收回已完成实例:实例复活为运行中、归档行移除。
|
||||
func TestRecallCompleted_ByStarterReopensInstance(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
recallSeedHiInstance(t, q, "inst-term", string(enums.InstanceStatusCompleted), time.Now().Add(-24*time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-a", "inst-term", "a", "jia", time.Now().Add(-23*time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-b", "inst-term", "b", "yi", time.Now().Add(-22*time.Hour))
|
||||
svc, eng := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "starter", TenantID: "t1", UserName: "发起人"}),
|
||||
Actor{UserID: "starter", TenantID: "t1"}, "inst-term", "批错了,整单重开"))
|
||||
|
||||
revived, err := q.WfInstance.WithContext(context.Background()).Where(q.WfInstance.ID.Eq("inst-term")).First()
|
||||
require.NoError(t, err, "实例应回插运行表")
|
||||
require.Equal(t, string(enums.InstanceStatusActive), revived.Status)
|
||||
require.Nil(t, revived.EndedAt)
|
||||
hiGone, err := q.WfHiInstance.WithContext(context.Background()).Where(q.WfHiInstance.ID.Eq("inst-term")).Count()
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, hiGone, "归档行应移除")
|
||||
require.Equal(t, "b", eng.internal.execNextNode, "应重入末节点 b")
|
||||
}
|
||||
|
||||
func TestRecallCompleted_Guards(t *testing.T) {
|
||||
def := recallDefinition(true,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
defOff := recallDefinition(false,
|
||||
[]string{recallNode("a", "userTask"), recallNode("b", "userTask")},
|
||||
[]string{recallConn("a", "b")})
|
||||
|
||||
t.Run("非发起人且非管理员", func(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
recallSeedHiInstance(t, q, "inst-g1", string(enums.InstanceStatusCompleted), time.Now().Add(-time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-g1", "inst-g1", "b", "yi", time.Now().Add(-30*time.Minute))
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
err := svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"}),
|
||||
Actor{UserID: "jia", TenantID: "t1"}, "inst-g1", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrPermissionDenied))
|
||||
require.Contains(t, err.Error(), "发起人或管理员")
|
||||
})
|
||||
|
||||
t.Run("超过窗口", func(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
recallSeedHiInstance(t, q, "inst-g2", string(enums.InstanceStatusCompleted), time.Now().Add(-8*24*time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-g2", "inst-g2", "b", "yi", time.Now().Add(-8*24*time.Hour))
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
err := svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "starter", TenantID: "t1", UserName: "发起人"}),
|
||||
Actor{UserID: "starter", TenantID: "t1"}, "inst-g2", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrValidation))
|
||||
require.Contains(t, err.Error(), "窗口")
|
||||
})
|
||||
|
||||
t.Run("流程未开启", func(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
recallSeedHiInstance(t, q, "inst-g3", string(enums.InstanceStatusCompleted), time.Now().Add(-time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-g3", "inst-g3", "b", "yi", time.Now().Add(-30*time.Minute))
|
||||
svc, _ := newRecallSvc(q, defOff, nil)
|
||||
err := svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "starter", TenantID: "t1", UserName: "发起人"}),
|
||||
Actor{UserID: "starter", TenantID: "t1"}, "inst-g3", "")
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, ErrPermissionDenied))
|
||||
})
|
||||
|
||||
t.Run("管理员可收", func(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
recallSeedHiInstance(t, q, "inst-g4", string(enums.InstanceStatusCompleted), time.Now().Add(-time.Hour))
|
||||
recallSeedHiTask(t, q, "ht-g4", "inst-g4", "b", "yi", time.Now().Add(-30*time.Minute))
|
||||
svc, eng := newRecallSvc(q, def, nil)
|
||||
require.NoError(t, svc.Recall(
|
||||
SetUserToCtx(context.Background(), &Actor{UserID: "admin", TenantID: "t1", UserName: "管理员", WorkflowAdmin: true}),
|
||||
Actor{UserID: "admin", TenantID: "t1", WorkflowAdmin: true}, "inst-g4", ""))
|
||||
revived, err := q.WfInstance.WithContext(context.Background()).Where(q.WfInstance.ID.Eq("inst-g4")).First()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(enums.InstanceStatusActive), revived.Status)
|
||||
require.Equal(t, "b", eng.internal.execNextNode, "管理员收回同样重入末节点")
|
||||
})
|
||||
}
|
||||
|
||||
// recallWindowDays 配置解析:流程级覆盖生效,非法值回落默认 7 天。
|
||||
func TestRecallWindowDays(t *testing.T) {
|
||||
cases := []struct {
|
||||
ap map[string]interface{}
|
||||
want int
|
||||
}{
|
||||
{nil, 7},
|
||||
{map[string]interface{}{"recallWindowDays": float64(30)}, 30},
|
||||
{map[string]interface{}{"recallWindowDays": float64(1)}, 1},
|
||||
{map[string]interface{}{"recallWindowDays": float64(0)}, 7},
|
||||
{map[string]interface{}{"recallWindowDays": float64(-1)}, 7},
|
||||
{map[string]interface{}{"recallWindowDays": float64(400)}, 7},
|
||||
{map[string]interface{}{"recallWindowDays": "7"}, 7},
|
||||
}
|
||||
for _, c := range cases {
|
||||
require.Equal(t, c.want, recallWindowDays(c.ap), "ap=%v", c.ap)
|
||||
}
|
||||
}
|
||||
|
||||
// 开关缺省=开启(opt-out 语义):流程未配置 actionPermissions 时收回可用。
|
||||
func TestRecall_DefaultOnWithoutSwitch(t *testing.T) {
|
||||
q := secFixDB(t)
|
||||
ctx := SetUserToCtx(context.Background(), &Actor{UserID: "jia", TenantID: "t1", UserName: "甲"})
|
||||
// 无 actionPermissions 键的流程定义
|
||||
def := fmt.Sprintf(`{"ruleChain":{"additionalInfo":{"processType":"main"}},"metadata":{"nodes":[%s,%s],"connections":[%s]}}`,
|
||||
recallNode("a", "userTask"), recallNode("b", "userTask"), recallConn("a", "b"))
|
||||
recallSeedInstance(t, q, "inst-dft", string(enums.InstanceStatusActive))
|
||||
base := time.Now().Add(-time.Hour)
|
||||
recallSeedTask(t, q, "t-a", "inst-dft", "a", constants.TaskTypeUserTask, string(enums.TaskStatusCompleted),
|
||||
"jia", base, base.Add(time.Minute), "")
|
||||
recallSeedTask(t, q, "t-b", "inst-dft", "b", constants.TaskTypeUserTask, string(enums.TaskStatusActive),
|
||||
"yi", base.Add(2*time.Minute), time.Time{}, "")
|
||||
svc, _ := newRecallSvc(q, def, nil)
|
||||
|
||||
require.NoError(t, svc.Recall(ctx, Actor{UserID: "jia", TenantID: "t1"}, "inst-dft", ""))
|
||||
}
|
||||
@@ -73,6 +73,8 @@ const (
|
||||
EndReasonPrefixRejected = "审批拒绝"
|
||||
// EndReasonPrefixWithdrawn 发起人撤回写入 end_reason 的前缀
|
||||
EndReasonPrefixWithdrawn = "申请人撤回"
|
||||
// EndReasonPrefixRecall 收回终止前沿任务写入 end_reason 的前缀
|
||||
EndReasonPrefixRecall = "审批人收回"
|
||||
)
|
||||
const (
|
||||
TaskTypeUserTask = "userTask"
|
||||
|
||||
@@ -104,6 +104,8 @@ const (
|
||||
EndReasonClaimedByOther EndReason = "claimed_by_other"
|
||||
// EndReasonWithdrawn 发起人撤回
|
||||
EndReasonWithdrawn EndReason = "withdrawn"
|
||||
// EndReasonRecalled 审批人收回(撤销自己已通过的审批,重新待审)
|
||||
EndReasonRecalled EndReason = "recalled"
|
||||
)
|
||||
|
||||
// ActionType 操作类型枚举
|
||||
|
||||
Reference in new issue
Block a user