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());
            }
        }
        public void HttpResponseMessageHelperTests_ReturnsStatusCodeUnprocessableEntity_WhenHttpResponseMessageUnprocessableEntityIsCalled()
        {
            _httpResponseMessageHelper.UnprocessableEntity().Returns(x => new HttpResponseMessage((HttpStatusCode)422));

            var response = _httpResponseMessageHelper.UnprocessableEntity();

            Assert.IsInstanceOf <HttpResponseMessage>(response);
            Assert.AreEqual(422, (int)response.StatusCode);
        }
        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, "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)));
        }
예제 #6
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, "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")));
        }
        public async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "URLEndpoint")] HttpRequest req,
                                                    ILogger log)
        {
            string noti;
            string bearer = string.Empty;

            Models.Notification notification;

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

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

            string authHeader = string.Empty;

            if (req.Headers.TryGetValue("Authorization", out StringValues authToken))
            {
                authHeader = authToken.First();
            }
            else
            {
                log.LogInformation("Authorization header error !");
            }

            if (notification.ResourceURL != null)
            {
                if (notification.ResourceURL.ToString().Contains("collections"))
                {
                    var lastIndexOf = notification.ResourceURL.ToString().LastIndexOf("/", StringComparison.Ordinal);
                    if (lastIndexOf != -1)
                    {
                        var collectionId = notification.ResourceURL.ToString().Substring(lastIndexOf + 1);

                        if (Guid.TryParse(collectionId, out var collectionGuid))
                        {
                            notification.CollectionId = collectionGuid;
                        }
                    }
                }
            }

            noti = "Customer Id : " + notification.CustomerId + Environment.NewLine +
                   "URL : " + notification.ResourceURL + Environment.NewLine +
                   "LastModifiedDate : " + notification.LastModifiedDate + Environment.NewLine +
                   "Touchpoint Id : " + notification.TouchpointId + Environment.NewLine +
                   "Collection Id : " + notification.CollectionId + Environment.NewLine +
                   "Bearer : " + authHeader;

            log.LogInformation(noti);

            await _saveNotification.SaveNotificationToDBAsync(notification);

            return(_httpResponseMessageHelper.Ok(noti));
        }
예제 #9
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());
        }
예제 #10
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 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)));
        }
예제 #12
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)));
        }