Exemplo n.º 1
0
        public async Task ShouldReturnQuestionThatIsRequested()
        {
            _userSessionRepository.GetUserSession(Arg.Any <string>()).Returns(Task.FromResult(new UserSession()
            {
                AssessmentState = new AssessmentState("question-set", 5)
                {
                    CurrentQuestion = 1
                }
            }));

            _questionRepository.GetQuestion(1, "question-set")
            .Returns(Task.FromResult(new Question
            {
                QuestionId = "1",
                Texts      = new []
                {
                    new QuestionText()
                    {
                        LanguageCode = "en", Text = "Unit test question"
                    }
                },
                Order     = 1,
                TraitCode = "DOER"
            }));

            var result = await RunFunction("201901-session1");

            var content = await result.Content.ReadAsAsync <AssessmentQuestionResponse>();

            Assert.IsType <HttpResponseMessage>(result);
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Assert.Equal(1, content.QuestionNumber);
            Assert.Equal(1, content.NextQuestionNumber);
        }
Exemplo n.º 2
0
        public async Task ShouldReturnOkWithValidRequest()
        {
            var body = new SendSessionSmsRequest
            {
                Domain       = "discover-skills-and-careers.co.uk",
                MobileNumber = "0123456789",
                SessionId    = "201904-282gk265gzmzyz",
                TemplateId   = "3B840739-F4C5-40AA-93E9-6827A6F29003"
            };

            _userSessionRepository.GetUserSession("201904-282gk265gzmzyz").Returns(Task.FromResult(new UserSession
            {
                UserSessionId = "201904-282gk265gzmzyz"
            }));

            _notifyClient.SendSms(body.Domain, body.MobileNumber, body.TemplateId, body.SessionId).Returns(Task.CompletedTask);

            var result = await RunFunction(body);

            Assert.IsType <HttpResponseMessage>(result);
            var content = await result.Content.ReadAsAsync <SendSessionSmsResponse>();

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Assert.True(content.IsSuccess);
        }
Exemplo n.º 3
0
        public async Task ResultsHttpTriggerTest_OnException_ShouldReturn500()
        {
            _httpResponseMessageHelper = new HttpResponseMessageHelper();

            _userSessionRepository.GetUserSession("session1").Throws(new Exception());

            var result = await RunFunction("session1");

            Assert.IsType <HttpResponseMessage>(result);
            Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
        }
Exemplo n.º 4
0
        public string GetAccessToken(string userName)
        {
            var userSession = _userSessionRepository.GetUserSession(userName);

            if (userSession == null || userSession.RequestToken == null)
            {
                return(null);
            }

            if (userSession.AccessToken != null)
            {
                return(userSession.AccessToken);
            }

            return(null);
        }
Exemplo n.º 5
0
        public async Task PostAnswerHttpTrigger_UnableToFindQuestion_ShouldReturnNoContent()
        {
            _httpResponseMessageHelper = new HttpResponseMessageHelper();
            var postAnswerRequest = new PostAnswerRequest()
            {
                QuestionId     = "1",
                SelectedOption = "Agree"
            };

            _questionRepository.GetQuestion("1").Returns(Task.FromResult <Question>(null));

            _userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(new UserSession
            {
                AssessmentState = new AssessmentState("QS-1", 5)
            }));

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);

            _request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

            var result = await RunFunction("session1");

            Assert.IsType <HttpResponseMessage>(result);
            Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
        }
