public When_ReferralEmailService_Is_Called_To_Send_Provider_Email() { var datetimeProvider = Substitute.For <IDateTimeProvider>(); _backgroundProcessHistoryRepository = Substitute.For <IRepository <BackgroundProcessHistory> >(); var mapper = Substitute.For <IMapper>(); var opportunityItemRepository = Substitute.For <IRepository <OpportunityItem> >(); _emailService = Substitute.For <IEmailService>(); _opportunityRepository = Substitute.For <IOpportunityRepository>(); _backgroundProcessHistoryRepository.GetSingleOrDefaultAsync( Arg.Any <Expression <Func <BackgroundProcessHistory, bool> > >()).Returns(new BackgroundProcessHistory { Id = 1, ProcessType = BackgroundProcessType.ProviderReferralEmail.ToString(), Status = BackgroundProcessHistoryStatus.Pending.ToString() }); _emailService .When(x => x.SendEmailAsync(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <int?>(), Arg.Any <int?>(), Arg.Any <IDictionary <string, string> >(), Arg.Any <string>())) .Do(x => { var address = x.ArgAt <string>(1); var tokens = x.Arg <Dictionary <string, string> >(); if (tokens.TryGetValue("contact_name", out var contact)) { _contactNames[address] = contact; } }); _opportunityRepository .GetProviderReferralsAsync( Arg.Any <int>(), Arg.Any <IEnumerable <int> >()) .Returns(new ValidOpportunityReferralDtoListBuilder().BuildWithOneReferral()); var functionLogRepository = Substitute.For <IRepository <FunctionLog> >(); var itemIds = new List <int> { 1 }; var referralEmailService = new ReferralEmailService(mapper, datetimeProvider, _emailService, _opportunityRepository, opportunityItemRepository, _backgroundProcessHistoryRepository, functionLogRepository); referralEmailService.SendProviderReferralEmailAsync(1, itemIds, 1, "system").GetAwaiter().GetResult(); }
public async Task SendProviderReferralEmailAsync(int opportunityId, IEnumerable <int> itemIds, int backgroundProcessHistoryId, string username) { if (await GetBackgroundProcessHistoryDataAsync(backgroundProcessHistoryId) == null) { await _functionLogRepository.CreateAsync(new FunctionLog { ErrorMessage = $"Background Processing History not found or not pending for id {backgroundProcessHistoryId} for provider referral emails", FunctionName = nameof(ReferralEmailService), RowNumber = -1 }); return; } var itemIdList = itemIds.ToList(); var referrals = await _opportunityRepository.GetProviderReferralsAsync(opportunityId, itemIdList); try { if (referrals == null || referrals.Count == 0) { await _functionLogRepository.CreateAsync(new FunctionLog { ErrorMessage = $"No provider referrals found for opportunity id {opportunityId} with {itemIdList.Count} items", FunctionName = nameof(ReferralEmailService), RowNumber = -1 }); } else { //Group by opportunity item, then loop over that with referrals onside var opportunityItemGroups = ( from p in referrals orderby p.OpportunityItemId group p by p.OpportunityItemId into g select new { OpportunityItemId = g.Key, Referrals = g.Select(c => c).ToList() } ).ToList(); foreach (var opportunityItem in opportunityItemGroups) { foreach (var referral in opportunityItem.Referrals) { var placements = GetNumberOfPlacements(referral.PlacementsKnown, referral.Placements); var tokens = new Dictionary <string, string> { { "contact_name", referral.ProviderPrimaryContact }, { "provider_name", referral.ProviderDisplayName }, { "route", referral.RouteName.ToLowerInvariant() }, { "venue_text", referral.VenueText }, { "search_radius", referral.DistanceFromEmployer }, { "job_role_list", string.IsNullOrEmpty(referral.JobRole) || referral.JobRole == "None given" ? $"* looking for students in courses related to {referral.RouteName.ToLowerInvariant()}" : $"* looking for this job role: {referral.JobRole}" }, { "employer_business_name", referral.CompanyName.ToTitleCase() }, { "employer_contact_name", referral.EmployerContact.ToTitleCase() }, { "employer_contact_number", referral.EmployerContactPhone }, { "employer_contact_email", referral.EmployerContactEmail }, { "employer_town_postcode", $"{referral.Town} {referral.Postcode}" }, { "number_of_placements", placements } }; const EmailTemplateName template = EmailTemplateName.ProviderReferralV5; await SendEmailAsync(template, opportunityId, referral.ProviderPrimaryContactEmail, tokens, referral.CreatedBy, referral.OpportunityItemId); if (!string.IsNullOrWhiteSpace(referral.ProviderSecondaryContactEmail) && !string.IsNullOrWhiteSpace(referral.ProviderSecondaryContact)) { tokens["contact_name"] = referral.ProviderSecondaryContact; await SendEmailAsync(template, opportunityId, referral.ProviderSecondaryContactEmail, tokens, referral.CreatedBy, referral.OpportunityItemId); } } await SetOpportunityItemsAsCompletedAsync(new[] { opportunityItem.OpportunityItemId }, username); } } await CompleteRemainingProvisionGapsAsync(opportunityId, username); await UpdateBackgroundProcessHistoryAsync(backgroundProcessHistoryId, referrals?.Count ?? 0, BackgroundProcessHistoryStatus.Complete, username); } catch (Exception ex) { var errorMessage = $"Error sending provider referral emails. {ex.Message} " + $"Opportunity id {opportunityId}" + $"\r\nInner exception: {ex.InnerException?.Message}\r\n" + $"Stack trace: {ex.StackTrace}"; await _functionLogRepository.CreateAsync(new FunctionLog { ErrorMessage = errorMessage, FunctionName = nameof(ReferralEmailService), RowNumber = -1 }); await UpdateBackgroundProcessHistoryAsync(backgroundProcessHistoryId, referrals?.Count ?? 0, BackgroundProcessHistoryStatus.Error, username, errorMessage); } }