Beispiel #1
0
        public async Task <IEnumerable <LegalEntityModel> > Get(string accountId)
        {
            try
            {
                var id  = _hashingService.DecodeValue(accountId);
                var url = OuterApiRoutes.LegalEntities.GetLegalEntities(id);

                using var response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);

                if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return(new List <LegalEntityModel>());
                }

                response.EnsureSuccessStatusCode();

                var data = await JsonSerializer.DeserializeAsync <IEnumerable <LegalEntityDto> >(await response.Content.ReadAsStreamAsync(), options : new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });

                return(data.ToLegalEntityModel(_hashingService));
            }
            catch (IndexOutOfRangeException) // invalid hashed id
            {
                return(new List <LegalEntityModel>());
            }
        }
Beispiel #2
0
        public async Task <Apprenticeship> MapFromAsync(ApprenticeshipViewModel viewModel)
        {
            var apprenticeship = new Apprenticeship
            {
                CommitmentId = _hashingService.DecodeValue(viewModel.HashedCommitmentId),
                Id           = string.IsNullOrWhiteSpace(viewModel.HashedApprenticeshipId) ? 0L : _hashingService.DecodeValue(viewModel.HashedApprenticeshipId),
                FirstName    = viewModel.FirstName,
                LastName     = viewModel.LastName,
                DateOfBirth  = viewModel.DateOfBirth.DateTime,
                NINumber     = viewModel.NINumber,
                ULN          = viewModel.ULN,
                Cost         = viewModel.Cost == null ? default(decimal?) : decimal.Parse(viewModel.Cost),
                StartDate    = viewModel.StartDate.DateTime,
                EndDate      = viewModel.EndDate.DateTime,
                ProviderRef  = viewModel.ProviderRef,
                EmployerRef  = viewModel.EmployerRef
            };

            if (!string.IsNullOrWhiteSpace(viewModel.TrainingCode))
            {
                var training = await GetTrainingProgramme(viewModel.TrainingCode);

                apprenticeship.TrainingType = training is Standard ? TrainingType.Standard : TrainingType.Framework;
                apprenticeship.TrainingCode = viewModel.TrainingCode;
                apprenticeship.TrainingName = training.Title;
            }

            return(apprenticeship);
        }
        public async Task Cancel(string accountLegalEntityId, IEnumerable <ApprenticeshipIncentiveModel> apprenticeshipIncentives,
                                 string hashedAccountId, string emailAddress)
        {
            var decodedAccountLegalEntityId = _hashingService.DecodeValue(accountLegalEntityId);

            var url            = $"withdrawals";
            var serviceRequest = new ServiceRequest()
            {
                TaskId          = Guid.NewGuid().ToString(),
                TaskCreatedDate = DateTime.UtcNow
            };

            foreach (var apprenticeshipIncentive in apprenticeshipIncentives)
            {
                var request = new WithdrawRequest(
                    WithdrawalType.Employer,
                    decodedAccountLegalEntityId,
                    apprenticeshipIncentive.Uln,
                    serviceRequest,
                    _hashingService.DecodeValue(hashedAccountId),
                    emailAddress
                    );

                using var response = await _client.PostAsJsonAsync(url, request);

                response.EnsureSuccessStatusCode();
            }
        }
