Example #1
0
        public async Task <List <SendMessageRequest> > IdentifyRecipients(int?recipientUserId, int?jobId, int?groupId, int?requestId, Dictionary <string, string> additionalParameters)
        {
            GetOpenShiftJobsByFilterRequest request = new GetOpenShiftJobsByFilterRequest();
            var shifts = await _connectRequestService.GetOpenShiftJobsByFilter(request);

            List <Tuple <int, Location> > usersToBeNotified = new List <Tuple <int, Location> >();

            if (shifts != null)
            {
                var locationsSupportActivities = shifts.GroupBy(d => new { d.Location, d.SupportActivity })
                                                 .Select(m => new { m.Key.Location, m.Key.SupportActivity });

                if (locationsSupportActivities != null && locationsSupportActivities.Count() > 0)
                {
                    foreach (var x in locationsSupportActivities)
                    {
                        var locations = await _connectAddressService.GetLocationDetails(x.Location, CancellationToken.None);

                        if (locations != null)
                        {
                            var users = await _connectUserService.GetVolunteersByPostcodeAndActivity(
                                locations.Address.Postcode,
                                new List <SupportActivities>() { x.SupportActivity },
                                _emailConfig.Value.OpenRequestRadius,
                                CancellationToken.None);

                            if (users != null && users.Volunteers.Count() > 0)
                            {
                                usersToBeNotified.AddRange(users.Volunteers.Select(i => new Tuple <int, Location>(i.UserID, x.Location)).ToList());
                            }
                        }
                    }
                }

                if (usersToBeNotified.Count > 0)
                {
                    var openRequests      = shifts.Select(x => x.RequestID).Distinct();
                    var shiftsDetailsSent = await _cosmosDbService.GetAllUserShiftDetailsHaveBeenSentTo(openRequests);

                    foreach (var userId in usersToBeNotified.GroupBy(g => g.Item1).Select(m => m.Key).ToList())
                    {
                        var requestsThatUserHasAlreadyBeenNotifiedAbout = shiftsDetailsSent.Where(x => x.RecipientUserID == userId).Select(x => x.RequestID);
                        var requestsStillToBeNotifiedAbout = openRequests.Where(s => !requestsThatUserHasAlreadyBeenNotifiedAbout.Contains(s)).ToList();

                        if (requestsStillToBeNotifiedAbout.Count > 0)
                        {
                            List <Location>             locations          = usersToBeNotified.Where(x => x.Item1 == userId).Select(m => m.Item2).ToList();
                            string                      parameter          = string.Join(",", locations.Cast <int>().ToArray());
                            Dictionary <string, string> locationParameters = new Dictionary <string, string>();
                            locationParameters.Add("locations", parameter);
                            AddRecipientAndTemplate(TemplateName.RequestNotification, userId, null, null, null, locationParameters);
                        }
                    }
                }
            }

            return(_sendMessageRequests);
        }
        private List <RequestJob> GetJobsForShiftRequest(GetRequestDetailsResponse response, List <GroupJob> groupJobs)
        {
            List <RequestJob> requestJobs = new List <RequestJob>();

            var locationDetails = _connectAddressService.GetLocationDetails(response.RequestSummary.Shift.Location, CancellationToken.None).Result;

            if (locationDetails == null)
            {
                throw new Exception($"Unable to retrieve location details for request {response.RequestSummary.RequestID}");
            }

            string locationName = locationDetails.ShortName;

            var time = TimeSpan.FromMinutes(response.RequestSummary.Shift.ShiftLength);

            string dueDateString = $"Shift: <strong>{response.RequestSummary.Shift.StartDate.FormatDate(DateTimeFormat.LongDateTimeFormat)} - {response.RequestSummary.Shift.EndDate.FormatDate(DateTimeFormat.TimeFormat)}</strong> " +
                                   $"(Duration: {Math.Floor(time.TotalHours)} hrs {time.Minutes} mins). " +
                                   $"Location: <strong>{locationName}</strong>";

            foreach (GroupJob gj in groupJobs)
            {
                requestJobs.Add(new RequestJob(
                                    activity: gj.SupportActivity.FriendlyNameShort(),
                                    countString: gj.Count == 1 ? $" - 1 volunteer required. " : $" - {gj.Count} volunteers required. ",
                                    dueDateString: dueDateString,
                                    showJobUrl: false,
                                    jobUrl: string.Empty
                                    ));
                ;
            }
            return(requestJobs);
        }
 private string GetLocationDetails(GetJobDetailsResponse job)
 {
     if (job.RequestSummary.Shift == null)
     {
         return(string.Empty);
     }
     else
     {
         var locationDetails = _connectAddressService.GetLocationDetails(job.RequestSummary.Shift.Location, CancellationToken.None).Result;
         if (locationDetails != null)
         {
             return($"{locationDetails.Name}");
         }
         else
         {
             throw new Exception("Unable to find location details");
         }
     }
 }
        public async Task <EmailBuildData> PrepareTemplateData(Guid batchId, int?recipientUserId, int?jobId, int?groupId, int?requestId, Dictionary <string, string> additionalParameters, string templateName)
        {
            var request = await _connectRequestService.GetRequestDetailsAsync(requestId.Value);

            var user = await _connectUserService.GetUserByIdAsync(recipientUserId.Value);

            var job      = request.RequestSummary.JobBasics.Where(x => x.JobID == jobId.Value).FirstOrDefault();
            var location = await _connectAddressService.GetLocationDetails(request.RequestSummary.Shift.Location, CancellationToken.None);

            string encodedJobId = Base64Utils.Base64Encode(jobId.Value.ToString());
            var    joburlToken  = await _linkRepository.CreateLink($"/link/j/{encodedJobId}", _linkConfig.Value.ExpiryDays);

            return(new EmailBuildData()
            {
                BaseDynamicData = new ShiftReminderMessageData(
                    title: "Volunteer shift reminder",
                    subject: "Volunteer shift reminder",
                    firstname: user.UserPersonalDetails.FirstName,
                    activity: job.SupportActivity.FriendlyNameShort(),
                    location: location.Name,
                    shiftStartDateString: FormatDate(request.RequestSummary.Shift.StartDate),
                    shiftEndDateString: FormatDate(request.RequestSummary.Shift.EndDate),
                    locationAddress: string.Empty,
                    joburlToken: joburlToken
                    ),
                EmailToAddress = user.UserPersonalDetails.EmailAddress,
                EmailToName = $"{user.UserPersonalDetails.FirstName} {user.UserPersonalDetails.LastName}",
                RequestID = requestId,
                JobID = jobId,
                ReferencedJobs = new List <ReferencedJob>()
                {
                    new ReferencedJob()
                    {
                        G = request.RequestSummary.ReferringGroupID,
                        R = requestId,
                        J = jobId
                    }
                }
            });
        }
        public async Task <EmailBuildData> PrepareTemplateData(Guid batchId, int?recipientUserId, int?jobId, int?groupId, int?requestId, Dictionary <string, string> additionalParameters, string templateName)
        {
            if (recipientUserId == null)
            {
                throw new BadRequestException("recipientUserId is null");
            }

            var user = _connectUserService.GetUserByIdAsync(recipientUserId.Value).Result;

            if (user == null)
            {
                throw new BadRequestException($"unable to retrieve user object for {recipientUserId.Value}");
            }

            var groups = _connectGroupService.GetUserGroups(recipientUserId.Value).Result;

            if (groups == null || groups.Groups == null || groups.Groups.Count == 0)
            {
                return(null);
            }

            Dictionary <SupportActivities, double?> nationalSupportActivities = new Dictionary <SupportActivities, double?>()
            {
                { SupportActivities.FaceMask, null },
                { SupportActivities.HomeworkSupport, null },
                { SupportActivities.PhoneCalls_Anxious, null },
                { SupportActivities.PhoneCalls_Friendly, null },
                { SupportActivities.VaccineSupport, _emailConfig.Value.OpenRequestRadius }
            };
            Dictionary <SupportActivities, double?> activitySpecificSupportDistancesInMiles = nationalSupportActivities.Where(a => user.SupportActivities.Contains(a.Key)).ToDictionary(a => a.Key, a => a.Value);

            GetAllJobsByFilterResponse openRequests;

            openRequests = await _connectRequestService.GetAllJobsByFilter(new GetAllJobsByFilterRequest()
            {
                JobStatuses = new JobStatusRequest()
                {
                    JobStatuses = new List <JobStatuses>()
                    {
                        JobStatuses.Open
                    }
                },
                Postcode        = user.PostalCode,
                DistanceInMiles = _emailConfig.Value.OpenRequestRadius,
                ExcludeSiblingsOfJobsAllocatedToUserID = recipientUserId,
                Groups = new GroupRequest()
                {
                    Groups = groups.Groups
                },
                ActivitySpecificSupportDistancesInMiles = activitySpecificSupportDistancesInMiles
            });


            var openTasks  = openRequests.JobSummaries.ToList();
            var openShifts = openRequests.ShiftJobs.Where(x => user.SupportActivities.Contains(x.SupportActivity)).ToList();

            if ((openTasks == null || openTasks.Count == 0) && (openShifts == null || openShifts.Count == 0))
            {
                return(null);
            }

            var chosenRequestTaskList = new List <DailyDigestDataJob>();
            var otherRequestTaskList  = new List <DailyDigestDataJob>();
            var shiftItemList         = new List <ShiftItem>();
            List <JobSummary> criteriaRequestTasks = new List <JobSummary>();
            List <JobSummary> otherRequestTasks    = new List <JobSummary>();


            if (openTasks.Count() > 0)
            {
                criteriaRequestTasks = openTasks
                                       .Where(x => user.SupportActivities.Contains(x.SupportActivity) && x.DistanceInMiles <= user.SupportRadiusMiles)
                                       .Distinct(_jobSummaryDedupe_EqualityComparer)
                                       .ToList();

                criteriaRequestTasks = criteriaRequestTasks.OrderBy(x => x.DueDate).ToList();

                otherRequestTasks = openTasks.Where(x => !criteriaRequestTasks.Contains(x, _jobSummaryDedupe_EqualityComparer)).ToList();
                var otherRequestTasksStats = otherRequestTasks.GroupBy(x => x.SupportActivity, x => x.DueDate, (activity, dueDate) => new { Key = activity, Count = dueDate.Count(), Min = dueDate.Min() });
                otherRequestTasksStats = otherRequestTasksStats.OrderByDescending(x => x.Count);

                foreach (var request in criteriaRequestTasks)
                {
                    string encodedRequestId = HelpMyStreet.Utils.Utils.Base64Utils.Base64Encode(request.RequestID.ToString());

                    chosenRequestTaskList.Add(new DailyDigestDataJob(
                                                  activity: request.SupportActivity.FriendlyNameShort(),
                                                  postCode: request.PostCode,
                                                  dueDate: request.DueDate.FormatDate(DateTimeFormat.ShortDateFormat),
                                                  soon: request.DueDate < DateTime.Now.AddDays(1),
                                                  urgent: request.IsHealthCritical,
                                                  isSingleItem: true, //not used in the chosen task component of the email
                                                  count: 1,           //not used in the chosen task component of the email
                                                  encodedRequestId: encodedRequestId,
                                                  distanceInMiles: Math.Round(request.DistanceInMiles, 1).ToString()
                                                  ));
                }

                foreach (var request in otherRequestTasksStats)
                {
                    otherRequestTaskList.Add(new DailyDigestDataJob(
                                                 activity: request.Key.FriendlyNameShort(),
                                                 postCode: string.Empty, //not used in the other task component of the email
                                                 dueDate: request.Min.FormatDate(DateTimeFormat.ShortDateFormat),
                                                 soon: false,            //not used in the other task component of the email
                                                 urgent: false,          //not used in the other task component of the email
                                                 isSingleItem: request.Count == 1 ? true : false,
                                                 count: request.Count,
                                                 encodedRequestId: "", //not used in the other task component of the email
                                                 distanceInMiles: ""   //not used in the other task component of the email
                                                 ));
                }
            }

            if (openShifts?.Count > 0)
            {
                var requests = openShifts
                               .Distinct(_shiftJobDedupe_EqualityComparer)
                               .ToList();

                foreach (var shift in requests)
                {
                    var location = await _connectAddressService.GetLocationDetails(shift.Location, CancellationToken.None);

                    string shiftDate = shift.StartDate.FormatDate(DateTimeFormat.LongDateTimeFormat) + " - " + shift.EndDate.FormatDate(DateTimeFormat.TimeFormat);
                    shiftItemList.Add(new ShiftItem($"<strong>{ shift.SupportActivity.FriendlyNameShort() }</strong> " +
                                                    $"at {location.Name} " +
                                                    $"( {Math.Round(shift.DistanceInMiles, 2)} miles away) " +
                                                    $"- {shiftDate}"));
                }
            }

            if (chosenRequestTaskList.Count > 0 || shiftItemList.Count > 0)
            {
                return(new EmailBuildData()
                {
                    BaseDynamicData = new DailyDigestData(
                        title: string.Empty,
                        firstName: user.UserPersonalDetails.FirstName,
                        chosenRequestTasks: criteriaRequestTasks.Count(),
                        otherRequestTasks: otherRequestTasks.Count() > 0,
                        shiftsAvailable: shiftItemList.Count > 0,
                        shiftCount: shiftItemList.Count,
                        chosenRequestTaskList: chosenRequestTaskList,
                        otherRequestTaskList: otherRequestTaskList,
                        shiftItemList: shiftItemList
                        ),
                    EmailToAddress = user.UserPersonalDetails.EmailAddress,
                    EmailToName = user.UserPersonalDetails.DisplayName,
                    ReferencedJobs = GetReferencedJobs(criteriaRequestTasks, otherRequestTasks, openShifts),
                });
            }
            else
            {
                return(null);
            }
        }