Esempio n. 1
0
        public async Task <IActionResult> PostTaskFeedbackCapture(string j, string r, FeedbackCaptureEditModel model, CancellationToken cancellationToken)
        {
            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(Redirect("/Error/401"));
            }
            if (!ModelState.IsValid)
            {
                throw new Exception($"Invalid model state in PostTaskFeedbackCapture for job {jobId}");
            }

            model.JobId = jobId;
            model.RoleSubmittingFeedback = requestRole;

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            var job = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

            var result = await _feedbackService.PostRecordFeedback(user, model);

            return(ShowMessage(result, job.ReferringGroupID, model));
        }
Esempio n. 2
0
        public async Task <ActionResult <SetJobStatusResult> > SetJobStatus(string j, string rq, JobStatuses s, string r, string u, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

                UpdateJobStatusOutcome?outcome;
                bool requestFeedback = false;

                if (string.IsNullOrEmpty(j))
                {
                    int requestId = Base64Utils.Base64DecodeToInt(rq);
                    outcome = await _requestService.UpdateRequestStatusAsync(requestId, s, user.ID, cancellationToken);
                }
                else
                {
                    RequestRoles requestRole  = (RequestRoles)Base64Utils.Base64DecodeToInt(r);
                    int?         targetUserId = null;
                    if (s == JobStatuses.Accepted || s == JobStatuses.InProgress)
                    {
                        targetUserId = (requestRole == RequestRoles.Volunteer ? user.ID : Base64Utils.Base64DecodeToInt(u));
                    }

                    int jobId = Base64Utils.Base64DecodeToInt(j);
                    outcome = await _requestService.UpdateJobStatusAsync(jobId, s, user.ID, targetUserId, cancellationToken);

                    var job = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

                    if (job.RequestType.Equals(RequestType.Task))
                    {
                        requestFeedback = (await GetJobFeedbackStatus(jobId, user.ID, requestRole, cancellationToken)).FeedbackDue;
                    }
                }

                switch (outcome)
                {
                case UpdateJobStatusOutcome.AlreadyInThisStatus:
                case UpdateJobStatusOutcome.Success:
                    return(new SetJobStatusResult
                    {
                        NewStatus = s.FriendlyName(),
                        RequestFeedback = requestFeedback
                    });

                case UpdateJobStatusOutcome.BadRequest:
                    return(StatusCode(400));

                case UpdateJobStatusOutcome.Unauthorized:
                    return(StatusCode(401));

                default:
                    return(StatusCode(500));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception in SetRequestStatus", ex);
                return(StatusCode(500));
            }
        }
Esempio n. 3
0
        public async Task <bool> GetFeedbackExists(int JobId, RequestRoles requestRole, int?userId)
        {
            GetFeedbackExistsRequest request = new GetFeedbackExistsRequest()
            {
                JobId           = JobId,
                RequestRoleType = new RequestRoleType()
                {
                    RequestRole = requestRole
                },
                UserId = userId
            };
            string              json     = JsonConvert.SerializeObject(request);
            StringContent       data     = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await Client.PostAsync("/api/GetFeedbackExists", data);

            string str = await response.Content.ReadAsStringAsync();

            var deserializedResponse = JsonConvert.DeserializeObject <ResponseWrapper <bool, FeedbackServiceErrorCode> >(str);

            if (deserializedResponse.HasContent && deserializedResponse.IsSuccessful)
            {
                return(deserializedResponse.Content);
            }
            return(false);
        }
