Exemplo n.º 1
0
        public async Task <RefreshTrusteesResult> RefreshTrustees(Guid applicationId, Guid userId)
        {
            var organisation = await _organisationApiClient.GetByApplicationId(applicationId);

            var ukprn         = organisation?.OrganisationUkprn?.ToString();
            var charityNumber = organisation?.OrganisationDetails?.CharityNumber;

            if (ukprn == null || charityNumber == null || !int.TryParse(charityNumber, out var charityNumberValue))
            {
                _logger.LogInformation($"RefreshTrusteesService: Refresh failure for applicationId {applicationId}, ukprn: [{ukprn}], Charity number: [{charityNumber}]");

                return(new RefreshTrusteesResult {
                    CharityDetailsNotFound = true, CharityNumber = charityNumber
                });
            }

            var application = await _applicationApiClient.GetApplication(applicationId);

            if (application.ApplicationStatus != ApplicationStatus.InProgress)
            {
                _logger.LogInformation($"RefreshTrusteesService: Refresh failure for applicationId {applicationId} as status '{ApplicationStatus.InProgress}' expected.");
                return(new RefreshTrusteesResult {
                    CharityDetailsNotFound = true, CharityNumber = charityNumber
                });
            }

            Charity charityDetails;

            try
            {
                _logger.LogInformation($"RefreshTrusteesService:  retrieving charity details for applicationId {applicationId}  for charity registration number '{charityNumberValue}'");
                charityDetails = await _outerApiClient.GetCharityDetails(charityNumberValue);
            }
            catch (Exception ex)
            {
                var message =
                    $"RefreshTrusteesService: Exception for Application {applicationId}, failed to get charity details for charity number: [{charityNumberValue}]";
                _logger.LogError(ex, message);
                throw new InvalidOperationException(message, ex);
            }

            if (charityDetails == null || !charityDetails.IsActivelyTrading || charityDetails.Trustees == null || !charityDetails.Trustees.Any())
            {
                _logger.LogInformation($"RefreshTrusteesService:  Failure for applicationId {applicationId}  to retrieve trustee details from charity '{charityNumberValue}'");
                return(new RefreshTrusteesResult {
                    CharityDetailsNotFound = true, CharityNumber = charityNumber
                });
            }

            _logger.LogInformation($"RefreshTrusteesService: updating organisation trustees applicationId {applicationId}");

            try
            {
                var success = await _organisationApiClient.UpdateTrustees(ukprn, charityDetails.Trustees?.ToList(), userId);

                if (!success)
                {
                    throw new InvalidOperationException($"RefreshTrusteesService for Application {applicationId} update trustees failed");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"RefreshTrusteesService for Application {applicationId} update trustees failed: [{ex.Message}]");
            }

            var applicationDetails = new Domain.Roatp.ApplicationDetails {
                CharitySummary = Mapper.Map <CharityCommissionSummary>(charityDetails)
            };
            var trusteesAnswers = RoatpPreambleQuestionBuilder.CreateCharityCommissionWhosInControlQuestions(applicationDetails);

            _logger.LogInformation($"RefreshTrusteesService: resetting page answers for charities for page 80, 86 and section 3.4, applicationId {applicationId}");
            try
            {
                var resetSection1_3_80 = _qnaApiClient.ResetPageAnswersBySequenceAndSectionNumber(applicationId, RoatpWorkflowSequenceIds.YourOrganisation, RoatpWorkflowSectionIds.YourOrganisation.WhosInControl, RoatpWorkflowPageIds.WhosInControl.CharityCommissionTrustees);
                var resetSection1_3_86 = _qnaApiClient.ResetPageAnswersBySequenceAndSectionNumber(applicationId, RoatpWorkflowSequenceIds.YourOrganisation, RoatpWorkflowSectionIds.YourOrganisation.WhosInControl, RoatpWorkflowPageIds.WhosInControl.CharityCommissionTrusteesDob);
                var resetSection3_4    = _qnaApiClient.ResetPageAnswersBySection(applicationId, RoatpWorkflowSequenceIds.CriminalComplianceChecks, RoatpWorkflowSectionIds.CriminalComplianceChecks.CheckOnWhosInControl);
                await Task.WhenAll(resetSection1_3_80, resetSection1_3_86, resetSection3_4);

                _logger.LogInformation($"RefreshTrusteesService: updating page answers for charities, applicationId {applicationId}");
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"RefreshTrusteesService for Application {applicationId} reset qna page answers failed: [{ex.Message}]");
            }

            try
            {
                var response = await _qnaApiClient.UpdatePageAnswers(applicationId,
                                                                     RoatpWorkflowSequenceIds.YourOrganisation, RoatpWorkflowSectionIds.YourOrganisation.WhosInControl,
                                                                     RoatpWorkflowPageIds.WhosInControl.CharityCommissionTrustees, trusteesAnswers.ToList <Answer>());

                if (!response.ValidationPassed)
                {
                    throw new InvalidOperationException($"RefreshTrusteesService for Application {applicationId} update qna page answers failed");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"RefreshTrusteesService for Application {applicationId} update qna page answers failed: [{ex.Message}]");
            }

            return(new RefreshTrusteesResult
            {
                CharityNumber = charityNumber,
                CharityDetailsNotFound = false
            });
        }
        public async Task <IActionResult> RefreshDirectorsPscs(Guid applicationId, string ukprn, string companyNumber)
        {
            try
            {
                _logger.LogInformation($"RefreshDirectorsPscs: Retrieving company details applicationId {applicationId} | Company Number : {companyNumber}");
                var timer = new Stopwatch();
                timer.Start();
                var companyDetails = await _companiesHouseApiClient.GetCompanyDetails(companyNumber);

                var timeToCallCompanyDetails = $"{timer.ElapsedMilliseconds} ms";

                switch (companyDetails.Status)
                {
                case CompaniesHouseSummary.ServiceUnavailable:
                    _logger.LogInformation($"Issue refreshing directors/pscs - applicationId {applicationId} | Company Number : {companyNumber} | Status : Service Unavailable");
                    return(RedirectToAction("CompaniesHouseNotAvailable", "RoatpShutterPages"));

                case CompaniesHouseSummary.CompanyStatusNotFound:
                    _logger.LogInformation(
                        $"Issue refreshing directors/pscs - applicationId {applicationId} | Company Number : {companyNumber} | Status : Company Status Not Found");
                    return(RedirectToAction("CompanyNotFoundRefresh", "RoatpShutterPages", new { companyNumber }));
                }

                if (!CompaniesHouseValidator.CompaniesHouseStatusValid(ukprn, companyDetails.Status, _logger))
                {
                    _logger.LogInformation($"Issue refreshing directors/pscs - applicationId {applicationId} | UKPRN : {ukprn} | Status : Companies House status not valid: {companyDetails.Status}");
                    return(RedirectToAction("CompanyNotFoundRefresh", "RoatpShutterPages", new { companyNumber }));
                }

                var applicationDetails = new Domain.Roatp.ApplicationDetails {
                    CompanySummary = companyDetails
                };

                _logger.LogInformation($"RefreshDirectorsPscs: updating organisation directors/pscs applicationId {applicationId}");

                var success = await _organisationApiClient.UpdateDirectorsAndPscs(ukprn, companyDetails.Directors, companyDetails.PersonsWithSignificantControl, User.GetUserId());

                if (!success)
                {
                    _logger.LogInformation($"Organisation director/pscs update failed - applicationId {applicationId}");
                    return(RedirectToAction("CompaniesHouseNotAvailable", "RoatpShutterPages"));
                }

                var directorsAnswers = RoatpPreambleQuestionBuilder.CreateCompaniesHouseWhosInControlQuestions(applicationDetails);

                _logger.LogInformation($"RefreshDirectorsPscs: resetting page answers for companies, applicationId {applicationId}");
                var resetSection1_3 = _qnaApiClient.ResetPageAnswersBySequenceAndSectionNumber(applicationId, RoatpWorkflowSequenceIds.YourOrganisation, RoatpWorkflowSectionIds.YourOrganisation.WhosInControl, RoatpWorkflowPageIds.WhosInControl.CompaniesHouseStartPage);
                var resetSection3_4 = _qnaApiClient.ResetPageAnswersBySection(applicationId, RoatpWorkflowSequenceIds.CriminalComplianceChecks, RoatpWorkflowSectionIds.CriminalComplianceChecks.CheckOnWhosInControl);
                await Task.WhenAll(resetSection1_3, resetSection3_4);

                _logger.LogInformation($"RefreshDirectorsPscs: updating page answers for companies, applicationId {applicationId}");
                await _qnaApiClient.UpdatePageAnswers(applicationId, RoatpWorkflowSequenceIds.YourOrganisation, RoatpWorkflowSectionIds.YourOrganisation.WhosInControl, RoatpWorkflowPageIds.WhosInControl.CompaniesHouseStartPage, directorsAnswers.ToList <Answer>());

                var timeToDoEntireCall = $"{timer.ElapsedMilliseconds} ms";
                timer.Stop();
                _logger.LogInformation($"RefreshDirectorsPscs: all updates completed for {applicationId} - entire call timespan: {timeToDoEntireCall}, Company call timespan: {timeToCallCompanyDetails}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error when processing directors/pscs - applicationId {applicationId}");
                return(RedirectToAction("CompaniesHouseNotAvailable", "RoatpShutterPages"));
            }

            return(RedirectToAction("StartPage", "RoatpWhosInControlApplication", new { applicationId }));
        }