public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "customers/{customerId}/ContactDetails/{contactid}")] HttpRequest req, ILogger log, string customerId, string contactid)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("C# HTTP trigger function GetContactByIdHttpTrigger processed a request. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(contactid, out var contactGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(contactGuid));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var contact = await _getContactDetailsByIdService.GetContactDetailsForCustomerAsync(customerGuid, contactGuid);

            return(contact == null?
                   _httpResponseMessageHelper.NoContent(contactGuid) :
                       _httpResponseMessageHelper.Ok(JsonHelper.SerializeObject(contact)));
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Customers/{customerId}/Interactions/")] HttpRequest req, ILogger log, string customerId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'APIM-TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("Get Interaction C# HTTP trigger function  processed a request. By Touchpoint. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var interactions = await _interactionGetService.GetInteractionsAsync(customerGuid);

            return(interactions == null?
                   _httpResponseMessageHelper.NoContent(customerGuid) :
                       _httpResponseMessageHelper.Ok(_jsonHelper.SerializeObjectsAndRenameIdProperty(interactions, "id", "InteractionId")));
        }
Example #3
0
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Customers/{customerId}/Subscriptions/{subscriptionId}")] HttpRequest req, TraceWriter log, string customerId, string subscriptionId)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(subscriptionId, out var subscriptionsGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(subscriptionsGuid));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var subscriptions = await _getSubscriptionsByIdService.GetSubscriptionsForCustomerAsync(customerGuid, subscriptionsGuid);

            return(subscriptions == null?
                   _httpResponseMessageHelper.NoContent(subscriptionsGuid) :
                       _httpResponseMessageHelper.Ok(JsonHelper.SerializeObject(subscriptions)));
        }
Example #4
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "paths/{path}/regions/{pageRegion}")]
            HttpRequest req,
            ILogger log,
            string path,
            int pageRegion,
            [Inject] ILoggerHelper loggerHelper,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IJsonHelper jsonHelper,
            [Inject] IRegionService regionService
            )
        {
            loggerHelper.LogMethodEnter(log);

            // validate the parameters are present
            var dssCorrelationId = httpRequestHelper.GetDssCorrelationId(req);

            if (string.IsNullOrEmpty(dssCorrelationId))
            {
                log.LogInformation($"Unable to locate '{nameof(dssCorrelationId)}' in request header");
            }

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

            if (string.IsNullOrEmpty(path))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing value in request for '{nameof(path)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            if (pageRegion == 0 || !Enum.IsDefined(typeof(PageRegions), pageRegion))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing/invalid value in request for '{nameof(pageRegion)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            PageRegions pageRegionValue = (PageRegions)pageRegion;

            loggerHelper.LogInformationMessage(log, correlationGuid, $"Attempting to get Region {pageRegionValue} for Path {path}");

            var regionModel = await regionService.GetAsync(path, pageRegionValue);

            if (regionModel == null)
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Region does not exist for {pageRegionValue} for Path {path}");
                return(httpResponseMessageHelper.NoContent());
            }

            loggerHelper.LogMethodExit(log);

            return(regionModel != null
                ? httpResponseMessageHelper.Ok(jsonHelper.SerializeObjectAndRenameIdProperty(regionModel, "id", nameof(Models.Region.DocumentId)))
                : httpResponseMessageHelper.NoContent());
        }
        public static async Task <HttpResponseMessage> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "collections")] HttpRequest req,
            ILogger log,
            [Inject] IGetCollectionsHttpTriggerService service,
            [Inject] IJsonHelper jsonHelper,
            [Inject] IHttpRequestHelper requestHelper,
            [Inject] IHttpResponseMessageHelper responseMessageHelper)
        {
            log.LogInformation("Get Collections C# HTTP trigger function processing a request. TouchpointId " + requestHelper.GetDssTouchpointId(req));

            try
            {
                var results = await service.ProcessRequestAsync();

                if (results.Count == 0)
                {
                    return(responseMessageHelper.NoContent());
                }

                return(responseMessageHelper.Ok(jsonHelper.SerializeObjectsAndRenameIdProperty <Collection>(results, "id", "CollectionId")));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Get Collections C# HTTP trigger function");
                return(responseMessageHelper.UnprocessableEntity());
            }
        }
        public static async Task <HttpResponseMessage> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "collections/{collectionId}")] HttpRequest req, string collectionId,
            ILogger log,
            [Inject] IGetCollectionByIdHtppTriggerService service,
            [Inject] IJsonHelper jsonHelper,
            [Inject] IHttpResponseMessageHelper responseMessageHelper)
        {
            log.LogInformation("Get Collection C# HTTP trigger function processing a request. For CollectionId " + collectionId);

            try
            {
                var collection = await service.ProcessRequestAsync(collectionId);

                if (collection == null)
                {
                    return(responseMessageHelper.NoContent());
                }

                return(responseMessageHelper.Ok(jsonHelper.SerializeObjectAndRenameIdProperty <Collection>(collection, "id", "CollectionId")));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Get Collection C# HTTP trigger function");
                return(responseMessageHelper.UnprocessableEntity());
            }
        }