Esempio n. 4
0
        public async Task <IActionResult> PostTaskFeedbackCapture(string j, string r, string f, CancellationToken cancellationToken)
        {
            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(Redirect("/Error/401"));
            }

            int            jobId          = Base64Utils.Base64DecodeToInt(j);
            RequestRoles   requestRole    = (RequestRoles)Base64Utils.Base64DecodeToInt(r);
            FeedbackRating feedbackRating = string.IsNullOrEmpty(f) ? 0 : (FeedbackRating)Base64Utils.Base64DecodeToInt(f);
            var            job            = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            if (job.JobStatus.Incomplete())
            {
                return(ShowMessage(Result.Failure_IncorrectJobStatus, job.ReferringGroupID));
            }

            if (await _feedbackService.GetFeedbackExists(jobId, requestRole, user?.ID))
            {
                return(ShowMessage(Result.Failure_FeedbackAlreadyRecorded, job.ReferringGroupID));
            }

            return(View(new FeedbackCaptureViewComponentParameters()
            {
                JobId = jobId, RequestRole = requestRole, FeedbackRating = feedbackRating
            }));
        }
        private string GetHelpRecipient(RequestRoles requestRole, GetJobDetailsResponse job)
        {
            string recipient = string.Empty;

            if (job.Recipient != null)
            {
                if (job.JobSummary.RequestorType == RequestorType.Organisation && !string.IsNullOrEmpty(job.JobSummary.RecipientOrganisation))
                {
                    recipient = job.JobSummary.RecipientOrganisation;
                }
                else if (requestRole == RequestRoles.Recipient || (requestRole == RequestRoles.Requestor && job.JobSummary.RequestorType == RequestorType.Myself))
                {
                    recipient = $"You ({job.Recipient.FirstName})";
                }
                else if (!string.IsNullOrEmpty(job.Recipient.Address.Locality))
                {
                    recipient = $"{job.Recipient.FirstName} ({job.Recipient.Address.Locality.ToLower()})";
                }
                else
                {
                    recipient = job.Recipient.FirstName;
                }

                return(_textInfo.ToTitleCase(recipient));
            }
            else
            {
                return(string.Empty);
            }
        }
Esempio n. 6
0
        public async Task <bool> PostRecordFeedback(int jobId, RequestRoles requestRoles, int?userId, FeedbackRating feedbackRating)
        {
            PostRecordFeedbackRequest request = new PostRecordFeedbackRequest()
            {
                JobId           = jobId,
                RequestRoleType = new RequestRoleType()
                {
                    RequestRole = requestRoles
                },
                UserId             = userId,
                FeedbackRatingType = new FeedbackRatingType()
                {
                    FeedbackRating = feedbackRating
                }
            };
            string              json     = JsonConvert.SerializeObject(request);
            StringContent       data     = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await Client.PostAsync("/api/PostRecordFeedback", data);

            string str = await response.Content.ReadAsStringAsync();

            var deserializedResponse = JsonConvert.DeserializeObject <ResponseWrapper <PostRecordFeedbackResponse, FeedbackServiceErrorCode> >(str);

            if (deserializedResponse.HasContent && deserializedResponse.IsSuccessful)
            {
                return(deserializedResponse.Content.Success);
            }
            return(false);
        }
Esempio n. 7
0
        public async Task <IActionResult> PutFeedback(string j, string r, [FromBody] CapturedFeedback model, CancellationToken cancellationToken)
        {
            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized));
            }
            if (!ModelState.IsValid)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }

            model.JobId = jobId;
            model.RoleSubmittingFeedback = requestRole;

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            var result = await _feedbackService.PostRecordFeedback(user, model);

            if (result == Result.Success || result == Result.Failure_FeedbackAlreadyRecorded)
            {
                return(StatusCode((int)HttpStatusCode.OK));
            }
            else
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 8
0
 public static bool LimitOneFeedbackPerRequest(this RequestRoles role)
 {
     return(role switch
     {
         RequestRoles.Recipient => true,
         RequestRoles.Requestor => true,
         RequestRoles.Volunteer => false,
         RequestRoles.GroupAdmin => false,
         _ => throw new ArgumentException($"Unexpected RequestRoles value: {role}", nameof(role))
     });
        private string GetReference(RequestRoles requestRole, GetJobDetailsResponse job)
        {
            string reference = string.Empty;

            if (job.JobSummary.ReferringGroupID == (int)Groups.AgeUKLSL)
            {
                var question = job.JobSummary.Questions.FirstOrDefault(x => x.Id == (int)Questions.AgeUKReference);

                reference = question?.Answer;
            }

            return(reference);
        }
Esempio n. 10
0
        public IActionResult PostTaskFeedbackCapturePopup(string j, string r)
        {
            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized));
            }

            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            return(ViewComponent("FeedbackCapture", new { parameters = new FeedbackCaptureViewComponentParameters()
                                                          {
                                                              JobId = jobId, RequestRole = requestRole, RenderAsPopup = true
                                                          } }));
        }
        private string GetProtectedUrl(int jobId, RequestRoles requestRole, FeedbackRating?feedbackRating)
        {
            string encodedJobId           = Base64Utils.Base64Encode(jobId.ToString());
            string encodedRequestRoleType = Base64Utils.Base64Encode((int)requestRole);

            string tailUrl = $"/Feedback/PostTaskFeedbackCapture?j={encodedJobId}&r={encodedRequestRoleType}";

            if (feedbackRating.HasValue)
            {
                tailUrl += $"&f={Base64Utils.Base64Encode((int)feedbackRating)}";
            }
            var token = _linkRepository.CreateLink(tailUrl, _linkConfig.Value.ExpiryDays).Result;

            return(_sendGridConfig.Value.BaseUrl + "/link/" + token);
        }
