public async Task Notify(IReadOnlyCollection <Request> updatedRequests) { if (!updatedRequests.Any()) { return; } this.logger.LogDebug("Sending notifications for new requests."); var users = await this.userRepository.GetUsers(); var schedules = await this.scheduleRepository.GetSchedules(); var dailyNotificationSchedule = schedules.Single(s => s.ScheduledTaskType == ScheduledTaskType.DailyNotification); var weeklyNotificationSchedule = schedules.Single(s => s.ScheduledTaskType == ScheduledTaskType.WeeklyNotification); var datesToExclude = new List <LocalDate>(); if (dateCalculator.ScheduleIsDue(dailyNotificationSchedule, within: Duration.FromMinutes(2))) { this.logger.LogDebug("Daily notification email is due soon. Excluding this date."); datesToExclude.Add(this.dateCalculator.GetNextWorkingDate()); } if (dateCalculator.ScheduleIsDue(weeklyNotificationSchedule, within: Duration.FromMinutes(2))) { this.logger.LogDebug("Weekly notification email is due soon. Excluding these dates."); datesToExclude.AddRange(this.dateCalculator.GetWeeklyNotificationDates()); } var requestsToNotify = updatedRequests.Where(r => r.Status == RequestStatus.Allocated && !datesToExclude.Contains(r.Date)); foreach (var requestsByUser in requestsToNotify.GroupBy(r => r.UserId)) { var user = users.Single(u => u.UserId == requestsByUser.Key); var userRequests = requestsByUser.ToArray(); var emailTemplate = userRequests.Length == 1 ? (IEmailTemplate) new SingleDayAllocationNotification(userRequests[0], user) : new MultipleDayAllocationNotification(userRequests, user); await this.emailRepository.Send(emailTemplate); } }