Beispiel #4
0
        protected override async Task HandleCore(SignEmployerAgreementCommand message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            var owner = await _membershipRepository.GetCaller(message.HashedAccountId, message.ExternalUserId);

            if (owner == null || owner.Role != Role.Owner)
            {
                throw new UnauthorizedAccessException();
            }

            var agreementId = _hashingService.DecodeValue(message.HashedAgreementId);

            var signedAgreementDetails = new Models.EmployerAgreement.SignEmployerAgreement
            {
                SignedDate   = message.SignedDate,
                AgreementId  = agreementId,
                SignedById   = owner.UserId,
                SignedByName = $"{owner.FirstName} {owner.LastName}"
            };

            await _employerAgreementRepository.SignAgreement(signedAgreementDetails);

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            await AddAuditEntry(message, accountId, agreementId);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(agreementId);

            await _employerAgreementRepository.EvaluateEmployerLegalEntityAgreementStatus(accountId, agreement.LegalEntityId);

            var hashedLegalEntityId = _hashingService.HashValue((long)agreement.LegalEntityId);

            var agreementEvent = _agreementEventFactory.CreateSignedEvent(message.HashedAccountId, hashedLegalEntityId, message.HashedAgreementId);

            var genericEvent = _genericEventFactory.Create(agreementEvent);

            await _mediator.SendAsync(new PublishGenericEventCommand { Event = genericEvent });

            var commitments = await _commitmentService.GetEmployerCommitments(accountId);

            var accountHasCommitments = commitments?.Any() ?? false;

            await PublishAgreementSignedMessage(accountId, agreement.LegalEntityId, agreement.LegalEntityName, agreementId, accountHasCommitments, owner.FullName(), owner.UserRef);

            await _agreementService.RemoveFromCacheAsync(accountId);
        }
        private async Task <bool> UniqueUln(ApprenticeshipViewModel viewModel, string uln, PropertyValidatorContext arg3, CancellationToken arg4)
        {
            var id           = viewModel.HashedApprenticeshipId == null ? 0 : _hashingService.DecodeValue(viewModel.HashedApprenticeshipId);
            var commitmentId = _hashingService.DecodeValue(viewModel.HashedCommitmentId);

            var cohort = await _mediator.Send(new GetCommitmentQueryRequest
            {
                CommitmentId = commitmentId,
                ProviderId   = viewModel.ProviderId
            });

            return(cohort.Commitment.Apprenticeships.All(existing => existing.Id == id || existing.ULN != uln));
        }