Esempio n. 12
0
        private string SenderAndContextRecipient(string senderName, RequestRoles toRole)
        {
            switch (toRole)
            {
            case RequestRoles.Requestor:
                return($"<strong>{senderName}</strong>, the person who you requested help for.");

            case RequestRoles.Volunteer:
                return($"<strong>{senderName}</strong>, the person who you helped.");

            case RequestRoles.GroupAdmin:
                return($"<strong>{senderName}</strong>, the person who needed help.");

            default:
                throw new Exception($"Invalid Request Role {toRole}");
            }
        }
        private async Task EnsureFeedbackCanBeGiven(JobSummary jobSummary, RequestRoles requestRole, int?userId)
        {
            if (jobSummary.JobStatus.Incomplete())
            {
                throw new Exception($"Attempt to load feedback form for job {jobSummary.JobID}, but it is {jobSummary.JobStatus}");
            }

            if (await _feedbackRepository.GetFeedbackExists(jobSummary.JobID, requestRole, userId))
            {
                throw new Exception($"Attempt to load feedback form for job {jobSummary.JobID}, but feedback already exists for role {requestRole} / user {userId}");
            }

            if (jobSummary.Archive == true)
            {
                throw new Exception($"Attempt to load feedback form for achived job {jobSummary.JobID}");
            }
        }
Esempio n. 14
0
        private MessageParticipant GetToBlock(GetJobDetailsResponse job, RequestRoles requestRole)
        {
            MessageParticipant to = new MessageParticipant
            {
                RequestRoleType = new RequestRoleType {
                    RequestRole = requestRole
                }
            };

            switch (requestRole)
            {
            case RequestRoles.Recipient:
                to.EmailDetails = new EmailDetails
                {
                    DisplayName  = string.IsNullOrEmpty(job.JobSummary.RecipientOrganisation) ? job.Recipient.FirstName : job.JobSummary.RecipientOrganisation,
                    EmailAddress = job.Recipient.EmailAddress
                };
                break;

            case RequestRoles.Requestor:
                to.EmailDetails = new EmailDetails
                {
                    DisplayName  = job.Requestor.FirstName,
                    EmailAddress = job.Requestor.EmailAddress
                };
                break;

            case RequestRoles.Volunteer:
                to.UserId = job.JobSummary.VolunteerUserID;
                break;

            case RequestRoles.GroupAdmin:
                to.GroupRoleType = new GroupRoleType()
                {
                    GroupId    = job.JobSummary.ReferringGroupID,
                    GroupRoles = GroupRoles.Owner
                };
                break;

            default:
                throw new ArgumentException(message: $"Unexpected RequestRoles value: {requestRole}", paramName: nameof(requestRole));
            }

            return(to);
        }