Example #7
0
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Customers/{customerId}/Interactions/{interactionId}/Transfers/{transferId}")] HttpRequest req, ILogger log, string customerId, string interactionId, string transferId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("Get Transfer By Id C# HTTP trigger function  processed a request. By Touchpoint. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(interactionId, out var interactionGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(interactionGuid));
            }

            if (!Guid.TryParse(transferId, out var transferGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(transferGuid));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var doesInteractionExist = _resourceHelper.DoesInteractionResourceExistAndBelongToCustomer(interactionGuid, customerGuid);

            if (!doesInteractionExist)
            {
                return(_httpResponseMessageHelper.NoContent(interactionGuid));
            }

            var transfer = await _transferByIdService.GetTransferForCustomerAsync(customerGuid, transferGuid);

            return(transfer == null?
                   _httpResponseMessageHelper.NoContent(transferGuid) :
                       _httpResponseMessageHelper.Ok(_jsonHelper.SerializeObjectAndRenameIdProperty(transfer, "id", "TransferId")));
        }
Example #8
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "questionset/{assessmentType}/{title}/{version}")] HttpRequest req,
            string assessmentType,
            string title,
            int version,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IQuestionSetRepository questionSetRepository)
        {
            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();
                }

                var questionSet = await questionSetRepository.GetQuestionSetVersion(assessmentType, title, version);

                if (questionSet == null)
                {
                    log.LogInformation($"Correlation Id: {correlationId} - Question set version does not exist {version}");
                    return(httpResponseMessageHelper.NoContent());
                }

                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(questionSet)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Example #9
0
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Customers/{customerId}/Subscriptions/")] HttpRequest req, ILogger log, string customerId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'APIM-TouchpointId' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            var subscriptions = await _getSubscriptionsForTouchpointService.GetSubscriptionsForTouchpointAsync(customerGuid, touchpointId);

            return(subscriptions == null?
                   _httpResponseMessageHelper.NoContent(customerGuid) :
                       _httpResponseMessageHelper.Ok(JsonHelper.SerializeObjects(subscriptions)));
        }
