mirror of
https://github.com/rulego/gflow-engine.git
synced 2026-12-05 08:00:59 +00:00
894 lines
36 KiB
Go
894 lines
36 KiB
Go
package service
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"sort"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/sirupsen/logrus"
|
||
|
||
"github.com/rulego/gflow-engine/types/constants"
|
||
"github.com/rulego/gflow-engine/types/dto"
|
||
"github.com/rulego/gflow-engine/types/enums"
|
||
"github.com/rulego/gflow-engine/utils"
|
||
"github.com/rulego/rulego/api/types"
|
||
|
||
"github.com/rulego/gflow-engine/model"
|
||
)
|
||
|
||
// detailPageSizeFetchAll 实例详情需要单实例任务全集(时间线、活跃节点判定、
|
||
// 后续审批人预测):会签子任务、加签、驳回回跳重跑很容易超过默认 pageSize。
|
||
// 注意宿主分页钳制为 MaxPageSize=200,本常量超过 200 时按 200 生效,超量
|
||
// 由 listAllInstanceTasks 的循环翻页兜底(正确性不受影响,多付几次 COUNT)。
|
||
const detailPageSizeFetchAll = 1000
|
||
|
||
// listAllInstanceTasks 翻页取全单实例任务集,防止分页截断。实例任务量正常远
|
||
// 小于单页上限,循环只是防御极端形态(上万行实例本身就异常)。
|
||
func (s *RuntimeServiceImpl) listAllInstanceTasks(ctx context.Context, actor Actor, q *dto.TaskQuery) ([]*model.WfTask, error) {
|
||
var all []*model.WfTask
|
||
for page := 1; ; page++ {
|
||
q.Page = page
|
||
pageTasks, total, err := s.workflowEngine.GetTaskService().GetTaskList(ctx, actor, q)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
all = append(all, pageTasks...)
|
||
if int64(len(all)) >= total || len(pageTasks) == 0 {
|
||
return all, nil
|
||
}
|
||
}
|
||
}
|
||
|
||
// GetProcessInstanceDetail 获取流程实例详情(时间线、流程定义、当前用户任务与权限)
|
||
// 入参:actor 查询视角的用户(操作人);processInstanceID 流程实例ID
|
||
// 出参:dto.InstanceDetailResponse
|
||
func (s *RuntimeServiceImpl) GetProcessInstanceDetail(ctx context.Context, actor Actor, processInstanceID string) (*dto.InstanceDetailResponse, error) {
|
||
ctx = bindActor(ctx, actor)
|
||
currentUserId := actor.UserID
|
||
// 1. 获取流程实例
|
||
instance, err := s.GetProcessInstance(ctx, actor, processInstanceID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if instance == nil {
|
||
return nil, fmt.Errorf("instance not found")
|
||
}
|
||
|
||
if err := ensureTenantAccess(ctx, "process instance", instance.TenantID); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
// 2. 查询该实例下任务列表并组装审批时间线
|
||
// 可见性校验需要覆盖历史 assignee 与 CC 抄送归属,故终态实例查历史、活态实例同时查运行时+历史
|
||
taskQuery := &dto.TaskQuery{InstanceID: &processInstanceID, PageRequest: dto.PageRequest{PageSize: detailPageSizeFetchAll}}
|
||
if instance.Status == string(enums.InstanceStatusActive) || instance.Status == string(enums.InstanceStatusSuspended) {
|
||
taskQuery.QueryHistory = false
|
||
} else {
|
||
taskQuery.QueryHistory = true
|
||
}
|
||
tasks, err := s.listAllInstanceTasks(ctx, actor, taskQuery)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
// 活态实例主查询只读运行时表,可见性判定需要补查历史 task(已 completed 的前序节点 assignee + CC 抄送归属)
|
||
visibilityTasks := tasks
|
||
if !taskQuery.QueryHistory {
|
||
histQuery := &dto.TaskQuery{InstanceID: &processInstanceID, QueryHistory: true, PageRequest: dto.PageRequest{PageSize: detailPageSizeFetchAll}}
|
||
if histTasks, histErr := s.listAllInstanceTasks(ctx, actor, histQuery); histErr == nil {
|
||
visibilityTasks = append(visibilityTasks, histTasks...)
|
||
}
|
||
}
|
||
|
||
// 可见性校验:当前用户必须是 发起人 / 该实例任一 task 的 assignee(含历史)/ CC 抄送归属,否则 IDOR 越权拒绝。
|
||
// actor.UserID 为空即拒绝(fail-closed):宿主漏传操作人时不得因缺身份而放行。
|
||
// 工作流管理员放行——管理侧需要查看全部实例。
|
||
if isWorkflowAdmin(GetUserFromCtx(ctx)) {
|
||
// 管理员放行
|
||
} else if currentUserId == "" {
|
||
return nil, fmt.Errorf("instance %s detail requires an actor with user id: %w", processInstanceID, ErrAuthenticationRequired)
|
||
} else if !isInstanceVisibleToUser(instance, visibilityTasks, currentUserId) && !s.isPendingCandidateVisible(ctx, visibilityTasks, currentUserId) {
|
||
return nil, fmt.Errorf("current user %s has no view permission on instance %s: %w", currentUserId, processInstanceID, ErrPermissionDenied)
|
||
}
|
||
var approvalList []dto.ExecutionInfo
|
||
// 回退/撤回会把 returned/terminated 任务归档进历史表并从运行时表删除,
|
||
// 活态实例只读运行时表就看不到这些痕迹,故并入历史条目(visibilityTasks
|
||
// 已是两表全集),再按创建时间排序还原节点先后。
|
||
timelineTasks := tasks
|
||
if !taskQuery.QueryHistory {
|
||
seen := make(map[string]bool, len(visibilityTasks))
|
||
for _, t := range tasks {
|
||
seen[t.ID] = true
|
||
}
|
||
for _, t := range visibilityTasks {
|
||
if !seen[t.ID] {
|
||
timelineTasks = append(timelineTasks, t)
|
||
seen[t.ID] = true
|
||
}
|
||
}
|
||
sort.SliceStable(timelineTasks, func(i, j int) bool {
|
||
return timelineTasks[i].CreatedAt.Before(timelineTasks[j].CreatedAt)
|
||
})
|
||
}
|
||
for _, task := range timelineTasks {
|
||
if task.ParentID == nil || *task.ParentID == "" {
|
||
approvalList = append(approvalList, Task2ExecutionInfo(task, timelineTasks))
|
||
}
|
||
}
|
||
markFormModified(timelineTasks, approvalList)
|
||
// 意见源升级:账本行(wf_task_comment)优先、Comment 快照兜底,附件随账本行透出
|
||
mergeTimelineComments(approvalList, s.loadTimelineComments(ctx, timelineTasks))
|
||
|
||
// 3. 当前用户在该实例上的待审批任务 - 查找 active/suspended/pending 状态的任务
|
||
var currentUserTask *model.WfTask
|
||
var currentUserTaskStatus string // 记录找到的任务状态,用于权限判断
|
||
if currentUserId != "" {
|
||
// 优先查找 active 任务
|
||
for _, t := range tasks {
|
||
if t.Assignee != nil && *t.Assignee == currentUserId && t.Status == string(enums.TaskStatusActive) {
|
||
currentUserTask = t
|
||
currentUserTaskStatus = string(enums.TaskStatusActive)
|
||
break
|
||
}
|
||
}
|
||
// 其次查找 suspended 任务(挂起的任务可唤醒)
|
||
if currentUserTask == nil {
|
||
for _, t := range tasks {
|
||
if t.Assignee != nil && *t.Assignee == currentUserId && t.Status == string(enums.TaskStatusSuspended) {
|
||
currentUserTask = t
|
||
currentUserTaskStatus = string(enums.TaskStatusSuspended)
|
||
break
|
||
}
|
||
}
|
||
}
|
||
// 最后查找 pending 任务(候选组待认领):仅选中当前用户是候选成员的任务。
|
||
// 同节点候选结果调用内缓存,避免对同一 defKey 重复展开角色/部门
|
||
if currentUserTask == nil {
|
||
candMemo := map[string]bool{}
|
||
for _, t := range tasks {
|
||
if t.Status != string(enums.TaskStatusPending) {
|
||
continue
|
||
}
|
||
ok, cached := candMemo[t.TaskDefKey]
|
||
if !cached {
|
||
ok = s.isUserCandidate(ctx, t, currentUserId)
|
||
candMemo[t.TaskDefKey] = ok
|
||
}
|
||
if ok {
|
||
currentUserTask = t
|
||
currentUserTaskStatus = string(enums.TaskStatusPending)
|
||
break
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 4. 流程定义与节点配置
|
||
var definitionJSON string
|
||
var formSchemaJSON string
|
||
var processName string // 流程定义名称:详情头部/打印模板展示
|
||
var actionPermissions = map[string]interface{}{} // 审批人节点(userTask)的设计器动作权限
|
||
var starterActionPermissions = map[string]interface{}{} // 发起人动作权限(流程级 ruleChain.additionalInfo.actionPermissions)
|
||
var formPermissions = map[string]string{}
|
||
var ccFormPermissions map[string]string // 抄送人视角字段权限(无待办、仅抄送可见时下发)
|
||
var ruleChain *types.RuleChain // 解析后的链定义(upcoming 预测遍历用)
|
||
if instance.ProcessID != "" {
|
||
procDef, err := s.workflowEngine.GetProcessService().Get(ctx, instance.ProcessID)
|
||
if err == nil && procDef != nil {
|
||
definitionJSON = procDef.DefinitionJSON
|
||
processName = procDef.Name
|
||
|
||
// 从 definitionJson 中提取 form schema:标准位 ruleChain.additionalInfo.form,
|
||
// 旧格式顶层 form 兜底(与前端 parseDefinitionJson 同口径)
|
||
var defData map[string]interface{}
|
||
if err := json.Unmarshal([]byte(definitionJSON), &defData); err == nil {
|
||
extractForm := func(v interface{}) bool {
|
||
if v == nil {
|
||
return false
|
||
}
|
||
if formBytes, merr := json.Marshal(v); merr == nil {
|
||
formSchemaJSON = string(formBytes)
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
if rc, ok := defData["ruleChain"].(map[string]interface{}); ok {
|
||
if ai, ok := rc["additionalInfo"].(map[string]interface{}); ok {
|
||
extractForm(ai["form"])
|
||
}
|
||
}
|
||
if formSchemaJSON == "" {
|
||
extractForm(defData["form"])
|
||
}
|
||
}
|
||
if formSchemaJSON == "" {
|
||
formSchemaJSON = "{}"
|
||
}
|
||
|
||
// 设计器配置分两层:
|
||
// - ruleChain.additionalInfo.actionPermissions:流程级发起人动作(withdraw/resubmit/urge/suspend/terminate)
|
||
// —— 即流程级"高级设置",不挂在 startTask 节点上
|
||
// - userTask(审批人节点)的 additionalInfo.actionPermissions:审批人视角动作(addComment/transfer/return/terminate/uploadAttachment/awaken)
|
||
rc, rcErr := procDef.ToRuleChain()
|
||
if rcErr == nil {
|
||
ruleChain = rc
|
||
// 流程级发起人动作权限
|
||
if ap, ok := rc.RuleChain.GetAdditionalInfo("actionPermissions"); ok {
|
||
if v, ok := ap.(map[string]interface{}); ok {
|
||
starterActionPermissions = v
|
||
}
|
||
}
|
||
|
||
if currentUserTask != nil {
|
||
if node, ok := rc.GetNode(currentUserTask.TaskDefKey); ok {
|
||
// 审批人节点 actionPermissions:直接读已解析链的节点配置。
|
||
// 不再走 resolveNodeActionPermissions——那条路径重复加载实例行
|
||
// 与定义行并二次解析全量链 JSON,本函数上文已全部持有。
|
||
if ap, ok := node.GetAdditionalInfo("actionPermissions"); ok {
|
||
if v, ok := ap.(map[string]interface{}); ok {
|
||
actionPermissions = v
|
||
}
|
||
}
|
||
if ap, ok := node.GetAdditionalInfo("formPermissions"); ok {
|
||
// additionalInfo 经 JSON 反序列化为 map[string]interface{},字段值需逐键断言为 string 取出。
|
||
if v, ok := ap.(map[string]interface{}); ok {
|
||
formPermissions = normalizeDetailFormPermissions(v, formSchemaFieldKeyMap(rc))
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
// 无待办任务且以抄送身份查看:下发其所在抄送节点的字段权限,
|
||
// 设计器 CcDrawer 的配置至此生效('h' 隐藏字段抄送人不可见)。
|
||
// 多个抄送节点同字段配置不一致时取最严(h > r > w)。
|
||
ccFormPermissions = resolveCCFormPermissions(rc, timelineTasks, currentUserId)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 5. 变量(来自任务)
|
||
var variables map[string]interface{}
|
||
sourceTask := currentUserTask
|
||
if sourceTask == nil {
|
||
// 兜底行从末尾向前取第一份真实任务快照:终态实例的历史行集含流转
|
||
// 轨迹行(转办/委派/改派/收回留痕),其变量只有留痕键,选中会让
|
||
// 详情变量变成无业务含义的垃圾键,整张表单数据消失。
|
||
for i := len(tasks) - 1; i >= 0; i-- {
|
||
t := tasks[i]
|
||
if t == nil || constants.IsTransitionTraceType(t.TaskType) || t.TaskType == constants.TaskTypeRecall {
|
||
continue
|
||
}
|
||
sourceTask = t
|
||
break
|
||
}
|
||
}
|
||
if sourceTask != nil {
|
||
// 解析失败保持 nil(响应里变量为空),不阻断详情装配
|
||
if v, err := ParseVariablesJSON(sourceTask.Variables); err == nil {
|
||
variables = v
|
||
}
|
||
}
|
||
// 草稿实例没有任务(发起时不驱动引擎),变量只在实例行上:
|
||
// 任务侧取不到时回退实例变量,否则暂存的表单数据在详情里不可见
|
||
if variables == nil && instance.Variables != nil {
|
||
if v, err := ParseVariablesJSON(instance.Variables); err == nil {
|
||
variables = v
|
||
}
|
||
}
|
||
// 任务快照可能缺失或预埋系统字段:预测与实际驱动一样,以实例快照为准。
|
||
variables = resolveForecastVariables(variables, instance.Variables)
|
||
|
||
// 5.5 后续审批节点预测(仅活态实例):从活跃节点沿 Success 出边向前遍历
|
||
var upcoming []dto.UpcomingNode
|
||
if ruleChain != nil &&
|
||
(instance.Status == string(enums.InstanceStatusActive) || instance.Status == string(enums.InstanceStatusSuspended)) {
|
||
activeNodeSet := make(map[string]bool)
|
||
for _, t := range tasks {
|
||
if t.Status == string(enums.TaskStatusActive) || t.Status == string(enums.TaskStatusPending) || t.Status == string(enums.TaskStatusSuspended) {
|
||
activeNodeSet[t.TaskDefKey] = true
|
||
}
|
||
}
|
||
if len(activeNodeSet) > 0 {
|
||
activeNodeIDs := make([]string, 0, len(activeNodeSet))
|
||
for id := range activeNodeSet {
|
||
activeNodeIDs = append(activeNodeIDs, id)
|
||
}
|
||
upcoming = BuildUpcomingNodes(ruleChain, activeNodeIDs, instance.TenantID, instance.StartUserID, variables)
|
||
}
|
||
}
|
||
|
||
// 6. 组装响应。ActionPermissions 在第 7 步按"状态 × 设计器"二维合并后填入
|
||
// 系统组织快照只参与路由和预测,不进入业务表单变量。
|
||
delete(variables, constants.VarsStarter)
|
||
resp := &dto.InstanceDetailResponse{
|
||
InstanceID: instance.ID,
|
||
InstanceStatus: instance.Status,
|
||
Name: instance.Name,
|
||
ProcessName: processName,
|
||
StartUserID: instance.StartUserID,
|
||
StartTime: instance.CreatedAt,
|
||
DefinitionJSON: definitionJSON,
|
||
FormSchemaJSON: formSchemaJSON,
|
||
Executions: approvalList,
|
||
Variables: variables,
|
||
Upcoming: upcoming,
|
||
ActionPermissions: map[string]interface{}{},
|
||
}
|
||
if len(ccFormPermissions) > 0 {
|
||
resp.CCFormPermissions = ccFormPermissions
|
||
}
|
||
if instance.EndReason != nil {
|
||
resp.EndReason = *instance.EndReason
|
||
}
|
||
|
||
// 7. 基于"状态 × 设计器"二维计算动作权限
|
||
// 设计器不可控的动作(核心审批 + 任务生命周期),按状态强制开放:
|
||
// approve / reject / claim / unclaim / activate / delete / suspend
|
||
// 设计器可控的动作(默认开/关由前端 DEFAULT_ACTION_PERMISSIONS 决定):
|
||
// addComment / withdraw / awaken / resubmit / transfer / return / urge / terminate / uploadAttachment
|
||
// 合并语义:
|
||
// - 状态强制键:状态命中即开放,忽略 designer
|
||
// - 设计器可控键:状态命中 AND designer 未显式 false 才开放
|
||
// - designer 显式开启的可选键(transfer/return/urge/uploadAttachment):仅 active 任务才有意义
|
||
// 注意:发起人和审批人权限可叠加(同一用户可能既是发起人又是审批人),前端通过 pageType 区分显示
|
||
isActiveTask := currentUserTask != nil && currentUserTaskStatus == string(enums.TaskStatusActive)
|
||
|
||
if instance.StartUserID == currentUserId {
|
||
// 发起人动作的设计器开关来自流程级 additionalInfo.actionPermissions(starterActionPermissions)
|
||
switch instance.Status {
|
||
case string(enums.InstanceStatusDraft):
|
||
resp.ActionPermissions["activate"] = true // 草稿→发起审批(实例级,必备)
|
||
resp.ActionPermissions["delete"] = true // 草稿→可删除(实例级,必备)
|
||
case string(enums.InstanceStatusActive):
|
||
// suspend / withdraw 受流程级配置控制
|
||
if !designerDisabled(starterActionPermissions, "suspend") {
|
||
resp.ActionPermissions["suspend"] = true
|
||
}
|
||
if !designerDisabled(starterActionPermissions, "withdraw") {
|
||
resp.ActionPermissions["withdraw"] = true
|
||
}
|
||
// urge:发起人催办(active 实例时可催办审批人)
|
||
if !designerDisabled(starterActionPermissions, "urge") {
|
||
resp.ActionPermissions["urge"] = true
|
||
}
|
||
case string(enums.InstanceStatusSuspended):
|
||
resp.ActionPermissions["activate"] = true // 已挂起→可恢复(实例级,必备)
|
||
if !designerDisabled(starterActionPermissions, "terminate") {
|
||
resp.ActionPermissions["terminate"] = true
|
||
}
|
||
case string(enums.InstanceStatusFailed):
|
||
resp.ActionPermissions["activate"] = true // 失败→可恢复(实例级,必备)
|
||
if !designerDisabled(starterActionPermissions, "resubmit") {
|
||
resp.ActionPermissions["resubmit"] = true
|
||
}
|
||
case string(enums.InstanceStatusTerminated):
|
||
if !designerDisabled(starterActionPermissions, "resubmit") {
|
||
resp.ActionPermissions["resubmit"] = true
|
||
}
|
||
// completed / cancelled: 终态,无操作权限
|
||
}
|
||
}
|
||
|
||
// 审批人收回:运行中实例=本人存在可收回记录且守卫通过;已完成实例=末节点
|
||
// 审批人在窗口期内可整单重开(末节点重审)。守卫与 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
|
||
}
|
||
}
|
||
}
|
||
// 完成实例的可重开前提:末尾存在已完成的 userTask 节点。末尾完成的是
|
||
// 系统节点时重入无从谈起,按钮位与写路径同拒,避免可点但必失败。
|
||
// terminalRecallEnabled 总闸关闭时已完成实例不下发收回位,与写路径同开同关。
|
||
if terminalRecallEnabled {
|
||
completedInstanceHasUserTask := false
|
||
for _, t := range tasks {
|
||
if t != nil && t.TaskType == constants.TaskTypeUserTask && t.Status == string(enums.TaskStatusCompleted) {
|
||
completedInstanceHasUserTask = true
|
||
break
|
||
}
|
||
}
|
||
if instance.Status == string(enums.InstanceStatusCompleted) && completedInstanceHasUserTask &&
|
||
!designerDisabled(starterActionPermissions, "recall") &&
|
||
currentUserIsLastNodeVoter(tasks, currentUserId) &&
|
||
withinRecallWindow(starterActionPermissions, instance.EndedAt) {
|
||
resp.ActionPermissions["recall"] = true
|
||
}
|
||
}
|
||
|
||
// 管理员代审按钮:流程开关未显式关闭(缺省即开,opt-out)+ WorkflowAdmin +
|
||
// 存在可代审的在途任务(已签收、非委派中)。与 ProxyAudit 写路径同口径;
|
||
// 按钮位只保证存在一个合格任务,加签未决/任务在此后被委派等时序外情况由
|
||
// 写路径兜底拒绝。API 准入另有宿主 workflow:task:proxy 权限位(前端按钮同判)。
|
||
if instance.Status == string(enums.InstanceStatusActive) &&
|
||
isWorkflowAdmin(&actor) && !designerDisabled(starterActionPermissions, "proxyAudit") {
|
||
for _, t := range tasks {
|
||
if t != nil && t.TaskType == constants.TaskTypeUserTask &&
|
||
t.Status == string(enums.TaskStatusActive) &&
|
||
t.Assignee != nil && *t.Assignee != "" &&
|
||
(t.Owner == nil || *t.Owner == "") {
|
||
resp.ActionPermissions["proxyAudit"] = true
|
||
break
|
||
}
|
||
}
|
||
}
|
||
|
||
if currentUserTask != nil {
|
||
switch currentUserTaskStatus {
|
||
case string(enums.TaskStatusActive):
|
||
// approve / reject 是核心审批动作,后端强制开放,设计器不可控制
|
||
resp.ActionPermissions["approve"] = true
|
||
resp.ActionPermissions["reject"] = true
|
||
// addComment 受 designer 控制(默认开)
|
||
if !designerDisabled(actionPermissions, "addComment") {
|
||
resp.ActionPermissions["addComment"] = true
|
||
}
|
||
// unclaim:当前用户已签收的 active 任务可释放
|
||
if currentUserTask.Assignee != nil &&
|
||
*currentUserTask.Assignee == currentUserId &&
|
||
currentUserTask.ClaimedAt != nil {
|
||
resp.ActionPermissions["unclaim"] = true
|
||
}
|
||
case string(enums.TaskStatusPending):
|
||
resp.ActionPermissions["claim"] = true // 待领取→必须能签收(设计器不可控制)
|
||
case string(enums.TaskStatusSuspended):
|
||
// 唤醒只在 active 实例上可用(单任务微操):实例级挂起期间任务冻结,
|
||
// 恢复走实例级 activate,与 ActivateTask 写路径守卫同口径
|
||
if instance.Status == string(enums.InstanceStatusActive) && !designerDisabled(actionPermissions, "awaken") {
|
||
resp.ActionPermissions["awaken"] = true
|
||
}
|
||
}
|
||
|
||
// designer 显式开启的可选动作(transfer / return / delegate / addSign / reduceSign / urge / uploadAttachment)
|
||
// 仅在 active 任务上有意义
|
||
if isActiveTask {
|
||
for _, k := range []string{"transfer", "return", "delegate", "addSign", "reduceSign", "urge", "uploadAttachment"} {
|
||
if designerEnabled(actionPermissions, k) {
|
||
resp.ActionPermissions[k] = true
|
||
}
|
||
}
|
||
}
|
||
|
||
// 可回退目标节点:仅在 return 按钮可见时计算,供前端回退弹窗直出选项,
|
||
// 与 Return 写路径校验同口径(已运行 + 拓扑上游 + 非自身 + 重执行区域不跨并行网关)
|
||
if isActiveTask && ruleChain != nil && designerEnabled(actionPermissions, "return") {
|
||
resp.ReturnableNodes = buildReturnableNodes(ruleChain, tasks, currentUserTask.TaskDefKey)
|
||
}
|
||
|
||
resp.CurrentUserActivityTask = dto.CurrentUserActivityTask{
|
||
TaskID: currentUserTask.ID,
|
||
TaskDefKey: currentUserTask.TaskDefKey,
|
||
TaskName: currentUserTask.Name,
|
||
FormPermissions: formPermissions,
|
||
Variables: parseTaskVariables(currentUserTask.Variables),
|
||
}
|
||
}
|
||
|
||
// 8. reject 策略透传:rejectStrategy / rejectTargetNode 是行为配置(控制拒绝后走向),
|
||
// 不是按钮显隐;只要 designer 配了就透传给前端
|
||
if v, ok := actionPermissions["rejectStrategy"]; ok && v != "" {
|
||
resp.ActionPermissions["rejectStrategy"] = v
|
||
}
|
||
if v, ok := actionPermissions["rejectTargetNode"]; ok && v != "" {
|
||
resp.ActionPermissions["rejectTargetNode"] = v
|
||
}
|
||
|
||
return resp, nil
|
||
}
|
||
|
||
// isInstanceVisibleToUser 判定当前用户对该实例是否有可见性。
|
||
// 可见条件(满足任一):发起人、该实例任一 task 的 assignee(含历史)、
|
||
// 流转动作轨迹行的当事人(操作人 created_by 或前一任办理人 prev_assignee,
|
||
// 覆盖转办/委派/归还/改派)、CC 抄送归属。
|
||
// 待认领候选成员不在 task.assignee 上,由调用方经 isPendingCandidateVisible 补充判定。
|
||
// currentUserId 由调用方保证非空(空 UserID 在 GetProcessInstanceDetail 已被拒绝)。
|
||
func isInstanceVisibleToUser(instance *model.WfInstance, tasks []*model.WfTask, currentUserId string) bool {
|
||
if instance.StartUserID == currentUserId {
|
||
return true
|
||
}
|
||
for _, t := range tasks {
|
||
if t == nil {
|
||
continue
|
||
}
|
||
if t.Assignee != nil && *t.Assignee == currentUserId {
|
||
return true
|
||
}
|
||
// 流转动作后票原地换受理人,操作人与前一任办理人在 assignee 口径上都
|
||
// 不可达:转办人/委派人/归还操作人凭 created_by 保留可见(对齐主流审批:
|
||
// 转出/委出后仍可查看单据进度,只是不可再操作),改派场景 prev_assignee
|
||
// 补上被换下的原受理人——操作人是管理员,原受理人两头无锚点即此缺口
|
||
if constants.IsTransitionTraceType(t.TaskType) &&
|
||
(t.CreatedBy == currentUserId || (t.PrevAssignee != nil && *t.PrevAssignee == currentUserId)) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// isPendingCandidateVisible 待认领任务的候选成员对实例详情可见:候选任务无 assignee,
|
||
// 不满足 isInstanceVisibleToUser 的任何条件,但成员须能看到详情才能签收。
|
||
func (s *RuntimeServiceImpl) isPendingCandidateVisible(ctx context.Context, tasks []*model.WfTask, currentUserId string) bool {
|
||
candMemo := map[string]bool{}
|
||
for _, t := range tasks {
|
||
if t == nil || t.Status != string(enums.TaskStatusPending) {
|
||
continue
|
||
}
|
||
ok, cached := candMemo[t.TaskDefKey]
|
||
if !cached {
|
||
ok = s.isUserCandidate(ctx, t, currentUserId)
|
||
candMemo[t.TaskDefKey] = ok
|
||
}
|
||
if ok {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// designerDisabled 判断设计器是否在 actionPermissions 中显式禁用了某个动作。
|
||
// 缺省(未配置)视为未禁用;只有显式 false 才视为禁用。
|
||
func designerDisabled(actionPermissions map[string]interface{}, key string) bool {
|
||
v, ok := actionPermissions[key]
|
||
if !ok {
|
||
return false
|
||
}
|
||
b, ok := v.(bool)
|
||
return ok && !b
|
||
}
|
||
|
||
// designerEnabled 判断设计器是否在 actionPermissions 中显式开启了某个动作。
|
||
// 用于"默认关"的可选动作(transfer / return / urge / uploadAttachment)。
|
||
func designerEnabled(actionPermissions map[string]interface{}, key string) bool {
|
||
v, ok := actionPermissions[key]
|
||
if !ok {
|
||
return false
|
||
}
|
||
b, ok := v.(bool)
|
||
return ok && b
|
||
}
|
||
|
||
// currentUserIsLastNodeVoter 判断查询者是否末节点(最近完成的 userTask 节点)
|
||
// 的已完成投票人——终态收回的第三类资格,与 recallCompleted 的
|
||
// latestCompletedNodeInHistory 同口径:按结束时间取最近完成的 userTask 节点,
|
||
// 该节点上本人存在已完成且有办理人的记录;代审票与系统自动完成票不算
|
||
// (isHumanCompletedVote),与写路径资格一致。
|
||
func currentUserIsLastNodeVoter(tasks []*model.WfTask, userID string) bool {
|
||
var last *model.WfTask
|
||
for _, t := range tasks {
|
||
if t == nil || t.TaskType != constants.TaskTypeUserTask ||
|
||
t.Status != string(enums.TaskStatusCompleted) || t.TaskDefKey == "" {
|
||
continue
|
||
}
|
||
if last == nil || (t.EndedAt != nil && (last.EndedAt == nil || t.EndedAt.After(*last.EndedAt))) {
|
||
last = t
|
||
}
|
||
}
|
||
if last == nil {
|
||
return false
|
||
}
|
||
for _, t := range tasks {
|
||
if t != nil && t.TaskDefKey == last.TaskDefKey &&
|
||
t.Status == string(enums.TaskStatusCompleted) &&
|
||
t.Assignee != nil && *t.Assignee == userID &&
|
||
isHumanCompletedVote(t.Variables, t.UpdatedBy) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// loadTimelineComments 一次批查时间线全部任务(含会签子任务)的意见行,按任务
|
||
// 分组、组内时间正序。查询失败降级为空表:意见源退回 Comment 快照、附件不展示,
|
||
// 不让账本查询故障拖垮详情主路径。
|
||
func (s *RuntimeServiceImpl) loadTimelineComments(ctx context.Context, tasks []*model.WfTask) map[string][]*model.WfTaskComment {
|
||
ids := make([]string, 0, len(tasks))
|
||
for _, t := range tasks {
|
||
if t != nil && t.ID != "" {
|
||
ids = append(ids, t.ID)
|
||
}
|
||
}
|
||
if len(ids) == 0 {
|
||
return nil
|
||
}
|
||
if s.taskCommentDAO == nil {
|
||
return nil
|
||
}
|
||
rows, err := s.taskCommentDAO.ListByTaskIDs(ctx, ids)
|
||
if err != nil {
|
||
logrus.WithError(err).Warn("failed to load timeline comments; falling back to snapshot comments")
|
||
return nil
|
||
}
|
||
byTask := make(map[string][]*model.WfTaskComment, len(rows))
|
||
for _, r := range rows {
|
||
if r != nil {
|
||
byTask[r.TaskID] = append(byTask[r.TaskID], r)
|
||
}
|
||
}
|
||
return byTask
|
||
}
|
||
|
||
// mergeTimelineComments 把意见账本行合并为时间线意见源:有账本行的任务以账本行
|
||
// 为准(首行文本为意见、全部行的附件并集),无账本行保持 Comment 快照兜底
|
||
// (意见列启用前的存量任务)。子任务子树递归同口径。
|
||
// 账本写入口:审批动作(含回退)、代审系统行、委派归还被委派人意见、强制改派
|
||
// 留痕——同任务多行时首行(最早)为意见文本,代审系统行写入侧已 +1ms 保证
|
||
// 排在本人意见行之后;委派归还是"被委派人先表态、原审批人后续完成"的两轮
|
||
// 场景,时间线只显示最近一轮先落的那行(被委派人意见),原审批人终审意见仍
|
||
// 在其自己的完成动作行上。AddTaskComment 是引擎开放 API 但宿主未接线,接入方
|
||
// 若启用它须重新评估取行策略。
|
||
func mergeTimelineComments(execs []dto.ExecutionInfo, byTask map[string][]*model.WfTaskComment) {
|
||
for i := range execs {
|
||
rows := byTask[execs[i].TaskID]
|
||
if len(rows) > 0 {
|
||
content := rows[0].Content
|
||
execs[i].Comment = &content
|
||
atts := make([]dto.ApprovalAttachment, 0, len(rows))
|
||
for _, r := range rows {
|
||
atts = append(atts, parseAttachmentRefs(r.Attachments)...)
|
||
}
|
||
if len(atts) > 0 {
|
||
execs[i].Attachments = atts
|
||
}
|
||
}
|
||
if len(execs[i].SubExecutions) > 0 {
|
||
mergeTimelineComments(execs[i].SubExecutions, byTask)
|
||
}
|
||
}
|
||
}
|
||
|
||
// parseAttachmentRefs 解析意见行的附件引用列;空列或损坏 JSON 返回空并告警
|
||
// (损坏行不阻断整条时间线)。
|
||
func parseAttachmentRefs(col *string) []dto.ApprovalAttachment {
|
||
if col == nil || *col == "" {
|
||
return nil
|
||
}
|
||
var atts []dto.ApprovalAttachment
|
||
if err := json.Unmarshal([]byte(*col), &atts); err != nil {
|
||
logrus.WithError(err).Warn("failed to parse comment attachments; skipping")
|
||
return nil
|
||
}
|
||
return atts
|
||
}
|
||
|
||
// Task2ExecutionInfo 把任务行装配为审批时间线视图。tasks 须包含同实例(至少是
|
||
// 同节点父子关系内的)全部任务,才能正确拼出 SubExecutions 会签子任务子树。
|
||
func Task2ExecutionInfo(task *model.WfTask, tasks []*model.WfTask) dto.ExecutionInfo {
|
||
executionInfo := dto.ExecutionInfo{
|
||
TaskID: task.ID,
|
||
TaskDefKey: task.TaskDefKey,
|
||
TaskName: task.Name,
|
||
TaskType: task.TaskType,
|
||
Status: task.Status,
|
||
EndReason: task.EndReason,
|
||
Assignee: task.Assignee,
|
||
Comment: task.Comment,
|
||
SubExecutions: GetSubTasks(task.ID, tasks),
|
||
}
|
||
executionInfo.IsCandidate = (task.Assignee == nil || *task.Assignee == "") && task.Status == string(enums.TaskStatusPending)
|
||
// 委派中(Owner 在位):代审对象列表须剔除——ExecutionInfo 不透出 owner 原值,
|
||
// 只透出该布尔(V1 代审不支持委派中任务)
|
||
executionInfo.Delegated = task.Owner != nil && *task.Owner != ""
|
||
if m, perr := ParseVariablesJSON(task.Variables); perr == nil {
|
||
if v, ok := m[constants.VarsProxyOperator].(string); ok {
|
||
executionInfo.ProxyBy = v
|
||
}
|
||
if v, ok := m[constants.VarsSignAddedBy].(string); ok {
|
||
executionInfo.SignAddedBy = v
|
||
}
|
||
// 转办留痕:转办后时间线渲染「由 X 转办」。transfer_time 旧数据是
|
||
// time.Time 的 RFC3339 序列化文本,统一规整为时间线时间格式,解析失败原样透出
|
||
if v, ok := m[constants.VarsTransferFrom].(string); ok {
|
||
executionInfo.TransferredFrom = v
|
||
}
|
||
if v, ok := m[constants.VarsTransferReason].(string); ok {
|
||
executionInfo.TransferredReason = v
|
||
}
|
||
if v, ok := m[constants.VarsTransferTime].(string); ok {
|
||
executionInfo.TransferredAt = formatTransferTime(v)
|
||
}
|
||
// 转办轨迹行的操作人:时间线把该行渲染成「已转办」节点,处理人取此值
|
||
if v, ok := m[constants.VarsForwardBy].(string); ok {
|
||
executionInfo.ForwardBy = v
|
||
}
|
||
// 委派/归还/改派轨迹行的操作人与目标人:时间线把该行渲染成对应动作
|
||
// 节点,处理人取操作人
|
||
if v, ok := m[constants.VarsTraceOperator].(string); ok {
|
||
executionInfo.TraceOperator = v
|
||
}
|
||
if v, ok := m[constants.VarsTraceTarget].(string); ok {
|
||
executionInfo.TraceTarget = v
|
||
}
|
||
}
|
||
if task.EndedAt != nil {
|
||
executionInfo.EndedAt = utils.FormatTime(*task.EndedAt)
|
||
}
|
||
if task.ClaimedAt != nil {
|
||
executionInfo.ClaimedAt = utils.FormatTime(*task.ClaimedAt)
|
||
}
|
||
return executionInfo
|
||
}
|
||
|
||
// formatTransferTime 转办时间规整为时间线时间格式(RFC3339 带时区偏移)。写入侧
|
||
// 现为 TimeFormatLayout 布局文本(进程本地墙钟,不带时区),旧数据是 time.Time 的
|
||
// RFC3339 序列化文本。布局分支必须按 time.Local 锚定:无区布局 time.Parse 默认得
|
||
// UTC,规整成 RFC3339 后浏览器按偏移换算会整体偏移一个时区;RFC3339 分支自带
|
||
// 偏移,锚定参数不生效。都不中则原样返回。
|
||
func formatTransferTime(raw string) string {
|
||
for _, layout := range []string{constants.TimeFormatLayout, time.RFC3339, time.RFC3339Nano} {
|
||
if t, err := time.ParseInLocation(layout, raw, time.Local); err == nil {
|
||
return utils.FormatTime(t)
|
||
}
|
||
}
|
||
return raw
|
||
}
|
||
|
||
// GetSubTasks 取 parentTaskId 的全部直接子任务(加签产生的会签子任务),并递归装配其自身子树。
|
||
func GetSubTasks(parentTaskId string, tasks []*model.WfTask) []dto.ExecutionInfo {
|
||
var assignees []dto.ExecutionInfo
|
||
for _, item := range tasks {
|
||
if item.ParentID != nil && *item.ParentID == parentTaskId {
|
||
info := Task2ExecutionInfo(item, tasks)
|
||
assignees = append(assignees, info)
|
||
}
|
||
}
|
||
return assignees
|
||
}
|
||
|
||
// parseTaskVariables 解析任务变量快照(JSON 字符串 → map);
|
||
// 空值/解析失败返回 nil(AI 兜底待办的 _ai 快照经此暴露给审批详情)。
|
||
func parseTaskVariables(raw *string) map[string]interface{} {
|
||
if raw == nil || strings.TrimSpace(*raw) == "" {
|
||
return nil
|
||
}
|
||
var m map[string]interface{}
|
||
if err := json.Unmarshal([]byte(*raw), &m); err != nil || m == nil {
|
||
return nil
|
||
}
|
||
return m
|
||
}
|
||
|
||
// formSnapshotMaxBytes 单份任务变量参与行级修改标记的体积上限:病态大表单
|
||
// (base64 附件误入变量等)逐键序列化比对会拖慢详情组装,超限的快照退出
|
||
// 比对链(该行不标记,弹窗仍可单独查看)。
|
||
const formSnapshotMaxBytes = 256 * 1024
|
||
|
||
// taskVariablesSnapshot 任务变量快照的对外口径:剥引擎保留标记键、审批约定
|
||
// 键(approved/comment——只在快照层剥,全局保留键集不含它们,Complete 内部
|
||
// 还要消费审批意图)、改派留痕与下划线前缀的引擎内部键(_sequentialAssignees
|
||
// 顺序审批缓存、_ai 智能体输出等),只余表单字段。历史任务查询透出、行级
|
||
// 修改标记与加签子任务的快照继承(addSignInternal 种子)共用,各方不得
|
||
// 各自维护剥离口径。
|
||
func taskVariablesSnapshot(task *model.WfTask) map[string]interface{} {
|
||
m := parseTaskVariables(task.Variables)
|
||
if m == nil {
|
||
return nil
|
||
}
|
||
for k := range m {
|
||
if k == constants.VarsApproved || k == constants.VarsComment ||
|
||
isEngineReservedVarKey(k) || strings.HasPrefix(k, "_") {
|
||
delete(m, k)
|
||
}
|
||
}
|
||
return m
|
||
}
|
||
|
||
// snapshotValueBytes 变量值序列化:map 键序由 encoding/json 排序保证确定性,
|
||
// 数组/对象整体序列化后比较(不递归出条目级差异)。
|
||
func snapshotValueBytes(v interface{}) []byte {
|
||
b, err := json.Marshal(v)
|
||
if err != nil {
|
||
return nil
|
||
}
|
||
return b
|
||
}
|
||
|
||
// diffSnapshotKeys 相邻两份快照的 key 级差异计数:新增/删除/值变化各算一处。
|
||
func diffSnapshotKeys(prev, cur map[string]interface{}) int {
|
||
changed := 0
|
||
for k, v := range cur {
|
||
pv, ok := prev[k]
|
||
if !ok {
|
||
changed++
|
||
continue
|
||
}
|
||
if string(snapshotValueBytes(pv)) != string(snapshotValueBytes(v)) {
|
||
changed++
|
||
}
|
||
}
|
||
for k := range prev {
|
||
if _, ok := cur[k]; !ok {
|
||
changed++
|
||
}
|
||
}
|
||
return changed
|
||
}
|
||
|
||
// markFormModified 给审批时间线行打表单修改标记:按完成时间序对已完成任务
|
||
// (startTask/userTask)的变量快照做相邻比对,与上一份快照有差异的行标记
|
||
// formModified 并记差异字段数;行上同时下发 FormPrevTaskID(前一份快照的
|
||
// 任务 ID),快照弹窗的修改痕迹据此对齐,宿主不自行重建比对链。发起行的
|
||
// 快照即发起初版表单(行上冻结,后续修改不回写),作为链首参与比对,第一
|
||
// 个审批节点改表单因此可检测;发起行自身是链首,永不标记。轨迹行/系统节点/
|
||
// 超限/解析失败的快照退出比对链。
|
||
func markFormModified(tasks []*model.WfTask, approvals []dto.ExecutionInfo) {
|
||
// 比对链按完成时间排序:会签子任务先于父任务完成,创建序与完成序相反,
|
||
// 修改痕迹的先后语义跟随快照冻结时刻
|
||
chain := make([]*model.WfTask, 0, len(tasks))
|
||
for _, t := range tasks {
|
||
if t == nil || t.Status != string(enums.TaskStatusCompleted) {
|
||
continue
|
||
}
|
||
if t.TaskType != constants.TaskTypeUserTask && t.TaskType != constants.TaskTypeStartTask {
|
||
continue
|
||
}
|
||
if t.Variables == nil || *t.Variables == "" || len(*t.Variables) > formSnapshotMaxBytes {
|
||
continue
|
||
}
|
||
chain = append(chain, t)
|
||
}
|
||
sort.SliceStable(chain, func(i, j int) bool {
|
||
a, b := chain[i], chain[j]
|
||
at, bt := a.CreatedAt, b.CreatedAt
|
||
if a.EndedAt != nil {
|
||
at = *a.EndedAt
|
||
}
|
||
if b.EndedAt != nil {
|
||
bt = *b.EndedAt
|
||
}
|
||
if !at.Equal(bt) {
|
||
return at.Before(bt)
|
||
}
|
||
return a.CreatedAt.Before(b.CreatedAt)
|
||
})
|
||
|
||
type chainSnapshot struct {
|
||
taskID string
|
||
raw string
|
||
fields map[string]interface{}
|
||
}
|
||
marks := make(map[string]int, len(chain))
|
||
prevOf := make(map[string]string, len(chain))
|
||
var prev *chainSnapshot
|
||
for _, t := range chain {
|
||
snap := taskVariablesSnapshot(t)
|
||
// 解析失败的损坏数据退出链:nil 快照若进链会毒化后续所有比对(假阴性)
|
||
if snap == nil {
|
||
continue
|
||
}
|
||
if prev != nil {
|
||
// 相邻快照原文相等(审批人未改表的常见情形)时跳过逐值序列化比对
|
||
if prev.raw != *t.Variables {
|
||
if n := diffSnapshotKeys(prev.fields, snap); n > 0 {
|
||
marks[t.ID] = n
|
||
}
|
||
}
|
||
prevOf[t.ID] = prev.taskID
|
||
}
|
||
prev = &chainSnapshot{taskID: t.ID, raw: *t.Variables, fields: snap}
|
||
}
|
||
if len(marks) == 0 && len(prevOf) == 0 {
|
||
return
|
||
}
|
||
applyFormModifiedMarks(approvals, marks, prevOf)
|
||
}
|
||
|
||
// applyFormModifiedMarks 递归下发行级标记:加签子任务在 SubExecutions 子树里。
|
||
func applyFormModifiedMarks(approvals []dto.ExecutionInfo, marks map[string]int, prevOf map[string]string) {
|
||
for i := range approvals {
|
||
if n, ok := marks[approvals[i].TaskID]; ok {
|
||
approvals[i].FormModified = true
|
||
approvals[i].FormChangedCount = n
|
||
}
|
||
if id, ok := prevOf[approvals[i].TaskID]; ok {
|
||
approvals[i].FormPrevTaskID = id
|
||
}
|
||
if len(approvals[i].SubExecutions) > 0 {
|
||
applyFormModifiedMarks(approvals[i].SubExecutions, marks, prevOf)
|
||
}
|
||
}
|
||
}
|