Esempio n. 15
0
        private MessageParticipant GetFromBlock(User user, RequestRoles requestRole, GetJobDetailsResponse job)
        {
            MessageParticipant from = new MessageParticipant
            {
                RequestRoleType = new RequestRoleType {
                    RequestRole = requestRole
                }
            };

            switch (requestRole)
            {
            case RequestRoles.GroupAdmin:
                from.GroupRoleType = new GroupRoleType
                {
                    GroupId    = job.JobSummary.ReferringGroupID,
                    GroupRoles = GroupRoles.Owner
                };
                break;

            case RequestRoles.Volunteer:
                from.UserId = user.ID;
                break;

            case RequestRoles.Recipient:
                from.EmailDetails = new EmailDetails
                {
                    DisplayName = string.IsNullOrEmpty(job.JobSummary.RecipientOrganisation) ? job.Recipient.FirstName : job.JobSummary.RecipientOrganisation
                };
                break;

            case RequestRoles.Requestor:
                from.EmailDetails = new EmailDetails
                {
                    DisplayName = job.Requestor.FirstName
                };
                break;

            default:
                throw new ArgumentException(message: $"Unexpected RequestRoles value: {requestRole}", paramName: nameof(requestRole));
            }

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

            string dueDateString = string.Empty;
            bool   showJobUrl    = false;
            string jobUrl        = string.Empty;

            //TODO - This can be written to handle multiple jobs for a standard request. Need to tweak when repeat enquiries functionality added
            if (groupJobs.Count == 1)
            {
                int jobid = response.RequestSummary.JobBasics[0].JobID;
                GetJobDetailsResponse jobResponse = _connectRequestService.GetJobDetailsAsync(jobid).Result;

                if (jobResponse != null)
                {
                    RequestRoles getChangedBy = GetChangedByRole(jobResponse);
                    showJobUrl = getChangedBy == RequestRoles.Volunteer ||
                                 getChangedBy == RequestRoles.GroupAdmin ||
                                 (getChangedBy == RequestRoles.Requestor && jobResponse.JobSummary.RequestorDefinedByGroup);
                    jobUrl = showJobUrl ? GetJobUrl(jobid, response.RequestSummary.RequestID, groupJobs[0].Count) : string.Empty;

                    dueDateString = $" - Due Date: <strong>{jobResponse.JobSummary.DueDate.FormatDate(DateTimeFormat.LongDateFormat)}.</strong>";
                }
                else
                {
                    throw new Exception($"Unable to retrieve job details for jobid { jobid }");
                }
            }

            foreach (GroupJob gj in groupJobs)
            {
                requestJobs.Add(new RequestJob(
                                    activity: gj.SupportActivity.FriendlyNameShort(),
                                    countString: gj.Count == 1 ? string.Empty: $" - {gj.Count} volunteers required. ",
                                    dueDateString: dueDateString,
                                    showJobUrl: showJobUrl,
                                    jobUrl: jobUrl
                                    ));
            }
            return(requestJobs);
        }
        private async Task <string> GetVolunteer(RequestRoles requestRole, GetJobDetailsResponse job)
        {
            string volunteer = string.Empty;

            if (job.JobSummary.VolunteerUserID.HasValue)
            {
                var user = await _connectUserService.GetUserByIdAsync(job.JobSummary.VolunteerUserID.Value);

                if (requestRole == RequestRoles.Volunteer)
                {
                    volunteer = $"You ({user.UserPersonalDetails.FirstName})";
                }
                else
                {
                    volunteer = user.UserPersonalDetails.FirstName;
                }
            }

            return(_textInfo.ToTitleCase(volunteer));
        }