Beispiel #6
0
        public async Task <DataLockMismatchViewModel> GetApprenticeshipMismatchDataLock(long providerId, string hashedApprenticeshipId)
        {
            var apprenticeshipId = _hashingService.DecodeValue(hashedApprenticeshipId);

            _logger.Info($"Getting apprenticeship datalock for provider: {providerId}", providerId: providerId, apprenticeshipId: apprenticeshipId);

            var datalockSummary = await _mediator.Send(new GetApprenticeshipDataLockSummaryQueryRequest
            {
                ProviderId       = providerId,
                ApprenticeshipId = apprenticeshipId
            });

            var data = await _mediator.Send(new GetApprenticeshipQueryRequest
            {
                ProviderId       = providerId,
                ApprenticeshipId = apprenticeshipId
            });

            var commitmentData = await _mediator.Send(new GetCommitmentQueryRequest
            {
                ProviderId   = providerId,
                CommitmentId = data.Apprenticeship.CommitmentId
            });

            var priceHistory = await _mediator.Send(new GetApprenticeshipPriceHistoryQueryRequest
            {
                ProviderId       = providerId,
                ApprenticeshipId = apprenticeshipId
            });

            var datalockSummaryViewModel = await _dataLockMapper.MapDataLockSummary(datalockSummary.DataLockSummary, data.Apprenticeship.HasHadDataLockSuccess);

            var dasRecordViewModel = _apprenticeshipMapper.MapApprenticeship(data.Apprenticeship, commitmentData.Commitment);
            var priceDataLocks     = datalockSummaryViewModel
                                     .DataLockWithCourseMismatch
                                     .Concat(datalockSummaryViewModel.DataLockWithOnlyPriceMismatch)
                                     .Where(m => m.DataLockErrorCode.HasFlag(DataLockErrorCode.Dlock07))
                                     .OrderBy(x => x.IlrEffectiveFromDate);

            return(new DataLockMismatchViewModel
            {
                ProviderId = providerId,
                HashedApprenticeshipId = hashedApprenticeshipId,
                DasApprenticeship = dasRecordViewModel,
                DataLockSummaryViewModel = datalockSummaryViewModel,
                EmployerName = data.Apprenticeship.LegalEntityName,
                PriceDataLocks = _dataLockMapper.MapPriceDataLock(priceHistory.History, priceDataLocks),
                CourseDataLocks = _dataLockMapper.MapCourseDataLock(dasRecordViewModel, datalockSummaryViewModel.DataLockWithCourseMismatch, data.Apprenticeship, priceHistory.History)
            });
        }
        private async Task <IList <Types.Commitment.TransferRequestSummary> > GetTransferRequestsForSender(string hashedTransferSenderId)
        {
            var transferSenderId = _hashingService.DecodeValue(hashedTransferSenderId);

            _logger.Trace($"Getting transfer requests employer sender account {transferSenderId}", accountId: transferSenderId);

            var response = await _mediator.SendAsync(new GetTransferRequestsForSenderRequest
            {
                TransferSenderAccountId = transferSenderId
            });

            _logger.Info($"Retrieved transfer requests for employer sender account {transferSenderId}. {response.Data.Count} transfer requests found", accountId: transferSenderId);

            return(_transferRequestMapper.MapFrom(response.Data, Commitment.TransferType.AsSender).ToList());
        }
        public async Task <Apprenticeship> MapApprenticeship(ApprenticeshipViewModel vm)
        {
            var id = string.IsNullOrEmpty(vm.HashedApprenticeshipId)
                ? 0
                : _hashingService.DecodeValue(vm.HashedApprenticeshipId);

            var apprenticeship = new Apprenticeship
            {
                Id              = id,
                CommitmentId    = _hashingService.DecodeValue(vm.HashedCommitmentId),
                ProviderId      = vm.ProviderId,
                FirstName       = vm.FirstName,
                LastName        = vm.LastName,
                DateOfBirth     = vm.DateOfBirth.DateTime,
                NINumber        = vm.NINumber,
                ULN             = vm.ULN,
                Cost            = vm.Cost.AsNullableDecimal(),
                StartDate       = vm.StartDate.DateTime,
                EndDate         = vm.EndDate.DateTime,
                PaymentStatus   = vm.PaymentStatus,
                AgreementStatus = vm.AgreementStatus,
                ProviderRef     = vm.ProviderRef,
                EmployerRef     = vm.EmployerRef,
                ReservationId   = vm.ReservationId
            };

            if (!string.IsNullOrWhiteSpace(vm.CourseCode))
            {
                var training = await GetTrainingProgramme(vm.CourseCode);

                if (training != null)
                {
                    apprenticeship.TrainingType = int.TryParse(training.CourseCode, out _) ? CommitmentTrainingType.Standard : CommitmentTrainingType.Framework;
                    apprenticeship.TrainingCode = vm.CourseCode;
                    apprenticeship.TrainingName = training.Name;
                }
                else
                {
                    apprenticeship.TrainingType = vm.CourseType;
                    apprenticeship.TrainingCode = vm.CourseCode;
                    apprenticeship.TrainingName = vm.CourseName;

                    _logger.Warn($"Apprentice training course has expired. TrainingName: {apprenticeship.TrainingName}, TrainingCode: {apprenticeship.TrainingCode}, Employer Ref: {apprenticeship.EmployerRef}, ApprenticeshipId: {apprenticeship.Id}, Apprenticeship ULN: {apprenticeship.ULN}");
                }
            }

            return(apprenticeship);
        }
        public async Task <OrchestratorResponse <SummaryUnsubscribeViewModel> > Unsubscribe(
            string userRef,
            string hashedAccountId,
            string settingUrl)
        {
            return(await CheckUserAuthorization(
                       async() =>
            {
                var accountId = _hashingService.DecodeValue(hashedAccountId);
                var settings = await _mediator.SendAsync(new GetUserNotificationSettingsQuery
                {
                    UserRef = userRef
                });

                var userNotificationSettings = settings.NotificationSettings.SingleOrDefault(m => m.AccountId == accountId);

                if (userNotificationSettings == null)
                {
                    throw new InvalidStateException($"Cannot find user settings for user {userRef} in account {accountId}");
                }

                if (userNotificationSettings.ReceiveNotifications)
                {
                    await _mediator.SendAsync(
                        new UnsubscribeNotificationCommand
                    {
                        UserRef = userRef,
                        AccountId = accountId,
                        NotificationSettingUrl = settingUrl
                    });

                    _logger.Info("Unsubscribed from alerts for user {userRef} in account {accountId}");
                }
                else
                {
                    _logger.Info("Already unsubscribed from alerts for user {userRef} in account {accountId}");
                }

                return new OrchestratorResponse <SummaryUnsubscribeViewModel>
                {
                    Data = new SummaryUnsubscribeViewModel
                    {
                        AlreadyUnsubscribed = !userNotificationSettings.ReceiveNotifications,
                        AccountName = userNotificationSettings.Name
                    }
                };
            }, hashedAccountId, userRef));
        }