Exemplo n.º 6
0
        public async Task NewFilterSessionHttpTrigger_WithMissingUserSession_ShouldReturnBadRequest()
        {
            _httpResponseMessageHelper = new HttpResponseMessageHelper();

            _userSessionRepository.GetUserSession("session1").Returns(Task.FromResult <UserSession>(null));

            var result = await RunFunction("session1", "animal-care");

            Assert.IsType <HttpResponseMessage>(result);
            Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "assessment/{sessionId}/reload")] HttpRequest req,
            string sessionId,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionRepository questionRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(appSettings?.Value.SessionSalt))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} -Session salt not missing from configuration");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (!sessionId.Contains("-"))
                {
                    string partitionKey = PartitionKeyGenerator.UserSession(sessionId);
                    sessionId = $"{partitionKey}-{sessionId}";
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                if (userSession.ResultData?.JobCategories?.Length == 0)
                {
                    userSession.AssessmentState.CurrentQuestion = 1;
                    userSession.AssessmentState.RecordedAnswers = new Answer[] {};
                    userSession.ResultData = null;
                    await userSessionRepository.UpdateUserSession(userSession);
                }

                var questionSetVersion = userSession.CurrentQuestionSetVersion;

                var question = await questionRepository.GetQuestion(userSession.CurrentQuestion, questionSetVersion);

                if (question == null)
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Question number {userSession.CurrentQuestion} could not be found on session {userSession.PrimaryKey}");
                    return(httpResponseMessageHelper.NoContent());
                }

                int percentComplete = Convert.ToInt32((((decimal)userSession.CurrentQuestion - 1M) / (decimal)userSession.MaxQuestions) * 100);
                var response        = new AssessmentQuestionResponse()
                {
                    CurrentFilterAssessmentCode = userSession.FilteredAssessmentState?.CurrentFilterAssessmentCode,
                    IsComplete           = userSession.IsComplete,
                    NextQuestionNumber   = question.IsFilterQuestion ? userSession.FilteredAssessmentState?.MoveToNextQuestion() : userSession.AssessmentState.MoveToNextQuestion(),
                    QuestionId           = question.QuestionId,
                    QuestionText         = question.Texts.FirstOrDefault(x => x.LanguageCode.ToLower() == "en")?.Text,
                    TraitCode            = question.TraitCode,
                    QuestionNumber       = question.Order,
                    SessionId            = userSession.PrimaryKey,
                    PercentComplete      = percentComplete,
                    ReloadCode           = userSession.UserSessionId,
                    MaxQuestionsCount    = userSession.MaxQuestions,
                    RecordedAnswersCount = userSession.RecordedAnswers.Count(),
                    StartedDt            = userSession.StartedDt,
                    IsFilterAssessment   = userSession.IsFilterAssessment,
                    JobCategorySafeUrl   = (userSession.CurrentState as FilteredAssessmentState)?.JobFamilyNameUrlSafe
                };

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(response)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Exemplo n.º 8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "result/{sessionId}/{jobCategory}")] HttpRequest req,
            string sessionId,
            string jobCategory,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IJobProfileRepository jobProfileRepository)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"Correlation Id: {correlationId} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogInformation($"Correlation Id: {correlationId} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                if (userSession.ResultData == null)
                {
                    log.LogInformation($"Correlation Id: {correlationId} - Result data does not yet exist for session {userSession.PrimaryKey}");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var traits      = userSession.ResultData.Traits;
                int traitsTake  = (traits.Length > 3 && traits[2].TotalScore == traits[3].TotalScore) ? 4 : 3;
                var jobFamilies = userSession.ResultData.JobCategories;

                if (!jobCategory.EqualsIgnoreCase("short"))
                {
                    jobCategory = JobCategoryHelper.GetCode(jobCategory);
                }

                var suggestedJobProfiles = new List <JobProfileResult>();
                foreach (var category in jobFamilies)
                {
                    if (category.FilterAssessmentResult == null)
                    {
                        continue;
                    }

                    var categoryProfiles = new List <JobProfileResult>();
                    if (category.TotalQuestions == 0)
                    {
                        // Build the list of job profiles
                        var jobProfiles =
                            await jobProfileRepository.JobProfilesForJobFamily(category.JobCategoryName);

                        var profilesSet = category.FilterAssessmentResult.SuggestedJobProfiles.ToHashSet(StringComparer.InvariantCultureIgnoreCase);

                        foreach (var jobProfile in jobProfiles.Where(p =>
                                                                     (p.JobProfileCategories == null || p.JobProfileCategories.Contains(category.JobCategoryName, StringComparer.InvariantCultureIgnoreCase)) &&
                                                                     profilesSet.Contains(p.Title))
                                 )
                        {
                            categoryProfiles.Add(new JobProfileResult()
                            {
                                CareerPathAndProgression = jobProfile.CareerPathAndProgression,
                                Overview           = jobProfile.Overview,
                                SalaryExperienced  = jobProfile.SalaryExperienced,
                                SalaryStarter      = jobProfile.SalaryStarter,
                                JobCategory        = category.JobCategoryName,
                                SocCode            = jobProfile.SocCode,
                                Title              = jobProfile.Title,
                                UrlName            = jobProfile.UrlName,
                                TypicalHours       = jobProfile.TypicalHours,
                                TypicalHoursPeriod = String.Join("/", jobProfile.WorkingHoursDetails),
                                ShiftPattern       = String.Join("/", jobProfile.WorkingPattern),
                                ShiftPatternPeriod = String.Join("/", jobProfile.WorkingPatternDetails),
                                WYDDayToDayTasks   = jobProfile.WYDDayToDayTasks
                            });
                        }
                    }

                    category.ResultsShown =
                        category.ResultsShown ||
                        category.JobCategoryCode.EqualsIgnoreCase(jobCategory) ||
                        (category.TotalQuestions == 0 && (categoryProfiles.Count == 0));

                    suggestedJobProfiles.AddRange(categoryProfiles);
                }

                var model = new ResultsResponse()
                {
                    AssessmentType     = userSession.AssessmentType,
                    SessionId          = userSession.UserSessionId,
                    JobFamilyCount     = userSession.ResultData.JobCategories.Length,
                    JobFamilyMoreCount = userSession.ResultData.JobCategories.Length - 3,
                    Traits             = traits.Take(traitsTake).Select(x => x.TraitText).ToArray(),
                    JobCategories      = jobFamilies,
                    JobProfiles        = suggestedJobProfiles.ToArray(),
                    WhatYouToldUs      = userSession.ResultData?.JobCategories.SelectMany(r => r.FilterAssessmentResult?.WhatYouToldUs ?? new string[] { }).Distinct().ToArray() ?? new string[] { }
                };

                await userSessionRepository.UpdateUserSession(userSession);

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(model)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "assessment/{sessionId}/{assessment}/q/{questionNumber}")] HttpRequest req,
            string sessionId,
            string assessment,
            int questionNumber,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionRepository questionRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(assessment))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Assessment not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(appSettings?.Value.SessionSalt))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} -Session salt not missing from configuration");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (!sessionId.Contains("-"))
                {
                    var datetimeStamp = SessionIdHelper.Decode(appSettings?.Value.SessionSalt, sessionId);
                    if (datetimeStamp == null)
                    {
                        log.LogError($"CorrelationId: {correlationGuid} - Could not decode session id correctly: {sessionId}");
                        return(httpResponseMessageHelper.BadRequest());
                    }
                    string partitionKey = SessionIdHelper.GetYearMonth(datetimeStamp);
                    sessionId = $"{partitionKey}-{sessionId}";
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                Question question = null;

                if (assessment.EqualsIgnoreCase("short"))
                {
                    if (userSession.AssessmentState.IsComplete && questionNumber == 1)
                    {
                        userSession.AssessmentState.RecordedAnswers = new Answer[] {};
                        await userSessionRepository.UpdateUserSession(userSession);
                    }

                    question = await questionRepository.GetQuestion(questionNumber, userSession.CurrentQuestionSetVersion);

                    userSession.AssessmentState.CurrentQuestion = questionNumber;
                }
                else
                {
                    userSession.FilteredAssessmentState.CurrentFilterAssessmentCode = JobCategoryHelper.GetCode(assessment);
                    userSession.FilteredAssessmentState.CurrentQuestion             = questionNumber;

                    question = await questionRepository.GetQuestion(userSession.FilteredAssessmentState.CurrentQuestionId);
                }

                if (question == null)
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Question number {userSession.CurrentQuestion} could not be found on session {userSession.PrimaryKey}");
                    return(httpResponseMessageHelper.NoContent());
                }

                var percentageComplete = userSession.AssessmentState.PercentageComplete;

                var nextQuestion = question.IsFilterQuestion ? userSession.FilteredAssessmentState.MoveToNextQuestion() : userSession.AssessmentState.MoveToNextQuestion();
                await userSessionRepository.UpdateUserSession(userSession);

                var response = new AssessmentQuestionResponse()
                {
                    CurrentFilterAssessmentCode = userSession.FilteredAssessmentState?.CurrentFilterAssessmentCode,
                    IsComplete           = question.IsFilterQuestion ? (userSession.FilteredAssessmentState?.IsComplete ?? false) : userSession.AssessmentState.IsComplete,
                    NextQuestionNumber   = nextQuestion,
                    QuestionId           = question.QuestionId,
                    QuestionText         = question.Texts.FirstOrDefault(x => x.LanguageCode.ToLower() == "en")?.Text,
                    TraitCode            = question.TraitCode,
                    QuestionNumber       = questionNumber,
                    SessionId            = userSession.PrimaryKey,
                    PercentComplete      = percentageComplete,
                    ReloadCode           = userSession.UserSessionId,
                    MaxQuestionsCount    = userSession.MaxQuestions,
                    RecordedAnswersCount = userSession.RecordedAnswers.Length,
                    RecordedAnswer       = userSession.RecordedAnswers.SingleOrDefault(r => r?.QuestionId == question.QuestionId)?.SelectedOption,
                    StartedDt            = userSession.StartedDt,
                    IsFilterAssessment   = !assessment.EqualsIgnoreCase("short"),
                    JobCategorySafeUrl   = userSession.FilteredAssessmentState?.JobFamilyNameUrlSafe
                };

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(response)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment/{sessionId}")] HttpRequest req,
            string sessionId,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionRepository questionRepository,
            [Inject] IAssessmentCalculationService resultsService,
            [Inject] IFilterAssessmentCalculationService filterAssessmentCalculationService)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                PostAnswerRequest postAnswerRequest;
                using (var streamReader = new StreamReader(req.Body))
                {
                    var body = streamReader.ReadToEnd();
                    postAnswerRequest = JsonConvert.DeserializeObject <PostAnswerRequest>(body);
                }

                AnswerOption answerValue;
                if (Enum.TryParse(postAnswerRequest.SelectedOption, out answerValue) == false)
                {
                    log.LogInformation(
                        $"CorrelationId: {correlationGuid} - Answer supplied is invalid {postAnswerRequest.SelectedOption}");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                var question = await questionRepository.GetQuestion(postAnswerRequest.QuestionId);

                if (question == null)
                {
                    log.LogInformation(
                        $"CorrelationId: {correlationGuid} - Question Id does not exist {postAnswerRequest.QuestionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                userSession.AddAnswer(answerValue, question);

                await TryEvaluateSession(log, resultsService, filterAssessmentCalculationService, userSession);

                var displayFinish = question.IsFilterQuestion
                    ? userSession.FilteredAssessmentState.IsComplete
                    : userSession.AssessmentState.IsComplete;

                if (!question.IsFilterQuestion)
                {
                    userSession.AssessmentState.CurrentQuestion = question.Order;
                }

                var result = new PostAnswerResponse()
                {
                    IsSuccess          = true,
                    IsComplete         = displayFinish,
                    IsFilterAssessment = question.IsFilterQuestion,
                    JobCategorySafeUrl = question.IsFilterQuestion ? userSession.FilteredAssessmentState.JobFamilyNameUrlSafe : null,
                    NextQuestionNumber = question.IsFilterQuestion ? userSession.FilteredAssessmentState.MoveToNextQuestion() : userSession.AssessmentState.MoveToNextQuestion()
                };

                await userSessionRepository.UpdateUserSession(userSession);

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.Message);
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Exemplo n.º 11
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment/notify/email")] HttpRequest req,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] INotifyClient notifyClient)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                SendSessionEmailRequest sendSessionEmailRequest;
                using (var streamReader = new StreamReader(req.Body))
                {
                    var body = streamReader.ReadToEnd();
                    sendSessionEmailRequest = JsonConvert.DeserializeObject <SendSessionEmailRequest>(body);
                }

                if (sendSessionEmailRequest == null || string.IsNullOrEmpty(sendSessionEmailRequest.SessionId))
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(sendSessionEmailRequest.Domain))
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Domain not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(sendSessionEmailRequest.TemplateId))
                {
                    log.LogError($"CorrelationId: {correlationGuid} - TemplateId not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                if (string.IsNullOrEmpty(sendSessionEmailRequest.EmailAddress))
                {
                    log.LogError($"CorrelationId: {correlationGuid} - EmailAddress not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var userSession = await userSessionRepository.GetUserSession(sendSessionEmailRequest.SessionId);

                if (userSession == null)
                {
                    log.LogError($"CorrelationId: {correlationGuid} - Session Id does not exist {sendSessionEmailRequest.SessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                await notifyClient.SendEmail(sendSessionEmailRequest.Domain, sendSessionEmailRequest.EmailAddress, sendSessionEmailRequest.TemplateId, userSession.UserSessionId);

                var result = new SendSessionEmailResponse()
                {
                    IsSuccess = true,
                };

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                var result = new SendSessionEmailResponse()
                {
                    IsSuccess = false,
                    Message   = ex.Message
                };
                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
        }
Exemplo n.º 12
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment/filtered/{sessionId}/{jobCategory}")] HttpRequest req,
            string sessionId,
            string jobCategory,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogInformation("Unable to locate 'DssCorrelationId' in request header");
                }

                if (!Guid.TryParse(correlationId, out var correlationGuid))
                {
                    log.LogInformation("Unable to parse 'DssCorrelationId' to a Guid");
                    correlationGuid = Guid.NewGuid();
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id not supplied");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var userSession = await userSessionRepository.GetUserSession(sessionId);

                if (userSession == null)
                {
                    log.LogInformation($"CorrelationId: {correlationGuid} - Session Id does not exist {sessionId}");
                    return(httpResponseMessageHelper.NoContent());
                }

                if (userSession.ResultData == null)
                {
                    log.LogInformation(
                        $"CorrelationId: {correlationGuid} - Session Id {sessionId} has not completed the short assessment");
                    return(httpResponseMessageHelper.BadRequest());
                }

                var code = JobCategoryHelper.GetCode(jobCategory);

                if (!userSession.FilteredAssessmentState.JobCategoryStates.Any(j => j.JobCategoryCode.EqualsIgnoreCase(code)))
                {
                    return(httpResponseMessageHelper.BadRequest());
                }

                userSession.FilteredAssessmentState.CurrentFilterAssessmentCode = code;

                if (userSession.FilteredAssessmentState.IsComplete)
                {
                    userSession.FilteredAssessmentState.RemoveAnswersForCategory(code);
                }

                var questionNumber = userSession.FilteredAssessmentState.MoveToNextQuestion();

                await userSessionRepository.UpdateUserSession(userSession);

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(new FilterSessionResponse()
                {
                    SessionId = userSession.PrimaryKey,
                    QuestionNumber = questionNumber
                })));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }