public void Setup()
        {
            _ukprn      = 228987165;
            _templateId = Guid.NewGuid().ToString();
            _tokens     = new Dictionary <string, string>();
            _tokens.Add("key1", "value1");
            _tokens.Add("key2", "value2");

            _normalUser = new User {
                EmailAddress = "*****@*****.**", IsSuperUser = false, ReceiveNotifications = true
            };
            _superUser = new User {
                EmailAddress = "*****@*****.**", IsSuperUser = true, ReceiveNotifications = true
            };

            _accountUsers = new List <User>();
            _accountUsers.Add(_normalUser);
            _accountUsers.Add(_superUser);

            _accountOrchestrator = new Mock <IAccountOrchestrator>();
            _mediator            = new Mock <IMediator>();

            _accountOrchestrator
            .Setup(x => x.GetAccountUsers(_ukprn))
            .ReturnsAsync(_accountUsers);

            _request = new ProviderEmailRequest
            {
                TemplateId = _templateId,
                Tokens     = _tokens
            };
        }
        public async Task SendEmailToAllProviderRecipients(long providerId, ProviderEmailRequest message)
        {
            List <string> recipients;

            var accountUsers = (await _accountOrchestrator.GetAccountUsers(providerId)).ToList();

            if (message.ExplicitEmailAddresses != null && message.ExplicitEmailAddresses.Any())
            {
                _logger.Info("Explicit recipients requested for email");

                recipients = message.ExplicitEmailAddresses.ToList();
            }
            else
            {
                recipients = accountUsers.Any(u => !u.IsSuperUser) ? accountUsers.Where(x => !x.IsSuperUser).Select(x => x.EmailAddress).ToList()
                    : accountUsers.Select(x => x.EmailAddress).ToList();
            }

            var optedOutList = accountUsers.Where(x => !x.ReceiveNotifications).Select(x => x.EmailAddress).ToList();

            var finalRecipients = recipients.Where(x =>
                                                   !optedOutList.Any(y => x.Equals(y, StringComparison.CurrentCultureIgnoreCase)))
                                  .ToList();

            var commands = finalRecipients.Select(x => new SendNotificationCommand {
                Email = CreateEmailForRecipient(x, message)
            });
            await Task.WhenAll(commands.Select(x => _mediator.Send(x)));

            _logger.Info($"Sent email to {finalRecipients.Count} recipients for ukprn: {providerId}", providerId);
        }
        public async Task Setup()
        {
            _ukprn          = 228987165;
            _emailAddresses = new List <string>
            {
                "*****@*****.**",
                "*****@*****.**"
            };
            _templateId = Guid.NewGuid().ToString();
            _tokens     = new Dictionary <string, string>();
            _tokens.Add("key1", "value1");
            _tokens.Add("key2", "value2");

            _accountOrchestrator = new Mock <IAccountOrchestrator>();
            _mediator            = new Mock <IMediator>();
            _configuration       = new ProviderApprenticeshipsServiceConfiguration {
                CommitmentNotification = new ProviderNotificationConfiguration()
            };

            _accountOrchestrator
            .Setup(x => x.GetAccountUsers(_ukprn))
            .ReturnsAsync(_emailAddresses.Select(x => new User {
                EmailAddress = x, ReceiveNotifications = false
            }));

            _request = new ProviderEmailRequest
            {
                TemplateId = _templateId,
                Tokens     = _tokens
            };

            _sut = new EmailOrchestrator(_accountOrchestrator.Object, _mediator.Object, Mock.Of <IProviderCommitmentsLogger>());
            await _sut.SendEmailToAllProviderRecipients(_ukprn, _request);
        }
        private ProviderEmailRequest BuildEmailRequest(GetCohortSummaryQueryResult cohortSummary)
        {
            var request = new ProviderEmailRequest();

            request.ExplicitEmailAddresses = new List <string>();
            request.Tokens = new Dictionary <string, string>();

            if (!string.IsNullOrWhiteSpace(cohortSummary.LastUpdatedByProviderEmail))
            {
                request.ExplicitEmailAddresses.Add(cohortSummary.LastUpdatedByProviderEmail);
            }

            request.Tokens.Add("cohort_reference", cohortSummary.CohortReference);
            request.Tokens.Add("type", cohortSummary.LastAction == LastAction.Approve ? "approval" : "review");

            if (cohortSummary.IsFundedByTransfer)
            {
                request.TemplateId = "ProviderTransferCommitmentNotification";
                request.Tokens.Add("employer_name", cohortSummary.LegalEntityName);
            }
            else
            {
                request.TemplateId = "ProviderCommitmentNotification";
            }

            return(request);
        }
 private Email CreateEmailForRecipient(string recipient, ProviderEmailRequest source)
 {
     return(new Email
     {
         RecipientsAddress = recipient,
         TemplateId = source.TemplateId,
         Tokens = new Dictionary <string, string>(source.Tokens),
         ReplyToAddress = "*****@*****.**",
         Subject = "x",
         SystemId = "x"
     });
 }
        public async Task Handle(SendEmailToProviderCommand message, IMessageHandlerContext context)
        {
            try
            {
                var providerEmailRequest = new ProviderEmailRequest
                {
                    TemplateId             = message.Template,
                    Tokens                 = message.Tokens,
                    ExplicitEmailAddresses = string.IsNullOrWhiteSpace(message.EmailAddress)
                        ? new List <string>()
                        : new List <string> {
                        message.EmailAddress
                    }
                };

                await _pasAccountApi.SendEmailToAllProviderRecipients(message.ProviderId, providerEmailRequest);
            }
            catch (Exception e)
            {
                _logger.LogError($"Error processing {nameof(SendEmailToProviderCommand)}", e);
                throw;
            }
        }