Esempio n. 18
0
        private async Task <string> SenderAndContext(string senderName, string senderRequestorRole, string toRequestorRole, string senderGroupName, GetJobDetailsResponse job)
        {
            string       result        = string.Empty;
            RequestRoles senderRole    = (RequestRoles)Enum.Parse(typeof(RequestRoles), senderRequestorRole);
            RequestRoles toRole        = (RequestRoles)Enum.Parse(typeof(RequestRoles), toRequestorRole);
            string       helpRecipient = string.Empty;

            if (job != null)
            {
                helpRecipient = job.Recipient?.FirstName;
            }

            switch (senderRole)
            {
            case RequestRoles.Recipient:
                result = SenderAndContextRecipient(senderName, toRole);
                break;

            case RequestRoles.Requestor:
                result = SenderAndContextRequestor(senderName, helpRecipient, toRole);
                break;

            case RequestRoles.Volunteer:
                result = SenderAndContextVolunteer(senderName, helpRecipient, toRole);
                break;

            case RequestRoles.GroupAdmin:
                result = SenderAndContextGroupAdmin(senderName, senderGroupName);
                break;
            }

            if (job != null)
            {
                DateTime dtStatusChanged = job.JobSummary.DateStatusLastChanged;
                result = $"{result} The request was for <strong>{ job.JobSummary.SupportActivity.FriendlyNameShort()}</strong> and was {Mapping.StatusMappingsNotifications[job.JobSummary.JobStatus]} <strong>{dtStatusChanged.FriendlyPastDate()}</strong>";
            }
            return(result);
        }
        private string GetRequestedBy(RequestRoles requestRole, GetJobDetailsResponse job)
        {
            string requestor;

            if (job.JobSummary.RequestorDefinedByGroup)
            {
                requestor = job.Requestor.Address.AddressLine1;
            }
            else if (requestRole == RequestRoles.Requestor || (requestRole == RequestRoles.Recipient && job.JobSummary.RequestorType == RequestorType.Myself))
            {
                requestor = $"You ({job.Requestor.FirstName})";
            }
            else if (!string.IsNullOrEmpty(job.Requestor.Address.Locality))
            {
                requestor = $"{job.Requestor.FirstName} ({job.Requestor.Address.Locality.ToLower()})";
            }
            else
            {
                requestor = job.Requestor.FirstName;
            }

            return(_textInfo.ToTitleCase(requestor));
        }
Esempio n. 20
0
        public async Task <IActionResult> GetFeedbackComponent(string j, string r, CancellationToken cancellationToken)
        {
            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            if (user == null)
            {
                throw new UnauthorizedAccessException("No user in session");
            }

            var feedbackStatus = await GetJobFeedbackStatus(jobId, user.ID, requestRole, cancellationToken);

            if (feedbackStatus.FeedbackDue)
            {
                return(PartialView("_FeedbackDue"));
            }
            else if (feedbackStatus.FeedbackSubmitted)
            {
                return(PartialView("_FeedbackSubmitted"));
            }
            return(StatusCode((int)HttpStatusCode.OK));
        }
        private string GetFeedback(GetJobDetailsResponse job, RequestRoles requestRole)
        {
            if (job.JobSummary.JobStatus == JobStatuses.Done && (requestRole == RequestRoles.Recipient || requestRole == RequestRoles.Requestor))
            {
                var happyFaceImage = $"{_sendGridConfig.Value.BaseUrl}/img/email-resources/great.png";
                var sadFaceImage   = $"{_sendGridConfig.Value.BaseUrl}/img/email-resources/not-so-great.png";

                return($"<p>&nbsp;</p><p style='color:#001489;font-weight:bold;font-size:24px'>Tell us how it went</p><p>How was your experience with HelpMyStreet?</p>" +
                       $"<table>" +
                       $"<tr style='margin-left:10px'>" +
                       $"<td><a href='{GetProtectedUrl(job.JobSummary.JobID, requestRole, FeedbackRating.HappyFace)}'><img src='{happyFaceImage}' alt='Great' width='200'></a></td>" +
                       $"<td><a href='{GetProtectedUrl(job.JobSummary.JobID, requestRole, FeedbackRating.SadFace)}'><img src='{sadFaceImage}' alt='Not So Great' width='200'></a></td>" +
                       $"</tr>" +
                       $"<tr>" +
                       $"<td colspan=2><a href='{GetProtectedUrl(job.JobSummary.JobID, requestRole,null)}'>Click here to leave your feedback</a></td>" +
                       $"</tr>" +
                       $"</table>" +
                       $"<p>If you have any comments or queries, please click <a href='{GetProtectedUrl(job.JobSummary.JobID, requestRole, null)}'>here</a>, or get in touch by emailing [email protected].</p>");
            }
            else
            {
                return("<p>If you have any comments or queries, please get in touch by emailing [email protected].</p>");
            }
        }
