public When_i_clone_template_to_create_new_template()
            {
                _command = new TemplateCreateAsCloneCommand
                {
                    CloneFromTemplateId = Guid.NewGuid().ToString(),
                    Description         = "New Description",
                    FundingStreamId     = "NEW",
                    FundingPeriodId     = "20-21"
                };
                _author = new Reference("222", "CloningTestUser");

                SetupMocks();

                _service = new TemplateBuilderService(
                    _validatorFactory,
                    _templateValidationService,
                    _templateMetadataResolver,
                    _versionRepository,
                    _templateRepository,
                    _templateIndexer,
                    _policyRepository,
                    _templateBlobService,
                    Substitute.For <ILogger>());

                _result = _service.CreateTemplateAsClone(_command, _author).GetAwaiter().GetResult();
            }
コード例 #2
0
        public async Task <IActionResult> CreateTemplateAsClone([FromBody] TemplateCreateAsCloneCommand createModel)
        {
            Guard.ArgumentNotNull(createModel, nameof(createModel));

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FundingStreamPermission permissions = await _authorizationHelper.GetUserFundingStreamPermissions(User, createModel.FundingStreamId);

            if (!permissions.CanCreateTemplates)
            {
                _logger.Error($"User [{User?.Identity?.Name}] has insufficient permissions to create a {createModel.FundingStreamId} template");
                return(Forbid(new AuthenticationProperties()));
            }

            ValidatedApiResponse <string> result = await _client.CreateTemplateAsClone(createModel);

            switch (result.StatusCode)
            {
            case HttpStatusCode.Created:
                return(Created($"api/templates/build/{result.Content}", result.Content));

            case HttpStatusCode.BadRequest:
                return(BadRequest(result.ModelState));

            default:
                return(StatusCode((int)result.StatusCode));
            }
        }
        public async Task <IActionResult> CreateTemplateAsClone(TemplateCreateAsCloneCommand command)
        {
            ValidationResult validationResult = await _validatorFactory.Validate(command);

            if (!validationResult.IsValid)
            {
                return(validationResult.AsBadRequest());
            }

            Reference author = ControllerContext.HttpContext.Request?.GetUserOrDefault();

            CommandResult result = await _templateBuilderService.CreateTemplateAsClone(command, author);

            if (result.Succeeded)
            {
                return(new CreatedResult($"api/templates/build/{result.TemplateId}", result.TemplateId));
            }

            if (result.ValidationResult != null)
            {
                return(result.ValidationResult.AsBadRequest());
            }

            return(new InternalServerErrorResult(result.ErrorMessage ?? result.Exception?.Message ?? "Unknown error occurred"));
        }
コード例 #4
0
        public async Task <CommandResult> CreateTemplateAsClone(TemplateCreateAsCloneCommand command, Reference author)
        {
            ValidationResult validatorResult = await _validatorFactory.Validate(command);

            validatorResult.Errors.AddRange((await _validatorFactory.Validate(author))?.Errors);

            if (!validatorResult.IsValid)
            {
                return(CommandResult.ValidationFail(validatorResult));
            }

            try
            {
                var sourceTemplate = await _templateRepository.GetTemplate(command.CloneFromTemplateId);

                if (sourceTemplate == null)
                {
                    return(CommandResult.ValidationFail(nameof(command.CloneFromTemplateId), "Template doesn't exist"));
                }

                var sourceVersion = sourceTemplate.Current;
                if (command.Version != null)
                {
                    if (!int.TryParse(command.Version, out int versionNumber))
                    {
                        return(CommandResult.ValidationFail(nameof(command.Version), $"Invalid version '{command.Version}'"));
                    }

                    sourceVersion = await _templateVersionRepository.GetTemplateVersion(command.CloneFromTemplateId, versionNumber);

                    if (sourceVersion == null)
                    {
                        return(CommandResult.ValidationFail(nameof(command.Version),
                                                            $"Version '{command.Version}' could not be found for template '{command.CloneFromTemplateId}'"));
                    }
                }

                IEnumerable <FundingStreamWithPeriods> available = await GetFundingStreamAndPeriodsWithoutTemplates();

                var match = available.Where(x => x.FundingStream.Id == command.FundingStreamId &&
                                            x.FundingPeriods.Any(p => p.Id == command.FundingPeriodId));
                if (!match.Any())
                {
                    string validationErrorMessage =
                        $"Combination of FundingStreamId [{command.FundingStreamId}] and FundingPeriodId [{command.FundingPeriodId}] not available";
                    _logger.Error(validationErrorMessage);
                    ValidationResult validationResult = new ValidationResult();
                    validationResult.Errors.Add(new ValidationFailure(nameof(command.FundingStreamId), validationErrorMessage));
                    validationResult.Errors.Add(new ValidationFailure(nameof(command.FundingPeriodId), validationErrorMessage));
                    return(new CommandResult
                    {
                        ErrorMessage = validationErrorMessage,
                        ValidationResult = validationResult
                    });
                }

                Guid   templateId   = Guid.NewGuid();
                string templateName = $"{command.FundingStreamId} {command.FundingPeriodId}";
                FundingStreamWithPeriods streamWithPeriods = available.Single(x => x.FundingStream.Id == command.FundingStreamId);
                Template template = new Template
                {
                    TemplateId    = templateId.ToString(),
                    Name          = templateName,
                    Description   = command.Description,
                    FundingStream = streamWithPeriods.FundingStream,
                    FundingPeriod = streamWithPeriods.FundingPeriods.Single(p => p.Id == command.FundingPeriodId)
                };
                template.Current = Map(template,
                                       sourceVersion,
                                       author,
                                       majorVersion: 0,
                                       minorVersion: 1);

                // create new version and save it
                HttpStatusCode templateVersionUpdateResult = await _templateVersionRepository.SaveVersion(template.Current);

                if (!templateVersionUpdateResult.IsSuccess())
                {
                    return(CommandResult.ValidationFail(nameof(command.Version), $"Template version failed to save: {templateVersionUpdateResult}"));
                }

                HttpStatusCode result = await _templateRepository.CreateDraft(template);

                if (result.IsSuccess())
                {
                    await CreateTemplateIndexItem(template, author);

                    return(new CommandResult
                    {
                        Succeeded = true,
                        TemplateId = template.TemplateId
                    });
                }

                string errorMessage = $"Failed to create a new template with name {templateName} in Cosmos. Status code {(int) result}";
                _logger.Error(errorMessage);
                return(CommandResult.Fail(errorMessage));
            }
            catch (Exception ex)
            {
                return(new CommandResult
                {
                    Exception = ex
                });
            }
        }
コード例 #5
0
        public async Task <ValidatedApiResponse <string> > CreateTemplateAsClone(TemplateCreateAsCloneCommand command)
        {
            string url = "templates/build/clone";

            return(await ValidatedPostAsync <string, TemplateCreateAsCloneCommand>(url, command));
        }