Example #10
0
        public async Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "customers/{customerId}/ContactDetails/{contactid}")] HttpRequest req, ILogger log,
                                                         string customerId, string contactid)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            var ApimURL = _httpRequestMessageHelper.GetDssApimUrl(req);

            if (string.IsNullOrEmpty(ApimURL))
            {
                log.LogInformation("Unable to locate 'apimurl' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("C# HTTP trigger function Patch Contact processed a request. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(contactid, out var contactGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(contactGuid));
            }

            ContactDetailsPatch contactdetailsPatchRequest;

            try
            {
                contactdetailsPatchRequest = await _httpRequestMessageHelper.GetResourceFromRequest <ContactDetailsPatch>(req);
            }
            catch (JsonException ex)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (contactdetailsPatchRequest == null)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(req));
            }

            contactdetailsPatchRequest.LastModifiedTouchpointId = touchpointId;

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var isCustomerReadOnly = await _resourceHelper.IsCustomerReadOnly(customerGuid);

            if (isCustomerReadOnly)
            {
                return(_httpResponseMessageHelper.Forbidden(customerGuid));
            }

            var contactdetails = await _contactdetailsPatchService.GetContactDetailsForCustomerAsync(customerGuid, contactGuid);

            if (contactdetails == null)
            {
                return(_httpResponseMessageHelper.NoContent(contactGuid));
            }

            var errors = _validate.ValidateResource(contactdetailsPatchRequest, contactdetails, false);

            if (!string.IsNullOrEmpty(contactdetailsPatchRequest.EmailAddress))
            {
                var contacts = await _provider.GetContactsByEmail(contactdetailsPatchRequest.EmailAddress);

                if (contacts != null)
                {
                    foreach (var contact in contacts)
                    {
                        var isReadOnly = await _provider.DoesCustomerHaveATerminationDate(contact.CustomerId.GetValueOrDefault());

                        if (!isReadOnly && contact.CustomerId != contactdetails.CustomerId)
                        {
                            //if a customer that has the same email address is not readonly (has date of termination)
                            //then email address on the request cannot be used.
                            return(_httpResponseMessageHelper.Conflict());
                        }
                    }
                }
            }

            // Set Digital account properties so that contentenhancer can queue change on digital identity topic.
            var diaccount = await _provider.GetIdentityForCustomerAsync(contactdetails.CustomerId.Value);

            if (diaccount != null)
            {
                if (contactdetailsPatchRequest.EmailAddress == string.Empty)
                {
                    if (errors == null)
                    {
                        errors = new List <System.ComponentModel.DataAnnotations.ValidationResult>();
                    }
                    errors.Add(new System.ComponentModel.DataAnnotations.ValidationResult("Email Address cannot be removed because it is associated with a Digital Account", new List <string>()
                    {
                        "EmailAddress"
                    }));
                    return(_httpResponseMessageHelper.UnprocessableEntity(errors));
                }

                if (!string.IsNullOrEmpty(contactdetails.EmailAddress) && !string.IsNullOrEmpty(contactdetailsPatchRequest.EmailAddress) && contactdetails.EmailAddress?.ToLower() != contactdetailsPatchRequest.EmailAddress?.ToLower() && diaccount.IdentityStoreId.HasValue)
                {
                    contactdetails.SetDigitalAccountEmailChanged(contactdetailsPatchRequest.EmailAddress?.ToLower(), diaccount.IdentityStoreId.Value);
                }
            }

            if (errors != null && errors.Any())
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(errors));
            }

            var updatedContactDetails = await _contactdetailsPatchService.UpdateAsync(contactdetails, contactdetailsPatchRequest);

            if (updatedContactDetails != null)
            {
                await _contactdetailsPatchService.SendToServiceBusQueueAsync(updatedContactDetails, customerGuid, ApimURL);
            }

            return(updatedContactDetails == null?
                   _httpResponseMessageHelper.BadRequest(contactGuid) :
                       _httpResponseMessageHelper.Ok(JsonHelper.SerializeObject(updatedContactDetails)));
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Customers/{customerId}/Subscriptions")] HttpRequest req, ILogger log, string customerId)
        {
            var touchpointId = _httpRequestHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("C# HTTP trigger function processed a request. By Touchpoint " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            Models.Subscriptions subscriptionsRequest;

            try
            {
                subscriptionsRequest = await _httpRequestHelper.GetResourceFromRequest <Models.Subscriptions>(req);
            }
            catch (JsonSerializationException ex)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (subscriptionsRequest == null)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(req));
            }

            subscriptionsRequest.SetIds(customerGuid, touchpointId);

            var errors = _validate.ValidateResource(subscriptionsRequest);

            if (errors != null && errors.Any())
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(errors));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var doesSubscriptionExist = await _resourceHelper.DoesSubscriptionExist(customerGuid, touchpointId);

            if (doesSubscriptionExist.HasValue)
            {
                var duplicateError = _validate.ValidateResultForDuplicateSubscriptionId(doesSubscriptionExist.GetValueOrDefault());
                return(_httpResponseMessageHelper.Conflict());
            }

            var subscriptions = await _subscriptionsPostService.CreateAsync(subscriptionsRequest);

            return(subscriptions == null
                ? _httpResponseMessageHelper.BadRequest(customerGuid)
                : _httpResponseMessageHelper.Created(JsonHelper.SerializeObject(subscriptions)));
        }
