public string Get(string transactionId)
        {
            _Logger.LogInformation("[UIController] - GET - api/ui - [STARTS]");

            JObject uiDataResponseJson = null;
            string  uiResponse         = string.Empty;

            var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

            // makes the Get Origin call from the Partner API
            var originResponse = partnerAPIWrapper.GetOrigin(transactionId);

            if (originResponse != null)
            {
                _Logger.LogInformation("[UIController] - GET - api/ui - OriginResponse is not null");

                uiDataResponseJson = new JObject();
                uiDataResponseJson.Add("originResponse", originResponse);

                // Sanitizing the response payload here for any html or script tags and escaping them.
                var settings = new JsonSerializerSettings()
                {
                    StringEscapeHandling = StringEscapeHandling.EscapeHtml
                };

                uiResponse = JsonConvert.SerializeObject(uiDataResponseJson, settings);
            }

            _Logger.LogInformation("[UIController] - GET - api/ui - [END]");

            return(uiResponse);
        }
        public IActionResult GetAll(string transactionId)
        {
            try
            {
                _Logger.LogInformation("[MessageController] - GET - api/message - [STARTS]");
                var     partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                JObject result            = partnerAPIWrapper.GetAllMessages(transactionId);
                if (result != null)
                {
                    //build response
                    return(Ok(result));
                }
                else
                {
                    //build error response
                    return(NoContent());
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[MessageController] - GET - Error - " + ex.Message);
                _Logger.LogError("[MessageController] - GET - Stack Trace - " + ex.StackTrace);

                return(StatusCode(500));
            }
        }
        public IActionResult Post([FromBody] JObject data, string transactionId)
        {
            try
            {
                _Logger.LogInformation("[RequestController] - POST - api/request - [STARTS]");

                // checking to see if the incoming data is a Valid JSON and does not contain any XSS
                if (!data.IsValidJSON())
                {
                    _Logger.LogInformation("[RequestController] - POST - api/request - Incoming JSON is invalid");
                    _Logger.LogInformation("[RequestController] - POST - api/request - " + data.ToString());
                    return(BadRequest("The JSON payload is Invalid. Please provide a valid Input."));
                }

                // checking if the incoming data is null
                if (data != null)
                {
                    var requestObject = new JObject(data);

                    var settings = new JsonSerializerSettings()
                    {
                        StringEscapeHandling = StringEscapeHandling.EscapeHtml
                    };

                    // Sanitizing the Payload here for any html or script tags and escaping them
                    var requestPayload = JsonConvert.SerializeObject(requestObject, settings);

                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                    // This is the POST call to the Partner API (Create Request call) | // partner/v1/transactions/{{transactionId}}/request
                    partnerAPIWrapper.CreateRequest(requestObject.ToString(Formatting.None), transactionId);
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[RequestController] - POST - Error - " + ex.Message);
                _Logger.LogError("[RequestController] - POST - Stack Trace - " + ex.StackTrace);

                return(StatusCode(500));
            }

            _Logger.LogInformation("[RequestController] - POST - api/request - [ENDS]");
            return(Ok("{'success': true}"));
        }
Beispiel #4
0
        public string Get(string transactionId)
        {
            _Logger.LogInformation("[UIController] - GET - api/ui - [STARTS]");

            string uiResponse = string.Empty;

            var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

            // makes the Get Origin call from the Partner API
            var originResponse = partnerAPIWrapper.GetOrigin(transactionId);

            if (originResponse != null)
            {
                _Logger.LogInformation("[UIController] - GET - api/ui - OriginResponse is not null");

                dynamic uiDataResponseJson = new JObject();
                uiDataResponseJson.Add("originResponse", originResponse);

                if (uiDataResponseJson.originResponse.credentials != null)
                {
                    // reading the credentials object and stripping the password before sending it to the ui
                    var credentials = uiDataResponseJson.originResponse.credentials;

                    // better to have a universal password naming convention here
                    credentials["133003.Pwd"] = "********";
                    credentials["password"]   = "******";
                }

                // Sanitizing the response payload here for any html or script tags and escaping them.
                var settings = new JsonSerializerSettings()
                {
                    StringEscapeHandling = StringEscapeHandling.EscapeHtml
                };

                uiResponse = JsonConvert.SerializeObject(uiDataResponseJson, settings);

                //uiResponse = uiDataResponseJson.ToString(Formatting.None);
            }

            _Logger.LogInformation("[UIController] - GET - api/ui - [END]");

            return(uiResponse);
        }
        /// <summary>
        /// This method will submit partner acknowledgement to EPC
        /// </summary>
        /// <param name="response"></param>
        /// <param name="loanInformation"></param>
        public void SubmitAcknowledgementToEPC(JObject response, JToken loanInformation, string status = "")
        {
            dynamic responsePayload = new JObject();
            dynamic orders          = new JArray();
            var     transactionId   = _WebhookBody.meta != null ? _WebhookBody.meta.resourceId : string.Empty;

            if (response != null)
            {
                _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToEPC - Submitting Response to Partner API ");

                if (response.SelectToken("$.result") != null && loanInformation != null)
                {
                    if (string.Compare(_AppSettings.IntegrationType, "Appraisal", true) == 0)
                    {
                        orders = ProcessAppraisalResponse(response, loanInformation);
                    }
                    else if (string.Compare(_AppSettings.IntegrationType, "Verification", true) == 0)
                    {
                        orders = ProcessVerificationResponse(response, loanInformation);
                    }
                    else if (string.Compare(_AppSettings.IntegrationType, "DataDocs", true) == 0)
                    {
                        orders = ProcessDataDocsResponse(response, status);
                    }

                    responsePayload.orders = orders;

                    var responsePayloadString = Convert.ToString(responsePayload);

                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                    // This is the POST call to the Partner API (Create Response call) | partner/v1/transactions/{{transactionId}}/response
                    var isResponseCreated = partnerAPIWrapper.CreateResponse(responsePayloadString, transactionId);

                    if (isResponseCreated)
                    {
                        _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToEPC - isResponseCreated flag is true");
                        TransactionStatusCache.Instance.Add(transactionId, response);
                    }
                }
            }
        }
        public IActionResult Post([FromBody] JObject data, string transactionId)
        {
            try
            {
                _Logger.LogInformation("[MessageController] - POST - api/message - [STARTS]");

                // checking to see if the incoming data is a Valid JSON and does not contain any XSS
                if (!data.IsValidJSON())
                {
                    _Logger.LogInformation("[MessageController] - POST - api/message - Incoming JSON is invalid");
                    _Logger.LogInformation("[MessageController] - POST - api/message - " + data.ToString());
                    return(BadRequest("The JSON payload is Invalid. Please provide a valid Input."));
                }

                // checking if the incoming data is null
                if (data != null)
                {
                    var requestObject = new JObject(data);

                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                    var result = partnerAPIWrapper.PostMessage(transactionId, requestObject.ToString(Formatting.None));
                    if (result)
                    {
                        return(Ok());
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[MessageController] - POST - Error - " + ex.Message);
                _Logger.LogError("[MessageController] - POST - Stack Trace - " + ex.StackTrace);

                return(StatusCode(500));
            }

            _Logger.LogInformation("[MessageController] - POST - api/message - [ENDS]");
            return(StatusCode(400));
        }
        public void Post([FromBody] JObject data)
        {
            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - [STARTS]");

            // Checking if the request payload is null
            if (data != null)
            {
                _Logger.LogInformation("[" + _ClassName + "]  - POST - api/webhook -  Received Webhook Notification at ");

                var webhookSecret      = _AppSettings.WebhookSecret;
                var requestSignature   = Request.Headers["Elli-Signature"].ToString();
                var requestEnvironment = Request.Headers["Elli-Environment"].ToString();

                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Request Elli-Signature - " + requestSignature);
                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Request Elli-Environment - " + requestEnvironment);

                // generate the webhook token from the payload and secret using HMACSHA
                var webHookToken = WebHookHelper.GetWebhookNotificationToken(data.ToString(Formatting.None), webhookSecret);

                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Data - " + data.ToString(Formatting.Indented));
                _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Token - " + webHookToken);

                // Check if the generated WebHook token is similar to the request signature received in the header.
                if (WebHookHelper.IsValidWebhookToken(requestSignature, webHookToken))
                {
                    var webHookBody = new WebhookNotificationBody()
                    {
                        eventId   = data.GetValue <string>("eventId"),
                        eventTime = data.GetValue <DateTime>("eventTime"),
                        eventType = data.GetValue <string>("eventType"),
                        meta      = data.GetValue <Meta>("meta")
                    };

                    var transactionId = webHookBody.meta != null ? webHookBody.meta.resourceId : string.Empty;

                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Transaction ID - " + transactionId);

                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                    // executing the Get Request Partner API Call here
                    var requestData = partnerAPIWrapper.GetRequest(transactionId);

                    if (requestData != null)
                    {
                        _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Get Request Data is not null ");

                        var loanInformation = requestData;

                        // if the requestData is not null then the Partner will validate it against their business rules and if it is valid then they have to build their request here and submit it
                        // the response that they receive from their request will go back into the Partner API as a CreateResponse Partner API call

                        var validationInfo = MockResponseHelper.ValidateLoanData(requestData);

                        if (validationInfo != null && validationInfo["success"] != null)
                        {
                            var response = MockRequestHelper.SubmitToPartner(requestData, transactionId);

                            // This method will build the payload required for Creating Response in the Partner API
                            SubmitAcknowledgementToPartnerAPI(response, loanInformation, transactionId);
                        }
                        else
                        {
                            TransactionStatusCache.Instance.Add(transactionId, validationInfo);
                        }
                    }
                }
                else
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - WebHook Token is Invalid ");
                }
            }

            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - [ENDS]");
        }
        /// <summary>
        /// This method will build the payload required for Creating Response in the Partner API
        /// </summary>
        /// <param name="response"></param>
        /// <param name="loanInformation"></param>
        /// <param name="transactionId"></param>
        private void SubmitAcknowledgementToPartnerAPI(JObject response, JToken loanInformation, string transactionId)
        {
            _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - [STARTS]");

            try
            {
                if (response != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Submitting Resposne to Partner API ");

                    // assuming the response is of type JToken
                    if (response.SelectToken("$.result") != null && loanInformation != null)
                    {
                        var result          = response.SelectToken("$.result");
                        var productName     = loanInformation.SelectToken("$.product.options.productName");
                        var productId       = loanInformation.SelectToken("$.product.options.productId");
                        var existingOrderId = loanInformation.SelectToken("$.product.options.existingOrderId");

                        var random = new System.Random();

                        // setting the order id to existingOrderId if the payload has it otherwise setting it to a random number
                        var orderId = existingOrderId != null?existingOrderId.ToString() : random.Next(10000, 80000).ToString();

                        var orderInfo = new OrderInformation()
                        {
                            TransactionId = transactionId,
                            ProductName   = productName != null?productName.ToString() : string.Empty,
                                                ProductCode = productId != null?productId.ToString() : string.Empty,
                                                                  OrderId = existingOrderId != null?existingOrderId.ToString() : orderId.ToString(), // adding existing order id if it exists in the response object,
                                                                                OrderStatus     = response.SelectToken("$.status").ToString(),
                                                                                LoanInformation = loanInformation
                        };

                        // Adding Transaction Information in the local In Memory cache. This would be implemented by the partner in their own way to track transactions and their order statuses
                        TransactionInformationCache.Instance.Add(orderInfo);

                        // building payload for Partner API Create Response
                        dynamic responsePayload = new JObject();
                        dynamic orders          = new JArray();
                        dynamic order           = new JObject();

                        //var orderDate = DateTime.Now.ToUniversalTime();
                        var orderDate = DateTime.Now;

                        _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Order Date time is " + orderDate.ToString("o"));

                        order.id            = orderId.ToString();
                        order.orderDateTime = orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"); // result["orderDate"];
                        order.orderStatus   = response["status"];
                        order.orderMessage  = result["orderMessage"];
                        order.product       = productName;
                        order.documents     = new JArray();

                        orders.Add(order);

                        responsePayload.orders = orders;

                        var responsePayloadString = Convert.ToString(responsePayload);

                        var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                        // This is the POST call to the Partner API (Create Response call) | partner/v1/transactions/{{transactionId}}/response
                        var isResponseCreated = partnerAPIWrapper.CreateResponse(responsePayloadString, transactionId);

                        if (isResponseCreated)
                        {
                            TransactionStatusCache.Instance.Add(transactionId, response);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Exception - " + ex.Message);
                _Logger.LogError("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - StackTrace - " + ex.StackTrace);
            }

            _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - [ENDS]");
        }
        public IActionResult Post(string transactionId, string orderId)
        {
            JObject status = new JObject();

            try
            {
                _Logger.LogInformation("[StatusController] - POST - api/status - [STARTS]");

                // partner will check their systems/repository to check the status of the current order and return the documents if it is completed.
                var mockResponseHelper  = new MockResponseHelper(_AppSettings);
                var checkStatusResponse = mockResponseHelper.GetResponseForCheckStatus(transactionId, orderId);

                if (checkStatusResponse != null)
                {
                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                    var responseString    = Convert.ToString(checkStatusResponse);

                    // This is the POST call to the Partner API (Create Response call) | partner/v1/transactions/{{transactionId}}/response
                    var isResponseCreated = partnerAPIWrapper.CreateResponse(responseString, transactionId);

                    if (isResponseCreated)
                    {
                        _Logger.LogInformation("[StatusController] - POST - api/status - Response was created.");

                        // building success response for UI
                        var result    = new JObject();
                        var orderDate = DateTime.Now;

                        status.Add("status", checkStatusResponse["status"]);
                        result.Add("trackingId", orderId);
                        result.Add("orderDate", orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"));
                        result.Add("orderMessage", "Order has been completed successfully.");

                        status.Add("result", result);

                        // updating the transaction status in the memory cache so that the status check polling method on the UI gets the updated status of the transaction.
                        TransactionStatusCache.Instance.Add(transactionId, status);
                    }
                    else
                    {
                        _Logger.LogInformation("[StatusController] - POST - api/status - Response was not Created. isResponseCreate flag is false.");

                        // return Internal Server Error
                        return(StatusCode(500));
                    }
                }
                else
                {
                    _Logger.LogInformation("[StatusController] - POST - api/status - checkStatusResponse is null.");

                    // return Internal Server Error
                    return(StatusCode(500));
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[StatusController] - POST - Error - " + ex.Message);
                return(StatusCode(500));
            }

            _Logger.LogInformation("[StatusController] - POST - api/status - [ENDS]");
            return(Ok(status));
        }
        /// <summary>
        /// This method will be called when the order is fulfilled on the partners end.
        /// it will do a POST Response to Partner API
        /// </summary>
        /// <param name="response"></param>
        /// <param name="transactionId"></param>
        private void SubmitResponseToPartnerAPI(JObject response, string transactionId)
        {
            try
            {
                _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - Inside Method - ");

                // Getting the relevant Loan Information for the given Transaction
                var transactionLoanInformation = TransactionInformationCache.Instance.GetValue(transactionId);

                if (response != null)
                {
                    _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - response is not null - ");

                    if (transactionLoanInformation != null && response.SelectToken("status").ToString() == "Completed" && response.SelectToken("$.result") != null)
                    {
                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - TransactionLoanInformation is not null - ");

                        // build payload for Partner API Create Response
                        dynamic responsePayload = new JObject();

                        dynamic loanObject = new JObject();

                        loanObject.VaLoanData         = MockResponseHelper.GetVALoanData();
                        loanObject.UnderwriterSummary = MockResponseHelper.GetUnderWritterSummaryData();
                        loanObject.Uldd            = MockResponseHelper.GetUIDData();
                        loanObject.Tsum            = MockResponseHelper.GetTSumData();
                        loanObject.Property        = MockResponseHelper.GetPropertyData();
                        loanObject.HudLoanData     = MockResponseHelper.GetHUDLoanData();
                        loanObject.Hmda            = MockResponseHelper.GetHMDAData();
                        loanObject.Fees            = MockResponseHelper.GetLoanFeesData();
                        loanObject.Contacts        = MockResponseHelper.GetLoanContactsData();
                        loanObject.CommitmentTerms = MockResponseHelper.GetCommitmentTermsData();
                        loanObject.ClosingDocument = MockResponseHelper.GetClosingDocumentData();
                        loanObject.PropertyAppraisedValueAmount = 566000;

                        dynamic orders = new JArray();
                        dynamic order  = new JObject();

                        var result = response.SelectToken("$.result");

                        if (result != null)
                        {
                            order.id            = result["trackingId"];
                            order.orderDateTime = result["orderDate"];
                            order.orderStatus   = response["status"];
                            order.orderMessage  = result["orderMessage"];
                        }

                        order.product   = transactionLoanInformation.ProductName;
                        order.documents = GetDocumentsFromResponse(response, transactionId);

                        orders.Add(order);

                        responsePayload.LoanData = loanObject;
                        responsePayload.orders   = orders;

                        var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                        partnerAPIWrapper.CreateResponse(responsePayload.ToString(Formatting.None), transactionId);

                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - before adding response to TransactionStatus cache - ");
                        TransactionStatusCache.Instance.Add(transactionId, response);
                        _Logger.LogInformation("[ResponseController] - SubmitResponseToPartnerAPI - After adding response to TransactionStatus cache - ");
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[ResponseController] - SubmitResponseToPartnerAPI - Exception - " + ex.Message);
            }
        }
        /// <summary>
        /// This method will upload files to the media server and return a list of attachments
        /// </summary>
        /// <param name="mediaServerURL"></param>
        /// <param name="fileInfoList"></param>
        /// <returns></returns>
        private JArray UploadFilesToMediaServer(string mediaServerURL, IList <FileInfo> fileInfoList)
        {
            dynamic attachmentsList = new JArray();

            try
            {
                if (!string.IsNullOrEmpty(mediaServerURL) && fileInfoList != null)
                {
                    var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                    var response          = partnerAPIWrapper.UploadFilesToMediaServer(mediaServerURL, fileInfoList);

                    if (!string.IsNullOrEmpty(response))
                    {
                        _Logger.LogInformation("[ResponseController] - UploadFilesToMediaServer - File Upload was successful ");

                        var attachmentsResponse = JObject.Parse(response);

                        if (attachmentsResponse != null && attachmentsResponse.SelectToken("Files") != null)
                        {
                            var files = attachmentsResponse.SelectToken("Files");

                            dynamic attachments = new JArray();

                            foreach (var item in files.Children())
                            {
                                foreach (var file in fileInfoList)
                                {
                                    var fileName = string.Format(@"{0}.{1}", file.Name, file.FileExtension);

                                    if (item["FileName"].ToString().ToLower().Contains(fileName.ToLower()))
                                    {
                                        dynamic attachment = new JObject();

                                        attachment.id       = item["FileId"];
                                        attachment.name     = fileName;
                                        attachment.mimeType = file.ContentType;
                                        attachments.Add(attachment);

                                        // delete the temporary file from local system
                                        if (System.IO.Directory.Exists(file.FilePath))
                                        {
                                            System.IO.Directory.Delete(file.FilePath, true);
                                        }

                                        _Logger.LogInformation("[ResponseController] - UploadFilesToMediaServer - AttachmentID - " + item["FileId"].ToString());

                                        break;
                                    }
                                }
                            }

                            attachmentsList = attachments;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[ResponseController] - UploadFilesToMediaServer - Exception - " + ex.Message);
            }

            return(attachmentsList);
        }
        /// <summary>
        /// Returns the documents received in the response JSON
        /// </summary>
        /// <param name="orderResponse"></param>
        /// <param name="transactionId"></param>
        /// <returns></returns>
        private JArray GetDocumentsFromResponse(JObject orderResponse, string transactionId)
        {
            dynamic documentsResponse = new JArray();

            try
            {
                if (orderResponse != null)
                {
                    _Logger.LogInformation("[ResponseController] - GetDocumentsFromResponse - Order response is not null ");

                    var embeddedFiles = orderResponse.SelectToken("$.result.orderResponse.REPORT.EMBEDDED_FILES");

                    if (embeddedFiles != null && embeddedFiles.HasValues)
                    {
                        _Logger.LogInformation("[ResponseController] - GetDocumentsFromResponse - Order response has attachments and EmbeddedFiles is not null ");

                        var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);
                        var uploadURL         = partnerAPIWrapper.GetDropFilesURL(transactionId);

                        _Logger.LogInformation("[ResponseController] - GetDocumentsFromResponse - MediaServer URL is " + uploadURL);

                        if (!string.IsNullOrEmpty(uploadURL))
                        {
                            var fileInfoList = new List <FileInfo>();

                            var directoryName = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");

                            // Populating file info list for uploading to the Media server
                            foreach (var item in embeddedFiles.Children())
                            {
                                var file = item["DOCUMENT"];

                                var fileInfo = new FileInfo
                                {
                                    Name          = item["_Name"].ToString(),
                                    FileName      = item["_Name"].ToString(),
                                    FileExtension = item["_Type"].ToString(),
                                    ContentType   = item["MIMEType"].ToString(),
                                    Content       = Convert.FromBase64String(file.ToString()),
                                    FileDirectory = directoryName,
                                    FilePath      = CreateAndGetFilePath(directoryName, file.ToString(), item["_Name"].ToString(), item["_Type"].ToString())
                                };

                                fileInfoList.Add(fileInfo);
                            }

                            var mediaServerResponse = UploadFilesToMediaServer(uploadURL, fileInfoList);

                            if (mediaServerResponse != null)
                            {
                                _Logger.LogInformation("[ResponseController] - GetDocumentsFromResponse - MediaServer response is not null ");

                                dynamic document = new JObject();
                                document.name        = "Appraisal Report";
                                document.attachments = mediaServerResponse;
                                documentsResponse.Add(document);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[ResponseController] - GetDocumentsFromResponse - Exception - " + ex.Message);
            }

            return(documentsResponse);
        }
Beispiel #13
0
        /// <summary>
        /// This method will process the webhook request
        /// </summary>
        public void ProcessWebhookRequest()
        {
            var transactionId     = this._WebhookBody.meta != null ? _WebhookBody.meta.resourceId : string.Empty;
            var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

            _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Transaction ID - " + transactionId);

            // This is for the Transaction messaging flow. if the eventType is NewMessage then the Lender has sent a message to the Partner and the partner has to retreive it
            if (_WebhookBody.eventType == "NewMessage")
            {
                //Dump message body into cache.

                var resourceRefURL = _WebhookBody.meta.resourceRef;
                var messageId      = resourceRefURL.Substring(resourceRefURL.LastIndexOf('/') + 1, resourceRefURL.Length - resourceRefURL.LastIndexOf('/') - 1);

                var messageBody = partnerAPIWrapper.GetMessage(transactionId, messageId);
                if (messageBody != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Message is not null ");
                    MessageCache.Instance.Add(transactionId, messageBody.ToString());
                }
            }
            else if (_WebhookBody.eventType == "CreateRequest")
            {
                // executing the Get Request Partner API Call here
                var requestData = partnerAPIWrapper.GetRequest(transactionId);

                if (requestData != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - POST - api/webhook - Get Request Data is not null ");

                    var loanInformation = requestData;

                    // if the requestData is not null then the Partner will validate it against their business rules and if it is valid then they have to build their request here and submit it
                    // the response that they receive from their request will go back into the Partner API as a CreateResponse Partner API call

                    var mockResponseHelper = new MockResponseHelper(_AppSettings);
                    var validationInfo     = mockResponseHelper.ValidateLoanData(requestData);

                    if (validationInfo != null && validationInfo["success"] != null)
                    {
                        // This will get the type of Integration (e.g. Appraisal, Flood, Verification etc.)
                        var integrationCategory = _AppSettings.IntegrationType == null ? "Appraisal" : _AppSettings.IntegrationType;

                        var response = _MockRequestHelper.SubmitToPartner(requestData, transactionId);

                        // This method will build and submit the payload required for Creating the response in EPC
                        var responseParser = new ResponseProcessor(_WebhookBody, _Logger, _AppSettings);

                        // For Data & Docs flow, validating the credentials.
                        if (string.Compare(_AppSettings.IntegrationType, "DataDocs", true) == 0)
                        {
                            // use password manager and do validation.
                            if (requestData.SelectToken("$.credentials") != null)
                            {
                                var userName = requestData.GetValueByPath <string>("$.credentials.userName");
                                var password = requestData.GetValueByPath <string>("$.credentials.password");

                                // partner will validate the credentials returned from GetRequest with their system and submit the acknowledgement. here we're validating against a mock username and password.
                                if (userName == "datadocs" && password == "#######")
                                {
                                    responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Delivered");
                                }
                                else
                                {
                                    responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Rejected"); // if the credentials are invalid or null then send Rejected status
                                }
                            }
                            else
                            {
                                responseParser.SubmitAcknowledgementToEPC(response, loanInformation, "Rejected"); // if the credentials are invalid or null then send Rejected status
                            }
                        }
                        else
                        {
                            responseParser.SubmitAcknowledgementToEPC(response, loanInformation); // This is for the other categories.
                        }
                    }
                    else
                    {
                        TransactionStatusCache.Instance.Add(transactionId, validationInfo);
                    }
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// This method will build the payload required for Creating Response in the Partner API
        /// </summary>
        /// <param name="response"></param>
        /// <param name="loanInformation"></param>
        /// <param name="transactionId"></param>
        private void SubmitAcknowledgementToPartnerAPI(JObject response, JToken loanInformation, string transactionId)
        {
            _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - [STARTS]");

            try
            {
                if (response != null)
                {
                    _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Submitting Response to Partner API ");

                    if (response.SelectToken("$.result") != null && loanInformation != null)
                    {
                        JToken result          = response.SelectToken("$.result");;
                        JToken productName     = null;
                        JToken productId       = null;
                        JToken existingOrderId = null;
                        string orderId         = "";
                        var    random          = new System.Random();

                        // building payload for Partner API Create Response
                        dynamic responsePayload = new JObject();
                        dynamic orders          = new JArray();
                        dynamic order           = null;

                        //var orderDate = DateTime.Now.ToUniversalTime();
                        var orderDate = DateTime.Now;

                        // assuming the response is of type JToken
                        if (string.Compare(_AppSettings.IntegrationType, "Verification", true) == 0)
                        {
                            JToken tokenoptions = loanInformation.SelectToken("$.product.options");

                            if (tokenoptions != null)
                            {
                                foreach (JProperty prop in tokenoptions)
                                {
                                    string sProductName = "";
                                    if (!string.IsNullOrEmpty(prop.Name) && _MockRequestHelper.IsValidProduct(prop.Name))
                                    {
                                        sProductName = _MockRequestHelper.GetProductDescription(prop.Name);
                                    }

                                    if (!string.IsNullOrEmpty(sProductName))
                                    {
                                        _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - ProductName is " + sProductName);

                                        orderId = random.Next(10000, 80000).ToString();

                                        OrderInformation orderInfo = new OrderInformation()
                                        {
                                            TransactionId   = transactionId,
                                            ProductName     = sProductName,
                                            ProductCode     = prop.Name.ToString(),
                                            OrderId         = orderId.ToString(),
                                            OrderStatus     = response.SelectToken("$.status").ToString(),
                                            LoanInformation = loanInformation
                                        };

                                        TransactionInformationCache.Instance.Add(orderInfo, true);

                                        order               = new JObject();
                                        order.id            = orderId.ToString();
                                        order.orderDateTime = orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"); // result["orderDate"];
                                        order.orderStatus   = response["status"];
                                        order.orderMessage  = result["orderMessage"];
                                        order.product       = sProductName;
                                        order.documents     = new JArray();

                                        orders.Add(order);
                                    }
                                }
                            }
                        }
                        else if (string.Compare(_AppSettings.IntegrationType, "DataDocs", true) == 0)
                        {
                            orderId = random.Next(10000, 80000).ToString();

                            // responsePayload = new JObject();
                            //responsePayload.orders = new JArray();
                            dynamic orderResponse = new JObject();
                            orderResponse.id            = orderId.ToString();
                            orderResponse.orderDateTime = orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"); // result["orderDate"];
                            orderResponse.orderStatus   = "Delivered";
                            orderResponse.message       = result["orderMessage"];
                            orders.Add(orderResponse);
                        }
                        else
                        {
                            productName     = loanInformation.SelectToken("$.product.options.productName");
                            productId       = loanInformation.SelectToken("$.product.options.productId");
                            existingOrderId = loanInformation.SelectToken("$.product.options.existingOrderId");

                            // setting the order id to existingOrderId if the payload has it otherwise setting it to a random number
                            orderId = existingOrderId != null?existingOrderId.ToString() : random.Next(10000, 80000).ToString();

                            var orderInfo = new OrderInformation()
                            {
                                TransactionId = transactionId,
                                ProductName   = productName != null?productName.ToString() : string.Empty,
                                                    ProductCode = productId != null?productId.ToString() : string.Empty,
                                                                      OrderId = existingOrderId != null?existingOrderId.ToString() : orderId.ToString(), // adding existing order id if it exists in the response object,
                                                                                    OrderStatus     = response.SelectToken("$.status").ToString(),
                                                                                    LoanInformation = loanInformation
                            };

                            // Adding Transaction Information in the local In Memory cache. This would be implemented by the partner in their own way to track transactions and their order statuses
                            TransactionInformationCache.Instance.Add(orderInfo);

                            order               = new JObject();
                            order.id            = orderId.ToString();
                            order.orderDateTime = orderDate.ToString("yyyy-MM-ddTHH:mm-ss:ff"); // result["orderDate"];
                            order.orderStatus   = response["status"];
                            order.orderMessage  = result["orderMessage"];
                            order.product       = productName;
                            order.documents     = new JArray();

                            orders.Add(order);
                        }

                        _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Order Date time is " + orderDate.ToString("o"));

                        responsePayload.orders = orders;

                        var responsePayloadString = Convert.ToString(responsePayload);

                        var partnerAPIWrapper = new PartnerAPIWrapper(this._AppSettings);

                        // This is the POST call to the Partner API (Create Response call) | partner/v1/transactions/{{transactionId}}/response
                        var isResponseCreated = partnerAPIWrapper.CreateResponse(responsePayloadString, transactionId);

                        if (isResponseCreated)
                        {
                            _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - isResponseCreated flag is true");
                            TransactionStatusCache.Instance.Add(transactionId, response);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _Logger.LogError("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - Exception - " + ex.Message);
                _Logger.LogError("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - StackTrace - " + ex.StackTrace);
            }

            _Logger.LogInformation("[" + _ClassName + "] - SubmitAcknowledgementToPartnerAPI - [ENDS]");
        }