Esempio n. 22
0
        private string SenderAndContextRequestor(string senderName, string helpRecipient, RequestRoles toRole)
        {
            switch (toRole)
            {
            case RequestRoles.Recipient:
                return($"<strong>{senderName}</strong>, the person who requested help for you.");

            case RequestRoles.Volunteer:
            case RequestRoles.GroupAdmin:
                return($"<strong>{senderName}</strong>, the person who requested help for <strong>{helpRecipient}</strong>.");

            default:
                throw new Exception($"Invalid Request Role {toRole}");
            }
        }
Esempio n. 23
0
        private async Task <JobFeedbackStatus> GetJobFeedbackStatus(int jobId, int userId, RequestRoles role, CancellationToken cancellationToken)
        {
            var job = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

            if (job.JobStatus == JobStatuses.Done || job.JobStatus == JobStatuses.Cancelled)
            {
                bool feedbackSubmitted = await _feedbackService.GetFeedbackExists(jobId, role, userId);

                if (feedbackSubmitted)
                {
                    return(new JobFeedbackStatus
                    {
                        FeedbackSubmitted = true,
                        FeedbackDue = false,
                    });
                }
                else if (!job.Archive)
                {
                    _authService.PutSessionAuthorisedUrl(HttpContext, $"/api/feedback/get-post-task-feedback-popup?j={Base64Utils.Base64Encode(jobId)}&r={Base64Utils.Base64Encode((int)role)}");
                    _authService.PutSessionAuthorisedUrl(HttpContext, $"/api/feedback/put-feedback?j={Base64Utils.Base64Encode(jobId)}&r={Base64Utils.Base64Encode((int)role)}");

                    return(new JobFeedbackStatus
                    {
                        FeedbackSubmitted = false,
                        FeedbackDue = true,
                    });
                }
            }

            return(new JobFeedbackStatus
            {
                FeedbackSubmitted = false,
                FeedbackDue = false,
            });
        }
Esempio n. 24
0
 public async Task <bool> GetFeedbackExists(int jobId, RequestRoles requestRole, int?userId)
 {
     return(await _feedbackRepository.GetFeedbackExists(jobId, requestRole, userId));
 }
        public async Task <EmailBuildData> PrepareTemplateData(Guid batchId, int?recipientUserId, int?jobId, int?groupId, int?requestId, Dictionary <string, string> additionalParameters, string templateName)
        {
            var job = _connectRequestService.GetJobDetailsAsync(jobId.Value).Result;

            // Recipient
            RequestRoles emailRecipientRequestRole = (RequestRoles)Enum.Parse(typeof(RequestRoles), additionalParameters["RequestRole"]);

            string emailToAddress   = string.Empty;
            string emailToFullName  = string.Empty;
            string emailToFirstName = string.Empty;

            switch (emailRecipientRequestRole)
            {
            case RequestRoles.Volunteer:
                var user = await _connectUserService.GetUserByIdAsync(recipientUserId.Value);

                emailToFirstName = user.UserPersonalDetails.FirstName;
                emailToAddress   = user.UserPersonalDetails.EmailAddress;
                emailToFullName  = $"{user.UserPersonalDetails.FirstName} {user.UserPersonalDetails.LastName}";
                break;

            case RequestRoles.Requestor:
                emailToFirstName = job.Requestor.FirstName;
                emailToAddress   = job.Requestor.EmailAddress;
                emailToFullName  = $"{job.Requestor.FirstName} {job.Requestor.LastName}";
                break;

            case RequestRoles.Recipient:
                emailToFirstName = job.Recipient.FirstName;
                emailToAddress   = job.Recipient.EmailAddress;
                emailToFullName  = $"{job.Recipient.FirstName} {job.Recipient.LastName}";
                break;
            }

            // Change summary
            additionalParameters.TryGetValue("FieldUpdated", out string fieldUpdated);
            JobStatuses  previousStatus  = _connectRequestService.PreviousJobStatus(job);
            RequestRoles changedByRole   = GetChangedByRole(job);
            string       supportActivity = job.JobSummary.SupportActivity.FriendlyNameShort();

            bool showJobUrl = emailRecipientRequestRole == RequestRoles.Volunteer ||
                              emailRecipientRequestRole == RequestRoles.GroupAdmin ||
                              (emailRecipientRequestRole == RequestRoles.Requestor && job.JobSummary.RequestorDefinedByGroup);
            string jobUrl = showJobUrl ? GetJobUrl(jobId.Value) : string.Empty;

            // First table
            List <TaskDataItem> importantDataList = new List <TaskDataItem>();

            AddIfNotNullOrEmpty(importantDataList, "Status", job.JobSummary.JobStatus.FriendlyName().ToTitleCase());
            AddIfNotNullOrEmpty(importantDataList, "Reference", GetReference(emailRecipientRequestRole, job));

            // Second table
            string requestedBy   = GetRequestedBy(emailRecipientRequestRole, job);
            string helpRecipient = GetHelpRecipient(emailRecipientRequestRole, job);

            List <TaskDataItem> otherDataList = new List <TaskDataItem>();

            AddIfNotNullOrEmpty(otherDataList, "Request type", supportActivity.ToTitleCase());
            AddIfNotNullOrEmpty(otherDataList, "Help needed", GetDueDate(job));
            AddIfNotNullOrEmpty(otherDataList, "Help needed", GetShiftDetails(job));
            AddIfNotNullOrEmpty(otherDataList, "Location", GetLocationDetails(job));
            AddIfNotNullOrEmpty(otherDataList, "Requested by", requestedBy);
            AddIfNotNullOrEmpty(otherDataList, "Help requested from", await GetHelpRequestedFrom(job));
            if (!helpRecipient.Equals(requestedBy))
            {
                AddIfNotNullOrEmpty(otherDataList, "Recipient", helpRecipient);
            }
            AddIfNotNullOrEmpty(otherDataList, "Volunteer", await GetVolunteer(emailRecipientRequestRole, job));

            return(new EmailBuildData()
            {
                BaseDynamicData = new TaskUpdateSimplifiedData
                                  (
                    $"A {supportActivity} request has been updated",
                    $"A {supportActivity} request has been updated",
                    emailToFirstName,
                    changedByRole == RequestRoles.GroupAdmin ? "group administrator" : "volunteer",
                    fieldUpdated.ToLower(),
                    showJobUrl,
                    jobUrl,
                    importantDataList,
                    otherDataList,
                    faceCoveringComplete: job.JobSummary.SupportActivity == SupportActivities.FaceMask && job.JobSummary.JobStatus == JobStatuses.Done,
                    previouStatusCompleteAndNowInProgress: previousStatus == JobStatuses.Done && job.JobSummary.JobStatus == JobStatuses.InProgress,
                    previouStatusInProgressAndNowOpen: previousStatus == JobStatuses.InProgress && job.JobSummary.JobStatus == JobStatuses.Open,
                    statusNowCancelled: job.JobSummary.JobStatus == JobStatuses.Cancelled,
                    GetFeedback(job, emailRecipientRequestRole)
                                  ),
                EmailToAddress = emailToAddress,
                EmailToName = emailToFullName,
                JobID = job.JobSummary.JobID,
                RequestID = job.JobSummary.RequestID,
                GroupID = job.JobSummary.ReferringGroupID,
                ReferencedJobs = new List <ReferencedJob>()
                {
                    new ReferencedJob()
                    {
                        G = job.JobSummary.ReferringGroupID,
                        R = job.JobSummary.RequestID,
                        J = job.JobSummary.JobID
                    }
                }
            });
        }