Example #7
0
        private Task SendEmails(long providerId, IList <ProviderAlertSummary> alertSummaries)
        {
            var alert = alertSummaries.First(m => m.ProviderId == providerId);

            var email = new ProviderEmailRequest
            {
                TemplateId = "ProviderAlertSummaryNotification2",
                Tokens     =
                    new Dictionary <string, string>
                {
                    { "total_count_text", alert.TotalCount.ToString() },
                    { "need_needs", alert.TotalCount > 1 ? "need" : "needs" },
                    { "changes_for_review", ChangesForReviewText(alert.ChangesForReview) },
                    { "mismatch_changes", GetMismatchText(alert.DataMismatchCount) },
                    {
                        "link_to_mange_apprenticeships",
                        $"{providerId}/apprentices/manage/all?RecordStatus=ChangesForReview&RecordStatus=IlrDataMismatch&RecordStatus=ChangeRequested"
                    }
                }
            };

            return(_providerAccountClient.SendEmailToAllProviderRecipients(providerId, email));
        }
Example #8
0
        public SendUpdatedPermissionsNotificationCommandHandlerTestsFixture()
        {
            UnitOfWorkContext = new UnitOfWorkContext();

            CreateDb();
            CreateDefaultEntities();

            Client  = new Mock <IPasAccountApiClient>();
            Handler = new SendUpdatedPermissionsNotificationCommandHandler(Client.Object, new Lazy <ProviderRelationshipsDbContext>(() => Db));

            Command = new SendUpdatedPermissionsNotificationCommand(
                ukprn: 299792458,
                accountLegalEntityId: 12345,
                new HashSet <Operation>(),
                new HashSet <Operation>());

            Client
            .Setup(c => c.SendEmailToAllProviderRecipients(Provider.Ukprn, It.IsAny <ProviderEmailRequest>()))
            .Callback((long ukprn, ProviderEmailRequest provEmail) =>
            {
                ResultEmailRequest = provEmail;
            })
            .Returns(Task.FromResult(0));
        }
Example #9
0
        public async Task <IHttpActionResult> SendEmailToAllProviderRecipients(long ukprn, ProviderEmailRequest request)
        {
            try
            {
                await _emailOrchestrator.SendEmailToAllProviderRecipients(ukprn, request);

                _logger.Info($"Email template '{request?.TemplateId}' sent to Provider recipients successfully", ukprn);
                return(Ok());
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Error sending email template '{request?.TemplateId}' to Provider recipients", ukprn);
                throw;
            }
        }
 public async Task SendEmailToAllProviderRecipients(long ukprn, ProviderEmailRequest message)
 {
     await _httpClient.PostAsync(Path.Combine(GetBaseUrl(), $"api/email/{ukprn}/send"), message);
 }
 public async Task SendProviderEmailNotifications(long ukprn, ProviderEmailRequest request)
 {
     await _accountApiClient.SendEmailToAllProviderRecipients(ukprn, request);
 }
 public Task SendEmailToAllProviderRecipients(long providerId, ProviderEmailRequest message, CancellationToken cancellationToken)
 {
     return(_httpClient.PostAsJson($"api/email/{providerId}/send", message, cancellationToken));
 }