Example #12
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
                });
            }
        }
Example #15
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)));
            }
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "Customers/{customerId}/Subscriptions/{subscriptionId}")] HttpRequest req, ILogger log, string customerId, string subscriptionId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("C# HTTP trigger function processed a request. By Touchpoint " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(subscriptionId, out var subscriptionsGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(subscriptionsGuid));
            }

            SubscriptionsPatch subscriptionsPatchRequest;

            try
            {
                subscriptionsPatchRequest = await _httpRequestMessageHelper.GetResourceFromRequest <SubscriptionsPatch>(req);
            }
            catch (JsonSerializationException ex)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (subscriptionsPatchRequest == null)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(req));
            }

            subscriptionsPatchRequest.LastModifiedBy = touchpointId;

            var errors = _validate.ValidateResource(subscriptionsPatchRequest);

            if (errors != null && errors.Any())
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(errors));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var subscriptions = await _subscriptionsPatchService.GetSubscriptionsForCustomerAsync(customerGuid, subscriptionsGuid);

            if (subscriptions == null)
            {
                return(_httpResponseMessageHelper.NoContent(subscriptionsGuid));
            }

            var updatedSubscriptions = await _subscriptionsPatchService.UpdateAsync(subscriptions, subscriptionsPatchRequest);

            return(updatedSubscriptions == null?
                   _httpResponseMessageHelper.BadRequest(subscriptionsGuid) :
                       _httpResponseMessageHelper.Ok(JsonHelper.SerializeObject(updatedSubscriptions)));
        }
