Esempio n. 1
0
        private IUserInfo GetUser(IExecutionEntity execution, string authenticatedUserId)
        {
            IUserInfo         starter;
            IUserServiceProxy userService = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();

            try
            {
                starter = userService.GetUser(authenticatedUserId)
                          .ConfigureAwait(false)
                          .GetAwaiter()
                          .GetResult();
                starter.TenantId = execution.TenantId;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                starter = new UserInfo
                {
                    Id       = execution.StartUserId,
                    FullName = execution.StartUserId,
                    TenantId = execution.TenantId
                };
            }

            return(starter);
        }
        public void Notify(IDelegateTask task)
        {
            string assignee = task.Assignee;

            if (string.IsNullOrWhiteSpace(assignee))
            {
                return;
            }

            IUserInfo user = task.GetVariableLocal <IUserInfo>($"{assignee}");

            if (!(user is null) && user.Id == assignee)
            {
                return;
            }

            IUserServiceProxy userService = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();

            user = AsyncHelper.RunSync(() => userService.GetUser(assignee));
            if (user == null)
            {
                logger.LogError($"找不到执行人{assignee}");
            }
            else
            {
                user.TenantId     = task.TenantId;
                task.AssigneeUser = user.FullName;
            }

            task.SetVariableLocal($"{assignee}", user);
        }
        public virtual ITask Execute(ICommandContext commandContext)
        {
            ITaskService taskService = commandContext.ProcessEngineConfiguration.TaskService;

            if (taskService.CreateTaskQuery().SetTaskId(parentTaskId).SingleResult() == null)
            {
                throw new ActivitiObjectNotFoundException("Parent task with id " + parentTaskId + " was not found");
            }

            string id   = commandContext.ProcessEngineConfiguration.IdGenerator.GetNextId();
            ITask  task = taskService.NewTask(id);

            task.Name         = taskName;
            task.Description  = description;
            task.DueDate      = dueDate;
            task.Priority     = priority;
            task.ParentTaskId = parentTaskId;
            task.Assignee     = assignee;
            if (string.IsNullOrWhiteSpace(assignee) == false)
            {
                task.AssigneeUser = AsyncHelper.RunSync(() => userService.GetUser(assignee))?.FullName;
            }
            task.TenantId = tenantId;
            taskService.SaveTask(task);

            return(task);
        }
Esempio n. 4
0
        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var phone = context.Request.Raw["phone"];              //手机号
            var code  = context.Request.Raw["mobile_verify_code"]; //验证码

            if (phone == "18621685194" && code == "8888")
            {
                context.Result = new GrantValidationResult(
                    subject: phone,
                    authenticationMethod: "custom",
                    claims: new Claim[] {
                    new Claim("user_id", "888"),
                    new Claim("user_name", "18621685194"),
                    new Claim("mobile", "18621685194"),
                    new Claim("email", "*****@*****.**")
                }
                    );
                return;
            }

            var errorvalidationResult = new GrantValidationResult(TokenRequestErrors.InvalidGrant);

            if (string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(code))
            {
                context.Result = errorvalidationResult;
                return;
            }

            var verification = await _verificationServiceProxy.GetVerification(BizCode.Login, phone);

            if (verification == null)
            {
                context.Result = errorvalidationResult;
                return;
            }

            var result = await _userServiceProxy.GetUser(phone);

            if (result == null)
            {
                await _userServiceProxy.AddUser(phone, null, phone, null, null);
            }

            context.Result = new GrantValidationResult(
                subject: phone,
                authenticationMethod: "custom",
                claims: new Claim[] {
                new Claim("user_id", ""),
                new Claim("user_name", phone),
                new Claim("mobile", phone),
                new Claim("email", "")
            }
                );
        }
Esempio n. 5
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            task.DelegationState = DelegationState.PENDING;
            if (task.Owner is null)
            {
                task.Owner = task.Assignee;
            }
            string userName = null;

            if (string.IsNullOrWhiteSpace(userId) == false)
            {
                userName = AsyncHelper.RunSync(() => userService.GetUser(userId))?.FullName;
            }
            commandContext.TaskEntityManager.ChangeTaskAssignee(task, userId, userName);
            return(null);
        }
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            bool assignedToNoOne = false;

            if (IdentityLinkType.ASSIGNEE.Equals(identityType))
            {
                string assigneeUser = null;
                if (string.IsNullOrWhiteSpace(identityId) == false)
                {
                    assigneeUser = AsyncHelper.RunSync(() => userService.GetUser(identityId))?.FullName;
                }
                commandContext.TaskEntityManager.ChangeTaskAssignee(task, identityId, assigneeUser);
                assignedToNoOne = identityId is null;
            }
            else if (IdentityLinkType.OWNER.Equals(identityType))
            {
                commandContext.TaskEntityManager.ChangeTaskOwner(task, identityId);
            }
            else if (IDENTITY_USER == identityIdType)
            {
                task.AddUserIdentityLink(identityId, identityType);
            }
            else if (IDENTITY_GROUP == identityIdType)
            {
                task.AddGroupIdentityLink(identityId, identityType);
            }

            bool forceNullUserId = false;

            if (assignedToNoOne)
            {
                // ACT-1317: Special handling when assignee is set to NULL, a
                // CommentEntity notifying of assignee-delete should be created
                forceNullUserId = true;
            }

            if (IDENTITY_USER == identityIdType)
            {
                commandContext.HistoryManager.CreateUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId);
            }
            else
            {
                commandContext.HistoryManager.CreateGroupIdentityLinkComment(taskId, identityId, identityType, true);
            }

            return(null);
        }
Esempio n. 7
0
        public virtual ITask Execute(ICommandContext commandContext)
        {
            ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.ProcessEngineConfiguration;
            ITaskService taskService = processEngineConfiguration.TaskService;
            string       id          = processEngineConfiguration.IdGenerator.GetNextId();
            ITask        task        = taskService.NewTask(id);

            task.Name        = taskName;
            task.Description = description;
            task.DueDate     = dueDate;
            task.Priority    = priority;
            task.Assignee    = assignee;
            if (string.IsNullOrWhiteSpace(assignee) == false)
            {
                task.AssigneeUser = AsyncHelper.RunSync(() => userService.GetUser(assignee))?.FullName;
            }
            taskService.SaveTask(task);

            return(task);
        }
Esempio n. 8
0
        protected internal override object Execute(ICommandContext commandContext, ITaskEntity task)
        {
            if (variables != null)
            {
                task.Variables = variables;
            }
            if (transientVariables != null)
            {
                task.TransientVariables = transientVariables;
            }

            task.DelegationState = DelegationState.RESOLVED;
            string ownerName = null;

            if (string.IsNullOrWhiteSpace(task.Owner) == false)
            {
                ownerName = AsyncHelper.RunSync(() => userService.GetUser(task.Owner))?.FullName;
            }
            commandContext.TaskEntityManager.ChangeTaskAssignee(task, task.Owner, ownerName);

            return(null);
        }
        public void Notify(IDelegateTask task)
        {
            string assignee = task.Assignee;

            if (string.IsNullOrWhiteSpace(assignee))
            {
                return;
            }

            IUserInfo user;

            if (task.HasVariableLocal(assignee))
            {
                user = task.GetVariableLocal <IUserInfo>(assignee);
                if (user is object && string.Equals(user.Id, assignee, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
            }

            IUserServiceProxy userService = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();

            user = userService.GetUser(assignee)
                   .ConfigureAwait(false)
                   .GetAwaiter()
                   .GetResult();
            if (user == null)
            {
                logger.LogError($"找不到执行人{assignee}");
            }
            else
            {
                user.TenantId     = task.TenantId;
                task.AssigneeUser = user.FullName;
            }

            task.SetVariableLocal($"{assignee}", user);
        }
Esempio n. 10
0
        public virtual ITask Execute(ICommandContext commandContext)
        {
            ITaskService taskService = commandContext.ProcessEngineConfiguration.TaskService;
            ITask        task        = taskService.CreateTaskQuery().SetTaskId(updateTaskCmd.TaskId).SingleResult();

            if (task == null)
            {
                throw new ActivitiObjectNotFoundException("Unable to find task for the given id: " + updateTaskCmd.TaskId);
            }
            task.Assignee = updateTaskCmd.Assignee;
            if (string.IsNullOrWhiteSpace(task.Assignee) == false)
            {
                task.AssigneeUser = AsyncHelper.RunSync(() => userService.GetUser(task.Assignee))?.FullName;
            }
            task.Name         = updateTaskCmd.Name;
            task.Description  = updateTaskCmd.Description;
            task.DueDate      = updateTaskCmd.DueDate;
            task.Priority     = updateTaskCmd.Priority;
            task.ParentTaskId = string.IsNullOrWhiteSpace(updateTaskCmd.ParentTaskId) ? task.ParentTaskId : updateTaskCmd.ParentTaskId;
            taskService.SaveTask(task);

            return(task);
        }
Esempio n. 11
0
        public ITask[] Execute(ICommandContext commandContext)
        {
            ProcessEngineConfigurationImpl pec = commandContext.ProcessEngineConfiguration;
            IRuntimeService runtimeService     = pec.RuntimeService;
            ITaskService    taskService        = pec.TaskService;
            IIdGenerator    idGenerator        = pec.IdGenerator;

            ITask            task      = taskService.CreateTaskQuery().SetTaskId(taskId).SingleResult();
            IExecutionEntity execution = runtimeService.CreateExecutionQuery().SetExecutionId(task.ExecutionId).SingleResult() as IExecutionEntity;
            IExecutionEntity parent    = execution.Parent;

            //查找当前待追加人员是否已经存在在任务列表中,proc_inst_id_
            IList <ITask> assignTasks = taskService.CreateTaskQuery()
                                        .SetProcessInstanceId(execution.ProcessInstanceId)
                                        .SetTaskAssigneeIds(assignees)
                                        .List();

            var users = assignees.Where(x => assignTasks.Any(y => x == y.Assignee) == false).ToList();

            if (users.Count == 0)
            {
                throw new NotFoundAssigneeException();
            }

            if (parent.IsMultiInstanceRoot && parent.CurrentFlowElement is UserTask mTask)
            {
                string varName = mTask.LoopCharacteristics.InputDataItem;
                var    match   = new Regex("\\$\\{(.*?)\\}").Match(varName);
                varName = match.Groups[1].Value;

                IList <string> list = parent.GetLoopVariable <IList <string> >(varName);

                parent.SetLoopVariable(varName, users.Union(list).Distinct().ToArray());
            }

            IList <ITask> tasks = new List <ITask>(users.Count);

            foreach (var assignee in users)
            {
                //创建父活动的子活动
                IExecutionEntity newExecution = pec.CommandExecutor.Execute(new CreateChildExecutionCmd(parent));
                //设置为激活 状态
                newExecution.IsActive    = true;
                newExecution.ActivityId  = execution.ActivityId;
                newExecution.BusinessKey = execution.BusinessKey;
                //该属性表示创建的newExecution对象为分支,非常重要,不可缺少
                newExecution.IsConcurrent = execution.IsConcurrent;
                newExecution.IsScope      = false;
                ITaskEntity taskEntity = pec.CommandExecutor.Execute(new NewTaskCmd(pec.IdGenerator.GetNextId()));
                taskEntity.ProcessDefinitionId = task.ProcessDefinitionId;
                taskEntity.TaskDefinitionKey   = task.TaskDefinitionKey;
                taskEntity.ProcessInstanceId   = task.ProcessInstanceId;
                taskEntity.ExecutionId         = newExecution.Id;
                taskEntity.Name = task.Name;

                if (string.IsNullOrWhiteSpace(taskEntity.Id))
                {
                    string taskId = idGenerator.GetNextId();
                    taskEntity.Id = taskId;
                }
                taskEntity.Execution = newExecution;
                taskEntity.Assignee  = assignee;
                if (string.IsNullOrWhiteSpace(assignee) == false)
                {
                    taskEntity.AssigneeUser = AsyncHelper.RunSync(() => userService.GetUser(assignee))?.FullName;
                }
                taskEntity.TenantId = task.TenantId;
                taskEntity.FormKey  = task.FormKey;
                taskEntity.IsAppend = true;

                taskService.SaveTask(taskEntity);

                tasks.Add(taskEntity);
            }

            //修改执行实例父级实例变量数和活动实例变量数
            int nrOfInstances          = parent.GetLoopVariable <int>(MultiInstanceActivityBehavior.NUMBER_OF_INSTANCES);
            int nrOfActiveIntance      = parent.GetLoopVariable <int>(MultiInstanceActivityBehavior.NUMBER_OF_ACTIVE_INSTANCES);
            int nrOfCompletedInstances = parent.GetLoopVariable <int>(MultiInstanceActivityBehavior.NUMBER_OF_COMPLETED_INSTANCES);

            parent.SetLoopVariable(MultiInstanceActivityBehavior.NUMBER_OF_INSTANCES, nrOfInstances + users.Count);
            parent.SetLoopVariable(MultiInstanceActivityBehavior.NUMBER_OF_ACTIVE_INSTANCES, nrOfInstances - nrOfCompletedInstances + users.Count);

            return(tasks.ToArray());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="taskEntityManager"></param>
        /// <param name="assignee"></param>
        /// <param name="owner"></param>
        /// <param name="candidateUsers"></param>
        /// <param name="candidateGroups"></param>
        /// <param name="task"></param>
        /// <param name="expressionManager"></param>
        /// <param name="execution"></param>
        protected internal virtual void HandleAssignments(ITaskEntityManager taskEntityManager, string assignee, string owner, IList <string> candidateUsers, IList <string> candidateGroups, ITaskEntity task, ExpressionManager expressionManager, IExecutionEntity execution)
        {
            if (!string.IsNullOrWhiteSpace(assignee))
            {
                object assigneeExpressionValue = expressionManager.CreateExpression(assignee).GetValue(execution);
                string assigneeValue           = null;
                if (assigneeExpressionValue != null)
                {
                    assigneeValue = assigneeExpressionValue.ToString();
                }
                string assigneeUser = null;

                if (string.IsNullOrWhiteSpace(assigneeValue) == false)
                {
                    IUserServiceProxy userService = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();

                    var user = userService.GetUser(assigneeValue)
                               .ConfigureAwait(false)
                               .GetAwaiter()
                               .GetResult();

                    assigneeUser = user?.FullName;

                    task.SetVariableLocal(assigneeValue, user);
                }
                taskEntityManager.ChangeTaskAssigneeNoEvents(task, assigneeValue, assigneeUser);
            }

            if (!string.IsNullOrWhiteSpace(owner))
            {
                object ownerExpressionValue = expressionManager.CreateExpression(owner).GetValue(execution);
                string ownerValue           = null;
                if (ownerExpressionValue != null)
                {
                    ownerValue = ownerExpressionValue.ToString();
                }

                taskEntityManager.ChangeTaskOwner(task, ownerValue);
            }

            if (candidateGroups != null && candidateGroups.Count > 0)
            {
                foreach (string candidateGroup in candidateGroups)
                {
                    IExpression groupIdExpr = expressionManager.CreateExpression(candidateGroup);
                    object      value       = groupIdExpr.GetValue(execution);
                    if (value is string @string)
                    {
                        IList <string> candidates = ExtractCandidates(@string);
                        task.AddCandidateGroups(candidates);
                    }
                    else if (value is ICollection)
                    {
                        task.AddCandidateGroups((ICollection <string>)value);
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("Expression did not resolve to a string or collection of strings");
                    }
                }
            }

            if (candidateUsers != null && candidateUsers.Count > 0)
            {
                foreach (string candidateUser in candidateUsers)
                {
                    IExpression userIdExpr = expressionManager.CreateExpression(candidateUser);
                    object      value      = userIdExpr.GetValue(execution);
                    if (value is string @string)
                    {
                        IList <string> candidates = ExtractCandidates(@string);
                        task.AddCandidateUsers(candidates);
                    }
                    else if (value is ICollection)
                    {
                        task.AddCandidateUsers((ICollection <string>)value);
                    }
                    else
                    {
                        throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                    }
                }
            }

            if (userTask.CustomUserIdentityLinks != null && userTask.CustomUserIdentityLinks.Count > 0)
            {
                foreach (string customUserIdentityLinkType in userTask.CustomUserIdentityLinks.Keys)
                {
                    foreach (string userIdentityLink in userTask.CustomUserIdentityLinks[customUserIdentityLinkType])
                    {
                        IExpression idExpression = expressionManager.CreateExpression(userIdentityLink);
                        object      value        = idExpression.GetValue(execution);
                        if (value is string @string)
                        {
                            IList <string> userIds = ExtractCandidates(@string);
                            foreach (string userId in userIds)
                            {
                                task.AddUserIdentityLink(userId, customUserIdentityLinkType);
                            }
                        }
                        else if (value is ICollection collection)
                        {
                            IEnumerator userIdSet = collection.GetEnumerator();
                            while (userIdSet.MoveNext())
                            {
                                task.AddUserIdentityLink((string)userIdSet.Current, customUserIdentityLinkType);
                            }
                        }
                        else
                        {
                            throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                        }
                    }
                }
            }

            if (userTask.CustomGroupIdentityLinks != null && userTask.CustomGroupIdentityLinks.Count > 0)
            {
                foreach (string customGroupIdentityLinkType in userTask.CustomGroupIdentityLinks.Keys)
                {
                    foreach (string groupIdentityLink in userTask.CustomGroupIdentityLinks[customGroupIdentityLinkType])
                    {
                        IExpression idExpression = expressionManager.CreateExpression(groupIdentityLink);
                        object      value        = idExpression.GetValue(execution);
                        if (value is string @string)
                        {
                            IList <string> groupIds = ExtractCandidates(@string);
                            foreach (string groupId in groupIds)
                            {
                                task.AddGroupIdentityLink(groupId, customGroupIdentityLinkType);
                            }
                        }
                        else if (value is ICollection collection)
                        {
                            IEnumerator groupIdSet = collection.GetEnumerator();
                            while (groupIdSet.MoveNext())
                            {
                                task.AddGroupIdentityLink((string)groupIdSet.Current, customGroupIdentityLinkType);
                            }
                        }
                        else
                        {
                            throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                        }
                    }
                }
            }
        }
Esempio n. 13
0
        // CREATE METHODS

        public virtual IExecutionEntity CreateProcessInstanceExecution(IProcessDefinition processDefinition, string businessKey, string tenantId, string initiatorVariableName)
        {
            IExecutionEntity processInstanceExecution = executionDataManager.Create();

            if (ExecutionRelatedEntityCountEnabledGlobally)
            {
                ((ICountingExecutionEntity)processInstanceExecution).IsCountEnabled = true;
            }

            processInstanceExecution.ProcessDefinitionId      = processDefinition.Id;
            processInstanceExecution.ProcessDefinitionKey     = processDefinition.Key;
            processInstanceExecution.ProcessDefinitionName    = processDefinition.Name;
            processInstanceExecution.ProcessDefinitionVersion = processDefinition.Version;
            processInstanceExecution.BusinessKey = businessKey;
            processInstanceExecution.IsScope     = true; // process instance is always a scope for all child executions

            // Inherit tenant id (if any)
            if (!(tenantId is null))
            {
                processInstanceExecution.TenantId = tenantId;
            }

            string authenticatedUserId = Authentication.AuthenticatedUser.Id;

            processInstanceExecution.StartTime   = Context.ProcessEngineConfiguration.Clock.CurrentTime;
            processInstanceExecution.StartUserId = authenticatedUserId;
            processInstanceExecution.StartUser   = Authentication.AuthenticatedUser.FullName;

            // Store in database
            Insert(processInstanceExecution, false);

            if (string.IsNullOrWhiteSpace(processInstanceExecution.StartUserId) == false)
            {
                IUserInfo                 starter           = null;
                IUserServiceProxy         userService       = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();
                ExternalConnectorProvider externalConnector = ProcessEngineServiceProvider.Resolve <ExternalConnectorProvider>();

                try
                {
                    starter          = AsyncHelper.RunSync <IUserInfo>(() => userService.GetUser(processInstanceExecution.StartUserId));
                    starter.TenantId = processInstanceExecution.TenantId;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, ex.Message);
                    starter = new UserInfo
                    {
                        Id       = processInstanceExecution.StartUserId,
                        FullName = processInstanceExecution.StartUserId
                    };
                }

                //保存调用用户变量
                processInstanceExecution.SetVariable(processInstanceExecution.StartUserId, starter);
            }

            if (!(initiatorVariableName is null))
            {
                processInstanceExecution.SetVariable(initiatorVariableName, authenticatedUserId);
            }

            // Need to be after insert, cause we need the id
            processInstanceExecution.ProcessInstanceId     = processInstanceExecution.Id;
            processInstanceExecution.RootProcessInstanceId = processInstanceExecution.Id;
            if (!(authenticatedUserId is null))
            {
                IdentityLinkEntityManager.AddIdentityLink(processInstanceExecution, authenticatedUserId, null, IdentityLinkType.STARTER);
            }

            // Fire events
            if (EventDispatcher.Enabled)
            {
                EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.ENTITY_CREATED, processInstanceExecution));
            }

            return(processInstanceExecution);
        }