Ejemplo n.º 1
0
        public async Task <string> Handle(CreateNotificationInstanceCommand request, CancellationToken cancellationToken)
        {
            var notificationDef = await _notificationDefQueryRepository.Get(request.NotificationId, cancellationToken);

            if (notificationDef == null)
            {
                throw new UnknownNotificationException(string.Format(Global.UnknownNotification, request.NotificationId));
            }

            var operationParameters = request.Parameters == null ? new Dictionary <string, string>() : request.Parameters;
            var parameters          = _parameterParser.ParseOperationParameters(notificationDef.InputParameters, operationParameters);

            _logger.LogInformation($"Create notification '{notificationDef.Name}'");
            var presentationElt = _parameterParser.ParsePresentationElements(notificationDef.PresentationElements,
                                                                             notificationDef.PresentationParameters,
                                                                             parameters);
            var assignmentInstance = _parameterParser.ParsePeopleAssignments(
                notificationDef.PeopleAssignments,
                parameters);
            var id = Guid.NewGuid().ToString();
            var notificationInstance = NotificationInstanceAggregate.New(id,
                                                                         notificationDef.Priority,
                                                                         notificationDef.Name,
                                                                         parameters,
                                                                         presentationElt,
                                                                         assignmentInstance,
                                                                         notificationDef.Rendering);
            await _notificationInstanceCommandRepository.Add(notificationInstance, cancellationToken);

            await _notificationInstanceCommandRepository.SaveChanges(cancellationToken);

            return(notificationInstance.AggregateId);
        }
        public async Task <bool> Handle(CompleteHumanTaskInstanceCommand request, CancellationToken cancellationToken)
        {
            if (request.Claims == null || !request.Claims.Any())
            {
                _logger.LogError("User is not authenticated");
                throw new NotAuthenticatedException(Global.UserNotAuthenticated);
            }

            if (request.OperationParameters == null)
            {
                _logger.LogError("Output data must be specified");
                throw new BadRequestException(string.Format(Global.MissingParameter, "operationParameters"));
            }

            var humanTaskInstance = await _humanTaskInstanceQueryRepository.Get(request.HumanTaskInstanceId, cancellationToken);

            if (humanTaskInstance == null)
            {
                _logger.LogError($"HumanTask '{request.HumanTaskInstanceId}' doesn't exist");
                throw new UnknownHumanTaskInstanceException(string.Format(Global.UnknownHumanTaskInstance, request.HumanTaskInstanceId));
            }

            if (humanTaskInstance.Status != HumanTaskInstanceStatus.INPROGRESS)
            {
                _logger.LogError("Complete operation can be performed only on INPROGRESS human task instance");
                throw new BadOperationExceptions(string.Format(Global.OperationCanBePerformed, "Complete", "INPROGRESS"));
            }

            var operationParameters = request.OperationParameters;
            var parameters          = _parameterParser.ParseOperationParameters(humanTaskInstance.OutputOperationParameters, operationParameters);
            var nameIdentifier      = request.Claims.GetUserNameIdentifier();

            if (nameIdentifier != humanTaskInstance.ActualOwner)
            {
                _logger.LogError("Authenticated user is not the actual owner");
                throw new NotAuthorizedException(Global.NotActualOwner);
            }

            var completionResult = await CheckCompletionBehavior(humanTaskInstance, parameters, cancellationToken);

            if (completionResult.IsSatisfied)
            {
                parameters = completionResult.Content;
            }

            await Complete(humanTaskInstance, parameters, nameIdentifier, cancellationToken);

            if (!string.IsNullOrWhiteSpace(humanTaskInstance.ParentHumanTaskId))
            {
                var parentTask = await _humanTaskInstanceQueryRepository.Get(humanTaskInstance.ParentHumanTaskId, cancellationToken);

                if (parentTask.CompletionBehavior == CompletionBehaviors.AUTOMATIC)
                {
                    completionResult = await CheckCompletionBehavior(parentTask, new Dictionary <string, string>(), cancellationToken, false);

                    if (completionResult.IsSatisfied)
                    {
                        await Complete(parentTask, new Dictionary <string, string>(), nameIdentifier, cancellationToken);
                    }
                }
            }

            foreach (var cb in humanTaskInstance.CallbackOperations)
            {
                var jObj = new JObject
                {
                    { "parameters", parameters.ToJObj() }
                };
                using (var httpClient = _httpClientFactory.Build())
                {
                    var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                    {
                        Address      = _options.OAuthTokenEndpoint,
                        ClientId     = _options.ClientId,
                        ClientSecret = _options.ClientSecret,
                        Scope        = _options.Scope
                    }, cancellationToken);

                    var req = new HttpRequestMessage
                    {
                        Method     = HttpMethod.Post,
                        RequestUri = new Uri(cb.Url),
                        Content    = new StringContent(jObj.ToString(), Encoding.UTF8, "application/json")
                    };
                    req.Headers.Add("Authorization", $"Bearer {tokenResponse.AccessToken}");
                    await httpClient.SendAsync(req, cancellationToken);
                }
            }

            return(true);
        }
        public async Task <TaskInstanceCreatedResult> Handle(CreateHumanTaskInstanceCommand request, CancellationToken cancellationToken)
        {
            if (request.Claims == null || !request.Claims.Any())
            {
                _logger.LogError("User is not authenticated");
                throw new NotAuthenticatedException(Global.UserNotAuthenticated);
            }

            var humanTaskDef = await _humanTaskDefQueryRepository.GetLatest(request.HumanTaskName, cancellationToken);

            if (humanTaskDef == null)
            {
                _logger.LogError($"Human task definition '{request.HumanTaskName}' doesn't exist");
                throw new UnknownHumanTaskDefException(string.Format(Global.UnknownHumanTaskDef, request.HumanTaskName));
            }

            var operationParameters = request.OperationParameters == null ? new Dictionary <string, string>() : request.OperationParameters;
            var parameters          = _parameterParser.ParseOperationParameters(humanTaskDef.InputParameters, operationParameters);
            var assignment          = EnrichAssignment(humanTaskDef, request);
            var priority            = EnrichPriority(humanTaskDef, request);
            var assignmentInstance  = _parameterParser.ParsePeopleAssignments(assignment, parameters);

            if (!request.IgnorePermissions)
            {
                var roles = await _authorizationHelper.GetRoles(assignmentInstance, request.Claims, cancellationToken);

                if (!roles.Any(r => r == UserRoles.TASKINITIATOR))
                {
                    _logger.LogError("User is not a task initiator");
                    throw new NotAuthorizedException(Global.UserNotAuthorized);
                }
            }

            _logger.LogInformation($"Create human task '{request.HumanTaskName}'");
            var userPrincipal        = request.NameIdentifier;
            var id                   = Guid.NewGuid().ToString();
            var deadLines            = _deadlineParser.Evaluate(humanTaskDef.DeadLines, parameters);
            var presentationElements = _parameterParser.ParsePresentationElements(humanTaskDef.PresentationElements, humanTaskDef.PresentationParameters, operationParameters);
            var humanTaskInstance    = HumanTaskInstanceAggregate.New(
                id,
                userPrincipal,
                request.HumanTaskName,
                humanTaskDef.ValidatorFullQualifiedName,
                parameters,
                assignmentInstance,
                priority,
                request.ActivationDeferralTime,
                request.ExpirationTime,
                deadLines,
                presentationElements,
                humanTaskDef.Type,
                humanTaskDef.InstantiationPattern,
                humanTaskDef.SubTasks.Select(_ => new HumanTaskInstanceSubTask
            {
                HumanTaskName = _.TaskName,
                ToParts       = _.ToParts
            }).ToList(),
                humanTaskDef.OperationParameters,
                humanTaskDef.CompletionAction,
                humanTaskDef.Completions,
                humanTaskDef.Rendering,
                request.CallbackUrls == null ? new List <CallbackOperation>() : request.CallbackUrls.Select(_ => new CallbackOperation
            {
                Id  = Guid.NewGuid().ToString(),
                Url = _
            }).ToList());
            await _humanTaskInstanceCommandRepository.Add(humanTaskInstance, cancellationToken);

            await _humanTaskInstanceCommandRepository.SaveChanges(cancellationToken);

            humanTaskDef.IncrementInstance();
            await _humanTaskDefCommandRepository.Update(humanTaskDef, cancellationToken);

            return(new TaskInstanceCreatedResult
            {
                Id = humanTaskInstance.AggregateId,
                DefId = humanTaskDef.AggregateId
            });
        }