Beispiel #10
0
        public async Task <IEnumerable <PayeView> > GetPayeSchemsWithEnglishFractionForHashedAccountId(string hashedAccountId)
        {
            long accountId;

            try
            {
                accountId = _hashingService.DecodeValue(hashedAccountId);
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidRequestException(
                          new Dictionary <string, string>
                {
                    {
                        nameof(hashedAccountId), "Hashed account ID cannot be decoded."
                    }
                }
                          );
            }

            var payeSchemes = await _payeRepository.GetPayeSchemesByAccountId(accountId);

            if (payeSchemes.Count == 0)
            {
                return(payeSchemes);
            }

            await AddEnglishFractionsToPayeSchemes(accountId,
                                                   payeSchemes);

            return(payeSchemes);
        }
        public async Task <GetTransferRequestsResponse> Handle(GetTransferRequestsQuery message)
        {
            var transferRequests = await _employerCommitmentApi.GetTransferRequests(message.AccountHashedId);

            var accountIds = transferRequests
                             .SelectMany(r => new[] { r.HashedSendingEmployerAccountId, r.HashedReceivingEmployerAccountId })
                             .Select(h => _hashingService.DecodeValue(h))
                             .ToList();

            var accounts = await _db.Value.Accounts
                           .Where(a => accountIds.Contains(a.Id))
                           .ProjectTo <AccountDto>(_configurationProvider)
                           .ToDictionaryAsync(a => a.HashedId);

            var transferRequestsData = transferRequests
                                       .Select(r => new TransferRequestDto
            {
                CreatedDate             = r.CreatedOn,
                ReceiverAccount         = accounts[r.HashedReceivingEmployerAccountId],
                SenderAccount           = accounts[r.HashedSendingEmployerAccountId],
                Status                  = r.Status,
                TransferCost            = r.TransferCost,
                TransferRequestHashedId = r.HashedTransferRequestId
            })
                                       .OrderBy(r => r.ReceiverAccount.Id == message.AccountId.Value ? r.SenderAccount.Name : r.ReceiverAccount.Name)
                                       .ThenBy(r => r.CreatedDate)
                                       .ToList();

            return(new GetTransferRequestsResponse
            {
                TransferRequests = transferRequestsData
            });
        }
        public async Task <GetReservationsResponse> Handle(GetReservationsRequest message)
        {
            var validationResult = _validator.Validate(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            long accountId = _hashingService.DecodeValue(message.HashedAccountId);

            _logger.Info($"Getting reservations for hashed account id {message.HashedAccountId}");

            try
            {
                return(new GetReservationsResponse
                {
                    Reservations = await _service.Get(accountId)
                });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Failed to get Reservations for {message.HashedAccountId}");
                return(new GetReservationsResponse
                {
                    HasFailed = true
                });
            }
        }
        public async Task <GetNextUnsignedEmployerAgreementResponse> Handle(GetNextUnsignedEmployerAgreementRequest message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            var pendingAgreementId = await _db.Value.AccountLegalEntities
                                     .Where(x => x.AccountId == accountId && x.PendingAgreementId != null)
                                     .Select(x => x.PendingAgreementId).FirstOrDefaultAsync();

            return(new GetNextUnsignedEmployerAgreementResponse
            {
                HashedAgreementId = pendingAgreementId.HasValue ? _hashingService.HashValue(pendingAgreementId.Value) : null
            });
        }
        public async Task <GetEmployerAgreementByIdResponse> Handle(GetEmployerAgreementByIdRequest message)
        {
            var validationResult = _validator.Validate(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            var agreementId = _hashingService.DecodeValue(message.HashedAgreementId);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(agreementId);

            if (agreement == null)
            {
                throw new InvalidRequestException(new Dictionary <string, string> {
                    { "Agreement", "The agreement could not be found" }
                });
            }

            agreement.HashedAgreementId = message.HashedAgreementId;

            return(new GetEmployerAgreementByIdResponse
            {
                EmployerAgreement = agreement
            });
        }
        protected override async Task HandleCore(RenameEmployerAccountCommand message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            var account = await _accountRepository.GetAccountById(accountId);

            var accountPreviousName = account.Name;

            await _accountRepository.RenameAccount(accountId, message.NewName);

            var owner = await _membershipRepository.GetCaller(message.HashedAccountId, message.ExternalUserId);

            await AddAuditEntry(owner.Email, accountId, message.NewName);

            await NotifyAccountRenamed(message.HashedAccountId);

            await PublishAccountRenamedMessage(
                accountId, accountPreviousName, message.NewName, owner.FullName(), owner.UserRef);
        }
Beispiel #16
0
        public async Task <GetEmployerAgreementPdfResponse> Handle(GetEmployerAgreementPdfRequest message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var employerAgreementId = _hashingService.DecodeValue(message.HashedLegalAgreementId);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(employerAgreementId);

            var file = await _pdfService.SubsituteValuesForPdf($"{agreement.TemplatePartialViewName}.pdf");


            return(new GetEmployerAgreementPdfResponse {
                FileStream = file
            });
        }
        protected override async Task HandleCore(AddPayeToAccountCommand message)
        {
            await ValidateMessage(message);

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            await _payeRepository.AddPayeToAccount(
                new Paye
            {
                AccessToken  = message.AccessToken,
                RefreshToken = message.RefreshToken,
                AccountId    = accountId,
                EmpRef       = message.Empref,
                RefName      = message.EmprefName,
                Aorn         = message.Aorn
            }
                );

            var userResponse = await _mediator.SendAsync(new GetUserByRefQuery { UserRef = message.ExternalUserId });

            await AddAuditEntry(message, accountId);

            await AddPayeScheme(message.Empref, accountId, userResponse.User.FullName, userResponse.User.UserRef, message.Aorn, message.EmprefName, userResponse.User.CorrelationId);

            await NotifyPayeSchemeAdded(message.HashedAccountId, message.Empref);
        }
        public async Task <GetEmployerAgreementResponse> Handle(GetEmployerAgreementRequest message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            var agreementId       = _hashingService.DecodeValue(message.AgreementId);
            var employerAgreement = await _database.Value.Agreements.ProjectTo <AgreementDto>(_configurationProvider)
                                    .SingleOrDefaultAsync(x => x.Id.Equals(agreementId));

            if (employerAgreement == null)
            {
                return(new GetEmployerAgreementResponse());
            }

            employerAgreement.HashedAccountId     = _hashingService.HashValue(employerAgreement.AccountId);
            employerAgreement.HashedAgreementId   = _hashingService.HashValue(employerAgreement.Id);
            employerAgreement.HashedLegalEntityId = _hashingService.HashValue(employerAgreement.LegalEntityId);

            if (employerAgreement.StatusId != EmployerAgreementStatus.Signed)
            {
                employerAgreement.SignedByName = GetUserFullName(message.ExternalUserId);
            }

            return(new GetEmployerAgreementResponse
            {
                EmployerAgreement = employerAgreement
            });
        }
        public async Task <FindEmployerAccountLevyDeclarationTransactionsResponse> Handle(FindEmployerAccountLevyDeclarationTransactionsQuery message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var accountId    = _hashingService.DecodeValue(message.HashedAccountId);
            var transactions = await _dasLevyService.GetAccountLevyTransactionsByDateRange <LevyDeclarationTransactionLine>
                                   (accountId, message.FromDate, message.ToDate, message.ExternalUserId);

            //var transactionDetailSummaries = data.Select(item => new LevyDeclarationTransactionLine
            //{
            //    Amount = item.Amount,
            //    EmpRef = item.EmpRef,
            //    TopUp = item.TopUp,
            //    TransactionDate = item.TransactionDate,
            //    EnglishFraction = item.EnglishFraction,
            //    LineAmount = item.LineAmount
            //}).ToList();

            return(new FindEmployerAccountLevyDeclarationTransactionsResponse
            {
                Transactions = transactions.ToList(),
                Total = transactions.Sum(c => c.LineAmount)
            });
        }
        private static long GetCurrentAccountId(IHashingService hashingService)
        {
            var hashedAccountId = ScenarioContext.Current["HashedAccountId"] as string;
            var accountId       = hashingService.DecodeValue(hashedAccountId);

            return(accountId);
        }
Beispiel #21
0
        public async Task <GetApprenticeshipsResponse> Handle(GetApprenticeshipsRequest message)
        {
            var validationResult = _validator.Validate(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            long accountId = _hashingService.DecodeValue(message.HashedAccountId);

            try
            {
                return(new GetApprenticeshipsResponse
                {
                    Apprenticeships = await _commitmentV2Service.GetApprenticeships(accountId)
                });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Failed to get Cohorts for {message.HashedAccountId}");
                return(new GetApprenticeshipsResponse
                {
                    HasFailed = true
                });
            }
        }
Beispiel #22
0
        public async Task <SignEmployerAgreementCommandResponse> Handle(SignEmployerAgreementCommand message)
        {
            await ValidateRequest(message);

            var owner = await VerifyUserIsAccountOwner(message);

            var userResponse = await _mediator.SendAsync(new GetUserByRefQuery { UserRef = message.ExternalUserId });

            var agreementId = _hashingService.DecodeValue(message.HashedAgreementId);

            await SignAgreement(message, agreementId, owner);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(agreementId);

            var hashedLegalEntityId = _hashingService.HashValue((long)agreement.LegalEntityId);

            await Task.WhenAll(
                AddAuditEntry(message, agreement.AccountId, agreementId),
                _employerAgreementRepository.SetAccountLegalEntityAgreementDetails(agreement.AccountLegalEntityId, null, null, agreement.Id, agreement.VersionNumber),
                PublishEvents(message, hashedLegalEntityId, agreement, owner, userResponse.User.CorrelationId)
                );

            return(new SignEmployerAgreementCommandResponse
            {
                AgreementType = agreement.AgreementType,
                LegalEntityName = agreement.LegalEntityName
            });
        }
        public async Task <GetAccountEmployerAgreementsResponse> Handle(GetAccountEmployerAgreementsRequest message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            var agreements = await _db.Value.AccountLegalEntities
                             .WithSignedOrPendingAgreementsForAccount(accountId)
                             .ProjectTo <EmployerAgreementStatusDto>(_configurationProvider)
                             .ToListAsync();

            agreements = agreements.PostFixEmployerAgreementStatusDto(_hashingService, accountId).ToList();

            return(new GetAccountEmployerAgreementsResponse
            {
                EmployerAgreements = agreements
            });
        }
        public async Task <FindAccountProviderPaymentsResponse> Handle(FindAccountProviderPaymentsQuery message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var accountId    = _hashingService.DecodeValue(message.HashedAccountId);
            var transactions = await _dasLevyService.GetAccountProviderPaymentsByDateRange <PaymentTransactionLine>
                                   (accountId, message.UkPrn, message.FromDate, message.ToDate);

            if (!transactions.Any())
            {
                throw new NotFoundException("No transactions found.");
            }

            var firstTransaction = transactions.First();

            return(new FindAccountProviderPaymentsResponse
            {
                ProviderName = firstTransaction.ProviderName,
                TransactionDate = firstTransaction.TransactionDate,
                DateCreated = firstTransaction.DateCreated,
                Transactions = transactions.ToList(),
                Total = transactions.Sum(c => c.LineAmount)
            });
        }
Beispiel #25
0
        public async Task <List <LevySchemeDeclarationUpdatedMessage> > LevyForPeriod(string hashedAccountId, string payrollYear, short payrollMonth)
        {
            var accountId = _hashingService.DecodeValue(hashedAccountId);

            var levydeclarations = await _databaseService.GetAccountLevyDeclarations(accountId, payrollYear, payrollMonth);

            if (levydeclarations == null)
            {
                _logger.Debug($"Account API client returned null for GetLevyDeclarations for account {hashedAccountId}, period: {payrollYear}, {payrollMonth}");
                return(null);
            }

            _logger.Info($"Got {levydeclarations.Count} levy declarations for employer {hashedAccountId}.");
            var validLevyDeclarations = levydeclarations
                                        .OrderByDescending(ld => ld.SubmissionDate)
                                        .ToList();

            _logger.Info($"Got {validLevyDeclarations.Count} levy declarations for period {payrollYear}, {payrollMonth} for employer {hashedAccountId}.");

            return(validLevyDeclarations.Select(levy => new LevySchemeDeclarationUpdatedMessage
            {
                SubmissionId = levy.SubmissionId,
                AccountId = accountId,
                CreatedAt = levy.CreatedDate,
                CreatedDate = levy.CreatedDate,
                EmpRef = levy.EmpRef,
                PayrollMonth = levy.PayrollMonth,
                PayrollYear = levy.PayrollYear,
                LevyDeclaredInMonth = levy.Amount,
                SubmissionDate = levy.SubmissionDate,
            }).ToList());
        }
        protected override async Task HandleCore(RemoveLegalEntityCommand message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            if (validationResult.IsUnauthorized)
            {
                _logger.Info($"User {message.UserId} tried to remove {message.HashedLegalAgreementId} from Account {message.HashedAccountId}");
                throw new UnauthorizedAccessException();
            }

            var accountId        = _hashingService.DecodeValue(message.HashedAccountId);
            var legalAgreementId = _hashingService.DecodeValue(message.HashedLegalAgreementId);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(legalAgreementId);

            await _employerAgreementRepository.RemoveLegalEntityFromAccount(legalAgreementId);

            await _agreementService.RemoveFromCacheAsync(accountId);

            await AddAuditEntry(accountId, message.HashedLegalAgreementId);

            await CreateEvent(message.HashedLegalAgreementId);

            // it appears that an agreement is created whenever we create a legal entity, so there should always be an agreement associated with a legal entity
            if (agreement != null)
            {
                var agreementSigned = agreement.Status == EmployerAgreementStatus.Signed;
                var caller          = await _membershipRepository.GetCaller(accountId, message.UserId);

                var createdByName = caller.FullName();

                await PublishLegalEntityRemovedMessage(
                    accountId,
                    legalAgreementId,
                    agreementSigned,
                    createdByName,
                    agreement.LegalEntityId,
                    agreement.LegalEntityName,
                    agreement.AccountLegalEntityId,
                    message.UserId);
            }
        }
Beispiel #27
0
        public async Task <GetInvitationResponse> Handle(GetInvitationRequest message)
        {
            var invitation = await _invitationRepository.GetView(_hashingService.DecodeValue(message.Id));

            return(new GetInvitationResponse
            {
                Invitation = invitation
            });
        }
        public async Task <GetAccountTransactionSummaryResponse> Handle(GetAccountTransactionSummaryRequest message)
        {
            var accountId = _hashingService.DecodeValue(message.HashedAccountId);
            var result    = await _transactionRepository.GetAccountTransactionSummary(accountId);

            return(new GetAccountTransactionSummaryResponse {
                Data = result
            });
        }
        public async Task <CreateLegalEntityCommandResponse> Handle(CreateLegalEntityCommand message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }
            if (validationResult.IsUnauthorized)
            {
                throw new UnauthorizedAccessException();
            }

            var owner = await _membershipRepository.GetCaller(message.HashedAccountId, message.ExternalUserId);

            var ownerExternalUserId = Guid.Parse(owner.UserRef);

            var createParams = new CreateLegalEntityWithAgreementParams
            {
                AccountId              = owner.AccountId,
                Name                   = message.Name,
                Status                 = message.Status,
                Code                   = string.IsNullOrEmpty(message.Code) ? Guid.NewGuid().ToString() : message.Code,
                DateOfIncorporation    = message.DateOfIncorporation,
                PublicSectorDataSource = message.PublicSectorDataSource,
                Source                 = message.Source,
                Address                = message.Address,
                Sector                 = message.Sector
            };

            var agreementView = await _accountRepository.CreateLegalEntityWithAgreement(createParams);

            agreementView.HashedAgreementId = _hashingService.HashValue(agreementView.Id);

            await CreateAuditEntries(owner, agreementView);

            await NotifyLegalEntityCreated(message.HashedAccountId, agreementView.LegalEntityId);

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            await EvaluateEmployerLegalEntityAgreementStatus(owner.AccountId, agreementView.LegalEntityId);

            agreementView.AccountLegalEntityPublicHashedId = _accountLegalEntityPublicHashingService.HashValue(agreementView.AccountLegalEntityId);

            await PublishLegalEntityAddedMessage(accountId, agreementView.Id, createParams.Name, owner.FullName(), agreementView.LegalEntityId,
                                                 agreementView.AccountLegalEntityId, agreementView.AccountLegalEntityPublicHashedId, message.Code, message.Address, message.Source, ownerExternalUserId);

            await PublishAgreementCreatedMessage(accountId, agreementView.Id, createParams.Name, owner.FullName(), agreementView.LegalEntityId, ownerExternalUserId);

            await _agreementService.RemoveFromCacheAsync(accountId);

            return(new CreateLegalEntityCommandResponse
            {
                AgreementView = agreementView
            });
        }
Beispiel #30
0
        protected override async Task HandleCore(SignEmployerAgreementCommand message)
        {
            var validationResult = await _validator.ValidateAsync(message);

            if (!validationResult.IsValid())
            {
                throw new InvalidRequestException(validationResult.ValidationDictionary);
            }

            var owner = await _membershipRepository.GetCaller(message.HashedAccountId, message.ExternalUserId);

            if (owner == null || (Role)owner.RoleId != Role.Owner)
            {
                throw new UnauthorizedAccessException();
            }

            var agreementId = _hashingService.DecodeValue(message.HashedAgreementId);

            var signedAgreementDetails = new Domain.Models.EmployerAgreement.SignEmployerAgreement
            {
                SignedDate   = message.SignedDate,
                AgreementId  = agreementId,
                SignedById   = owner.UserId,
                SignedByName = $"{owner.FirstName} {owner.LastName}"
            };

            await _employerAgreementRepository.SignAgreement(signedAgreementDetails);

            var accountId = _hashingService.DecodeValue(message.HashedAccountId);

            await AddAuditEntry(message, accountId, agreementId);

            var agreement = await _employerAgreementRepository.GetEmployerAgreement(agreementId);

            var hashedLegalEntityId = _hashingService.HashValue(agreement.LegalEntityId);

            var agreementEvent = _agreementEventFactory.CreateSignedEvent(message.HashedAccountId, hashedLegalEntityId,
                                                                          message.HashedAgreementId);

            var genericEvent = _genericEventFactory.Create(agreementEvent);

            await _mediator.SendAsync(new PublishGenericEventCommand { Event = genericEvent });
        }