Esempio n. 26
0
 private async Task <SaveInterUserMessage> CreateSaveInterUserMessage(string senderFirstName, RequestRoles senderRequestRole, List <int> recipients, InterUserMessageRequest interUserMessageRequest)
 {
     return(new SaveInterUserMessage()
     {
         Content = interUserMessageRequest.Content,
         ThreadId = interUserMessageRequest.ThreadId,
         SenderFirstName = senderFirstName,
         SenderRequestRoles = senderRequestRole,
         JobId = interUserMessageRequest.JobId,
         RecipientUserIds = recipients,
         RecipientRequestRoles = interUserMessageRequest.To.RequestRoleType.RequestRole,
         MessageDate = DateTime.Now,
         EmailDetails = interUserMessageRequest.To.EmailDetails,
         id = Guid.NewGuid(),
         SenderUserIds = await IdentifyUserIDs(interUserMessageRequest.From),
     });
 }
        public async Task <List <SendMessageRequest> > IdentifyRecipients(int?recipientUserId, int?jobId, int?groupId, int?requestId, Dictionary <string, string> additionalParameters)
        {
            var job = await _connectRequestService.GetJobDetailsAsync(jobId.Value);

            if (job == null)
            {
                throw new Exception($"Job details cannot be retrieved for jobId {jobId}");
            }

            int?         currentOrLastVolunteerUserID = _connectRequestService.GetRelevantVolunteerUserID(job);
            RequestRoles changedByRole = GetChangedByRole(job);

            string volunteerEmailAddress = string.Empty;

            if (currentOrLastVolunteerUserID.HasValue)
            {
                var user = await _connectUserService.GetUserByIdAsync(currentOrLastVolunteerUserID.Value);

                if (user != null)
                {
                    volunteerEmailAddress = user.UserPersonalDetails.EmailAddress;
                }
            }

            if (currentOrLastVolunteerUserID.HasValue && changedByRole != RequestRoles.Volunteer)
            {
                var param = new Dictionary <string, string>(additionalParameters)
                {
                    { "RequestRole", RequestRoles.Volunteer.ToString() }
                };
                //We send an email to the volunteer as they did not make this change
                _sendMessageRequests.Add(new SendMessageRequest()
                {
                    TemplateName         = TemplateName.TaskUpdateSimplified,
                    RecipientUserID      = currentOrLastVolunteerUserID.Value,
                    GroupID              = groupId,
                    JobID                = jobId,
                    RequestID            = requestId,
                    AdditionalParameters = param
                });
            }

            string recipientEmailAddress = job.Recipient?.EmailAddress;
            string requestorEmailAddress = job.Requestor?.EmailAddress;

            var createdByUserID = GetCreatedByUserID(job);

            //Now consider the recipient
            if (!string.IsNullOrEmpty(recipientEmailAddress))
            {
                if (createdByUserID.HasValue && createdByUserID.Value != -1)
                {
                    var param = new Dictionary <string, string>(additionalParameters)
                    {
                        { "RequestRole", RequestRoles.Recipient.ToString() }
                    };
                    _sendMessageRequests.Add(new SendMessageRequest()
                    {
                        TemplateName         = TemplateName.TaskUpdateSimplified,
                        RecipientUserID      = REQUESTOR_DUMMY_USERID,
                        GroupID              = groupId,
                        JobID                = jobId,
                        RequestID            = requestId,
                        AdditionalParameters = param
                    });
                }
            }

            //Now consider the requestor
            if (!string.IsNullOrEmpty(requestorEmailAddress) &&
                requestorEmailAddress != volunteerEmailAddress && requestorEmailAddress != recipientEmailAddress)
            {
                if (createdByUserID.HasValue && createdByUserID.Value != -1)
                {
                    var param = new Dictionary <string, string>(additionalParameters)
                    {
                        { "RequestRole", RequestRoles.Requestor.ToString() }
                    };
                    _sendMessageRequests.Add(new SendMessageRequest()
                    {
                        TemplateName         = TemplateName.TaskUpdateSimplified,
                        RecipientUserID      = REQUESTOR_DUMMY_USERID,
                        GroupID              = groupId,
                        JobID                = jobId,
                        RequestID            = requestId,
                        AdditionalParameters = param
                    });
                }
            }

            return(_sendMessageRequests);
        }
Esempio n. 28
0
        private string SenderAndContextVolunteer(string senderName, string helpRecipient, RequestRoles toRole)
        {
            switch (toRole)
            {
            case RequestRoles.Recipient:
                return($"<strong>{senderName}</strong>, the volunteer who accepted the request for help.");

            case RequestRoles.Requestor:
                return($"<strong>{senderName}</strong>, the volunteer who accepted the request for <strong>{helpRecipient}</strong>.");

            case RequestRoles.GroupAdmin:
                return($"<strong>{senderName}</strong>, the volunteer who helped <strong>{helpRecipient}</strong>.");

            default:
                throw new Exception($"Invalid Request Role {toRole}");
            }
        }