Example #17
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "assessment")] HttpRequest req,
            ILogger log,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IUserSessionRepository userSessionRepository,
            [Inject] IQuestionSetRepository questionSetRepository,
            [Inject] IOptions <AppSettings> appSettings)
        {
            try
            {
                var correlationId = httpRequestHelper.GetDssCorrelationId(req);
                if (string.IsNullOrEmpty(correlationId))
                {
                    log.LogWarning("Unable to locate 'DssCorrelationId' in request header");
                    correlationId = Guid.NewGuid().ToString();
                }

                log.LogInformation($"CorrelationId: {correlationId} - Creating a new assessment");

                // Get the assessmentType and questionSetTitle values from the query string
                var queryDictionary = System.Web.HttpUtility.ParseQueryString(req.QueryString.ToString());
                var assessmentType  = queryDictionary.Get("assessmentType");
                if (string.IsNullOrEmpty(assessmentType))
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Missing assessmentType {assessmentType}");
                    return(httpResponseMessageHelper.BadRequest());
                }

                // Get the current question set version for this assesssment type and title (supplied by CMS - configured in appsettings)
                var currentQuestionSetInfo = await questionSetRepository.GetCurrentQuestionSet(assessmentType);

                if (currentQuestionSetInfo == null)
                {
                    log.LogInformation($"CorrelationId: {correlationId} - Unable to load latest question set {assessmentType}");
                    return(httpResponseMessageHelper.NoContent());
                }


                // Create a new user session
                string salt         = appSettings.Value.SessionSalt;
                string sessionId    = SessionIdHelper.GenerateSessionId(salt);
                string partitionKey = PartitionKeyGenerator.UserSession(sessionId);

                var userSession = new UserSession()
                {
                    UserSessionId   = sessionId,
                    Salt            = salt,
                    StartedDt       = DateTime.Now,
                    LanguageCode    = "en",
                    PartitionKey    = partitionKey,
                    AssessmentState = new AssessmentState(currentQuestionSetInfo.QuestionSetVersion, currentQuestionSetInfo.MaxQuestions),
                    AssessmentType  = currentQuestionSetInfo.AssessmentType.ToLower()
                };
                await userSessionRepository.CreateUserSession(userSession);

                log.LogInformation($"CorrelationId: {correlationId} - Finished creating new assessment {userSession.UserSessionId}");

                var result = new FilterSessionResponse()
                {
                    SessionId = userSession.PrimaryKey
                };
                return(httpResponseMessageHelper.Ok(JsonConvert.SerializeObject(result)));
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Fatal exception {message}", ex.ToString());
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Example #18
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "paths/{path}/regions/{pageRegion}")]
            HttpRequest req,
            ILogger log,
            string path,
            int pageRegion,
            [Inject] ILoggerHelper loggerHelper,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IJsonHelper jsonHelper,
            [Inject] IRegionService regionService
            )
        {
            loggerHelper.LogMethodEnter(log);

            // validate the parameters are present
            var correlationId = httpRequestHelper.GetOrCreateDssCorrelationId(req);

            if (string.IsNullOrEmpty(path))
            {
                loggerHelper.LogInformationMessage(log, correlationId, $"Missing value in request for '{nameof(path)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            if (pageRegion == 0 || !Enum.IsDefined(typeof(PageRegions), pageRegion))
            {
                loggerHelper.LogInformationMessage(log, correlationId, $"Missing/invalid value in request for '{nameof(pageRegion)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            PageRegions pageRegionValue = (PageRegions)pageRegion;

            JsonPatchDocument <Region> regionPatch;

            try
            {
                regionPatch = await httpRequestHelper.GetResourceFromRequest <JsonPatchDocument <Region> >(req);

                if (regionPatch == null)
                {
                    loggerHelper.LogException(log, correlationId, "Request body is empty", null);
                    return(httpResponseMessageHelper.BadRequest());
                }
            }
            catch (Exception ex)
            {
                loggerHelper.LogException(log, correlationId, ex);
                return(httpResponseMessageHelper.BadRequest());
            }

            loggerHelper.LogInformationMessage(log, correlationId, $"Attempting to get Region {pageRegionValue} for Path {path}");

            var currentRegion = await regionService.GetAsync(path, pageRegionValue);

            if (currentRegion == null)
            {
                loggerHelper.LogInformationMessage(log, correlationId, $"Region does not exist for {pageRegionValue} for Path {path}");
                return(httpResponseMessageHelper.NoContent());
            }

            try
            {
                loggerHelper.LogInformationMessage(log, correlationId, $"Attempting to apply patch to {path} region {pageRegionValue}");
                regionPatch?.ApplyTo(currentRegion);
                var validationResults = currentRegion.Validate(new ValidationContext(currentRegion));

                if (validationResults.Any())
                {
                    loggerHelper.LogInformationMessage(log, correlationId, "Validation Failed");
                    return(httpResponseMessageHelper.UnprocessableEntity(validationResults.ToList()));
                }
            }
            catch (Exception ex)
            {
                loggerHelper.LogException(log, correlationId, ex);
                return(httpResponseMessageHelper.BadRequest());
            }

            try
            {
                loggerHelper.LogInformationMessage(log, correlationId, $"Attempting to update path {path}");
                var patchedRegion = await regionService.ReplaceAsync(currentRegion);

                loggerHelper.LogMethodExit(log);
                return(httpResponseMessageHelper.Ok(jsonHelper.SerializeObjectAndRenameIdProperty(patchedRegion, "id", nameof(Models.Region.DocumentId))));
            }
            catch (Exception ex)
            {
                loggerHelper.LogException(log, correlationId, ex);
                return(httpResponseMessageHelper.UnprocessableEntity(new JsonException(ex.Message, ex)));
            }
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "Customers/{customerId}/Interactions/{interactionId}")] HttpRequest req, ILogger log, string customerId, string interactionId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'APIM-TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            var ApimURL = _httpRequestMessageHelper.GetDssApimUrl(req);

            if (string.IsNullOrEmpty(ApimURL))
            {
                log.LogInformation("Unable to locate 'apimurl' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("Patch Interaction C# HTTP trigger function processed a request. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(interactionId, out var interactionGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(interactionGuid));
            }

            InteractionPatch interactionPatchRequest;

            try
            {
                interactionPatchRequest = await _httpRequestMessageHelper.GetResourceFromRequest <Models.InteractionPatch>(req);
            }
            catch (JsonException ex)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (interactionPatchRequest == null)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(req));
            }

            interactionPatchRequest.LastModifiedTouchpointId = touchpointId;

            var errors = _validate.ValidateResource(interactionPatchRequest);

            if (errors != null && errors.Any())
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(errors));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var isCustomerReadOnly = await _resourceHelper.IsCustomerReadOnly(customerGuid);

            if (isCustomerReadOnly)
            {
                return(_httpResponseMessageHelper.Forbidden(customerGuid));
            }

            var interaction = await _interactionPatchService.GetInteractionForCustomerAsync(customerGuid, interactionGuid);

            if (interaction == null)
            {
                return(_httpResponseMessageHelper.NoContent(interactionGuid));
            }

            var updatedInteraction = await _interactionPatchService.UpdateAsync(interaction, interactionPatchRequest);

            if (updatedInteraction != null)
            {
                await _interactionPatchService.SendToServiceBusQueueAsync(updatedInteraction, customerGuid, ApimURL);
            }

            return(updatedInteraction == null?
                   _httpResponseMessageHelper.BadRequest(interactionGuid) :
                       _httpResponseMessageHelper.Ok(_jsonHelper.SerializeObjectAndRenameIdProperty(updatedInteraction, "id", "InteractionId")));
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Customers/{customerId}/Interactions/{interactionId}/Transfers/")] HttpRequest req, ILogger log, string customerId, string interactionId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header.");
                return(_httpResponseMessageHelper.BadRequest());
            }

            var ApimURL = _httpRequestMessageHelper.GetDssApimUrl(req);

            if (string.IsNullOrEmpty(ApimURL))
            {
                log.LogInformation("Unable to locate 'apimurl' in request header");
                return(_httpResponseMessageHelper.BadRequest());
            }

            log.LogInformation("Post Transfer C# HTTP trigger function processed a request. By Touchpoint. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(customerGuid));
            }

            if (!Guid.TryParse(interactionId, out var interactionGuid))
            {
                return(_httpResponseMessageHelper.BadRequest(interactionGuid));
            }

            Models.Transfer transferRequest;

            try
            {
                transferRequest = await _httpRequestMessageHelper.GetResourceFromRequest <Models.Transfer>(req);
            }
            catch (JsonException ex)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (transferRequest == null)
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(req));
            }

            transferRequest.SetIds(customerGuid, interactionGuid, touchpointId);

            var errors = _validate.ValidateResource(transferRequest, true);

            if (errors != null && errors.Any())
            {
                return(_httpResponseMessageHelper.UnprocessableEntity(errors));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_httpResponseMessageHelper.NoContent(customerGuid));
            }

            var isCustomerReadOnly = await _resourceHelper.IsCustomerReadOnly(customerGuid);

            if (isCustomerReadOnly)
            {
                return(_httpResponseMessageHelper.Forbidden(customerGuid));
            }

            var doesInteractionExist = _resourceHelper.DoesInteractionResourceExistAndBelongToCustomer(interactionGuid, customerGuid);

            if (!doesInteractionExist)
            {
                return(_httpResponseMessageHelper.NoContent(interactionGuid));
            }

            var transfer = await _transferPostService.CreateAsync(transferRequest);

            if (transfer != null)
            {
                await _transferPostService.SendToServiceBusQueueAsync(transfer, ApimURL);
            }

            return(transfer == null?
                   _httpResponseMessageHelper.BadRequest(customerGuid) :
                       _httpResponseMessageHelper.Created(_jsonHelper.SerializeObjectAndRenameIdProperty(transfer, "id", "TransferId")));
        }
Example #21
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "paths/{path}/regions")]
            HttpRequest req,
            ILogger log,
            string path,
            [Inject] ILoggerHelper loggerHelper,
            [Inject] IHttpRequestHelper httpRequestHelper,
            [Inject] IHttpResponseMessageHelper httpResponseMessageHelper,
            [Inject] IJsonHelper jsonHelper,
            [Inject] IRegionService regionService
            )
        {
            loggerHelper.LogMethodEnter(log);

            // validate the parameters are present
            var dssCorrelationId = httpRequestHelper.GetDssCorrelationId(req);

            if (string.IsNullOrEmpty(dssCorrelationId))
            {
                log.LogInformation($"Unable to locate '{nameof(dssCorrelationId)}' in request header");
            }

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

            if (string.IsNullOrEmpty(path))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing value in request for '{nameof(path)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            var pathRegex = new Regex(@"^[A-Za-z0-9.,-_]*$");

            if (path.Length > 100 || !pathRegex.IsMatch(path))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Invalid value in request for '{nameof(path)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            Models.Region regionRequest;

            try
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, "Attempt to get resource from body of the request");
                regionRequest = await httpRequestHelper.GetResourceFromRequest <Models.Region>(req);

                if (regionRequest == null)
                {
                    loggerHelper.LogInformationMessage(log, correlationGuid, "Missing body in req");
                    return(httpResponseMessageHelper.UnprocessableEntity());
                }
            }
            catch (JsonException ex)
            {
                loggerHelper.LogError(log, correlationGuid, "Unable to retrieve body from req", ex);
                return(httpResponseMessageHelper.UnprocessableEntity(ex));
            }

            if (path != regionRequest.Path)
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Request value for '{nameof(regionRequest.Path)}' does not match resource path value");
                return(httpResponseMessageHelper.BadRequest());
            }

            if (string.IsNullOrEmpty(regionRequest.RegionEndpoint))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing value in request for '{nameof(regionRequest.RegionEndpoint)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            const string PlaceMarkerStub = "{0}";
            string       regionEndpoint  = regionRequest.RegionEndpoint;

            if (regionEndpoint.Contains(PlaceMarkerStub))
            {
                // this is allowable, so replace with a valid string to permit the Uri.IsWellFormedUriString to check the resulting string
                regionEndpoint = regionEndpoint.Replace(PlaceMarkerStub, "valid");
            }

            if (!Uri.IsWellFormedUriString(regionEndpoint, UriKind.Absolute))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Request value for '{nameof(regionRequest.RegionEndpoint)}' is not a valid absolute Uri");
                return(httpResponseMessageHelper.BadRequest());
            }

            if (regionRequest.PageRegion == PageRegions.None || !Enum.IsDefined(typeof(PageRegions), regionRequest.PageRegion))
            {
                loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing/invalid value in request for '{nameof(regionRequest.PageRegion)}'");
                return(httpResponseMessageHelper.BadRequest());
            }

            if (!string.IsNullOrEmpty(regionRequest.OfflineHtml))
            {
                var htmlDoc = new HtmlDocument();

                htmlDoc.LoadHtml(regionRequest.OfflineHtml);

                if (htmlDoc.ParseErrors.Any())
                {
                    loggerHelper.LogInformationMessage(log, correlationGuid, $"Request value for '{nameof(regionRequest.OfflineHtml)}' contains malformed HTML");
                    return(httpResponseMessageHelper.BadRequest());
                }
            }

            loggerHelper.LogInformationMessage(log, correlationGuid, string.Format("Attempting to create region {0}", regionRequest.DocumentId));
            var createdRegion = await regionService.CreateAsync(regionRequest);

            loggerHelper.LogMethodExit(log);

            return(createdRegion != null
                ? httpResponseMessageHelper.Ok(jsonHelper.SerializeObjectAndRenameIdProperty(createdRegion, "id", nameof(Models.Region.DocumentId)))
                : httpResponseMessageHelper.NoContent());
        }
Example #22
0
        public async Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "customers/{customerId}/ContactDetails/")] HttpRequest req, ILogger log,
                                                         string customerId)
        {
            var touchpointId = _httpRequestMessageHelper.GetDssTouchpointId(req);

            if (string.IsNullOrEmpty(touchpointId))
            {
                log.LogInformation("Unable to locate 'TouchpointId' in request header.");
                return(_responseHelper.BadRequest());
            }

            var ApimURL = _httpRequestMessageHelper.GetDssApimUrl(req);

            if (string.IsNullOrEmpty(ApimURL))
            {
                log.LogInformation("Unable to locate 'apimurl' in request header");
                return(_responseHelper.BadRequest());
            }

            log.LogInformation("C# HTTP trigger function Post Contact processed a request. " + touchpointId);

            if (!Guid.TryParse(customerId, out var customerGuid))
            {
                return(_responseHelper.BadRequest(customerGuid));
            }

            Models.ContactDetails contactdetailsRequest;
            try
            {
                contactdetailsRequest = await _httpRequestMessageHelper.GetResourceFromRequest <Contact.Models.ContactDetails>(req);
            }
            catch (JsonException ex)
            {
                return(_responseHelper.UnprocessableEntity(ex));
            }

            if (contactdetailsRequest == null)
            {
                return(_responseHelper.UnprocessableEntity(req));
            }

            contactdetailsRequest.SetIds(customerGuid, touchpointId);

            var errors = _validate.ValidateResource(contactdetailsRequest, null, true);

            if (errors != null && errors.Any())
            {
                return(_responseHelper.UnprocessableEntity(errors));
            }

            var doesCustomerExist = await _resourceHelper.DoesCustomerExist(customerGuid);

            if (!doesCustomerExist)
            {
                return(_responseHelper.NoContent(customerGuid));
            }

            var isCustomerReadOnly = await _resourceHelper.IsCustomerReadOnly(customerGuid);

            if (isCustomerReadOnly)
            {
                return(_responseHelper.Forbidden(customerGuid));
            }

            var doesContactDetailsExist = _contactdetailsPostService.DoesContactDetailsExistForCustomer(customerGuid);

            if (doesContactDetailsExist)
            {
                return(_responseHelper.Conflict());
            }

            if (!string.IsNullOrEmpty(contactdetailsRequest.EmailAddress))
            {
                var contacts = await _provider.GetContactsByEmail(contactdetailsRequest.EmailAddress);

                if (contacts != null)
                {
                    foreach (var contact in contacts)
                    {
                        var isReadOnly = await _provider.DoesCustomerHaveATerminationDate(contact.CustomerId.GetValueOrDefault());

                        if (!isReadOnly)
                        {
                            //if a customer that has the same email address is not readonly (has date of termination)
                            //then email address on the request cannot be used.
                            return(_responseHelper.Conflict());
                        }
                    }
                }
            }

            var contactDetails = await _contactdetailsPostService.CreateAsync(contactdetailsRequest);

            if (contactDetails != null)
            {
                await _contactdetailsPostService.SendToServiceBusQueueAsync(contactDetails, ApimURL);
            }

            return(contactDetails == null
                ? _responseHelper.BadRequest(customerGuid)
                : _responseHelper.Created(JsonHelper.SerializeObject(contactDetails)));
        }
        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
                });
            }
        }
Example #24
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
                });
            }
        }