diff --git a/Source/DealerSelection.Api.Models/AuthValidateModel.cs b/Source/DealerSelection.Api.Models/AuthValidateModel.cs index f1c85fc..48b44cc 100644 --- a/Source/DealerSelection.Api.Models/AuthValidateModel.cs +++ b/Source/DealerSelection.Api.Models/AuthValidateModel.cs @@ -2,9 +2,8 @@ { public class AuthValidateModel { - public string ClientId { get; set; } - public string SecretId { get; set; } - public int BuId { get; set; } + public string client_id { get; set; } + public string client_secret { get; set; } } public class TokenModel diff --git a/Source/DealerSelection.Api.Models/CustomerDealerInfoRequest.cs b/Source/DealerSelection.Api.Models/CustomerDealerInfoRequest.cs index 36719d6..ca467d2 100644 --- a/Source/DealerSelection.Api.Models/CustomerDealerInfoRequest.cs +++ b/Source/DealerSelection.Api.Models/CustomerDealerInfoRequest.cs @@ -1,28 +1,30 @@ -namespace DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; + +namespace DealerSelection.Api.Models; public class CustomerDealerInfoRequest { - public CustomerDealerInfoRequest(int buId, int recordId, int mobileNumber, string modelCode, string modelName, - string modelVariant, string dealerName, string dealerCode, string pinCode, string latitude, string longitude, - DealerSelectionJobStatus dealerSelectionJobStatus) + public CustomerDealerInfoRequest(string buCode,string buSubType, + string mobileNumber, string dealerName, + string dealerCode, string pinCode, string latitude, string longitude + ) { - BuId = buId; - RecordId = recordId; - MobileNumber = mobileNumber; - ModelCode = modelCode; - ModelName = modelName; - ModelVariant = modelVariant; + + BuCode = buCode; + BuSubType= buSubType; + MobileNumber = mobileNumber; DealerName = dealerName; DealerCode = dealerCode; PinCode = pinCode; Latitude = latitude; Longitude = longitude; - DealerSelectionJobStatus = dealerSelectionJobStatus; } public int BuId { get; } + public string BuCode { get; } + public string BuSubType { get; set; } public int RecordId { get; } - public int MobileNumber { get; } + public string MobileNumber { get; } public string ModelCode { get; } public string ModelName { get; } public string ModelVariant { get; } @@ -40,7 +42,7 @@ public class CustomerDealerInfoRequest public string RequestDetail() { - return $"BuId: {BuId}, RecordId: {RecordId}, MobileNumber: {MobileNumber}, ModelCode: {ModelCode}, " + + return $"BuId: {BuId},BuName: {BuCode}, RecordId: {RecordId}, MobileNumber: {MobileNumber}, ModelCode: {ModelCode}, " + $"ModelName:{ModelName}, ModelVariant:{ModelVariant}, DealerName: {DealerName}, DealerCode: {DealerCode}, " + $"PinCode: {PinCode}, Latitude: {Latitude}, Longitude: {Longitude}, DealerSelectionJobStatus: {DealerSelectionJobStatus}"; } diff --git a/Source/DealerSelection.Api.Models/DealerSelectionJobStatus.cs b/Source/DealerSelection.Api.Models/DealerSelectionJobStatus.cs deleted file mode 100644 index 2f1550f..0000000 --- a/Source/DealerSelection.Api.Models/DealerSelectionJobStatus.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DealerSelection.Api.Models; - -public enum DealerSelectionJobStatus -{ - OldData = -1, - ReadyForJob = 0, - Picked = 1, - SentToBot = 2, - Complete = 3, -} diff --git a/Source/DealerSelection.Api.Models/Enum/CCAvenueTransactionStatus.cs b/Source/DealerSelection.Api.Models/Enum/CCAvenueTransactionStatus.cs new file mode 100644 index 0000000..0bdaa17 --- /dev/null +++ b/Source/DealerSelection.Api.Models/Enum/CCAvenueTransactionStatus.cs @@ -0,0 +1,7 @@ +namespace DealerSelection.Api.Models.Enum; + +public enum CCAvenueTransactionStatus +{ + Refunded = 0, + RefundFailed = 1 +} diff --git a/Source/DealerSelection.Api.Models/Enum/DealerSelectedMode.cs b/Source/DealerSelection.Api.Models/Enum/DealerSelectedMode.cs new file mode 100644 index 0000000..8d751f1 --- /dev/null +++ b/Source/DealerSelection.Api.Models/Enum/DealerSelectedMode.cs @@ -0,0 +1,8 @@ +namespace DealerSelection.Api.Models.Enum; + +public enum DealerSelectedMode +{ + Auto = 0, //Single Dealer + Dummy = 1, //No Response From Bot + Bot=2 //Selected through Bot +} diff --git a/Source/DealerSelection.Api.Models/Enum/DealerSelectionJobStatus.cs b/Source/DealerSelection.Api.Models/Enum/DealerSelectionJobStatus.cs new file mode 100644 index 0000000..5ae6204 --- /dev/null +++ b/Source/DealerSelection.Api.Models/Enum/DealerSelectionJobStatus.cs @@ -0,0 +1,10 @@ +namespace DealerSelection.Api.Models.Enum; + +public enum DealerSelectionJobStatus +{ + OldData = -1, + ReadyForJob = 0, //Booking Done and ready to pick + Picked = 1, // Picked by Job + SentToBot = 2, // Web Engage Event called to Inititate Bot + Complete = 3, //Dealer Assigned through Single/BOT/Dummy +} diff --git a/Source/DealerSelection.Api.Models/ModelDetail.cs b/Source/DealerSelection.Api.Models/ModelDetail.cs new file mode 100644 index 0000000..a266a0e --- /dev/null +++ b/Source/DealerSelection.Api.Models/ModelDetail.cs @@ -0,0 +1,12 @@ +namespace DealerSelection.Api.Models +{ + public class ModelDetail + { + public ModelDetail(string modelCode) + { + ModelCode = modelCode; + } + + public string ModelCode { get; } + } +} diff --git a/Source/DealerSelection.Api.Models/MulesoftCustomerInfo.cs b/Source/DealerSelection.Api.Models/MulesoftCustomerInfo.cs new file mode 100644 index 0000000..79e4b1e --- /dev/null +++ b/Source/DealerSelection.Api.Models/MulesoftCustomerInfo.cs @@ -0,0 +1,58 @@ + +namespace DealerSelection.Api.Models; + +public class MulesoftCustomerInfo +{ + public MulesoftCustomerInfo(int buId, string buName, int recordId, string bookingId, string customerName, string mobileNumber, string modelCode, string modelName, string colorCode, string dealerCode, string dealerName, bool isRegisterInterestRequest, string pinCode, string utmCustomDetails1, string utmCustomDetails2, string status, string cCTransactionId, string receiptId, string amountPaid, string referralUrl, bool isWhatsappOptIn, int leadTransferred, string customerLat, string customerLong) + { + BuId = buId; + BuName = buName; + RecordId = recordId; + BookingId = bookingId; + CustomerName = customerName; + MobileNumber = mobileNumber; + ModelCode = modelCode; + ModelName = modelName; + ColorCode = colorCode; + DealerCode = dealerCode; + DealerName = dealerName; + IsRegisterInterestRequest = isRegisterInterestRequest; + PinCode = pinCode; + UtmCustomDetails1 = utmCustomDetails1; + UtmCustomDetails2 = utmCustomDetails2; + Status = status; + CCTransactionId = cCTransactionId; + ReceiptId = receiptId; + AmountPaid = amountPaid; + ReferralUrl = referralUrl; + IsWhatsappOptIn = isWhatsappOptIn; + LeadTransferred = leadTransferred; + CustomerLat = customerLat; + CustomerLong = customerLong; + } + + public int BuId { get; } + public string BuName { get; } + public int RecordId { get; } + public string BookingId { get; } + public string CustomerName { get; } + public string MobileNumber { get; } + public string ModelCode { get; } + public string ModelName { get; } + public string ColorCode { get; } + public string DealerCode { get; } + public string DealerName { get; } + public bool IsRegisterInterestRequest { get; } + public string PinCode { get; } + public string UtmCustomDetails1 { get; } + public string UtmCustomDetails2 { get; } + public string Status { get; } + public string CCTransactionId { get; } + public string ReceiptId { get; } + public string AmountPaid { get; } + public string ReferralUrl { get; } + public bool IsWhatsappOptIn { get; } + public int LeadTransferred { get; } + public string CustomerLat { get; } + public string CustomerLong { get; } +} diff --git a/Source/DealerSelection.Api.Models/Procedure.cs b/Source/DealerSelection.Api.Models/Procedure.cs index 49205da..952d695 100644 --- a/Source/DealerSelection.Api.Models/Procedure.cs +++ b/Source/DealerSelection.Api.Models/Procedure.cs @@ -3,13 +3,21 @@ namespace DealerSelection.Api.Infrastructure; public class Procedure { - public const string UpdateDealerDetails = "usp_update_dealer_details"; + //Booking SPs public const string GetCustomerBookingInfo = "usp_get_customer_booking_info"; public const string InsertUpdateDealerDetail = "usp_Insert_Update_Dealer_Details"; public const string InsertLSQDetail = "usp_insert_lsq_data"; public const string GetDataForLsqPush = "usp_get_data_for_lsq_push"; public const string GetCustomerInfoOnBookingId = "usp_get_customer_Info_on_BookingId"; - public const string GetCustomerDataForJob = "usp_get_CustomerDataForJob"; //TO BE ADDED IN DB - public const string IsDuplicateMobileNumber = "usp_isDuplicateMobileNumber"; //TO BE ADDED IN DB - public const string UpdateDealerSelectionJobStatus = "usp_update_DealerSelectionJobStatus"; //TO BE ADDED IN DB + + //DealerSelection SPs + public const string UpdateDealerDetails = "DealerSelection.usp_update_dealer_details"; + public const string GetCustomerDataForJob = "DealerSelection.usp_get_CustomerDataForJob"; + public const string IsDuplicateMobileNumber = "DealerSelection.usp_isDuplicateMobileNumber"; + public const string GetCustomerDetailByBuCode = "DealerSelection.usp_get_CustomerDetailByBuCode"; + public const string UpdateDealerSelectionJobStatus = "DealerSelection.usp_update_DealerSelectionJobStatus"; + public const string Get24HrOldRecordsForJobProcessing = "DealerSelection.usp_get_24HrOldRecordsFor_jobProcessing"; + public const string GetModelDetails = "DealerSelection.usp_get_ModelDetails"; + public const string GetBokingDetailOnBookingId = "DealerSelection.usp_get_BookingDetail_OnBookingId"; + public const string UpdateRefundStatus = "DealerSelection.usp_update_RefundStatus"; } diff --git a/Source/DealerSelection.Api.Models/RefundApiResponse.cs b/Source/DealerSelection.Api.Models/RefundApiResponse.cs new file mode 100644 index 0000000..0e1a93d --- /dev/null +++ b/Source/DealerSelection.Api.Models/RefundApiResponse.cs @@ -0,0 +1,23 @@ + +namespace DealerSelection.Api.Models; + +public class RefundApiResponse +{ + public RefundApiResponse(string status, RefundStatusResponse refundStatusResponse) + { + Status = status; + RefundStatusResponse = refundStatusResponse; + } + public string Status { get; set; } + public RefundStatusResponse RefundStatusResponse { get; set; } +} +public class RefundStatusResponse +{ + public int? refund_status { get; set; } + public string reason { get; set; } + public string error_code { get; set; } +} + + + + diff --git a/Source/DealerSelection.Api.Models/WebEngageEvent.cs b/Source/DealerSelection.Api.Models/WebEngageEvent.cs index 2eb319a..c04415d 100644 --- a/Source/DealerSelection.Api.Models/WebEngageEvent.cs +++ b/Source/DealerSelection.Api.Models/WebEngageEvent.cs @@ -4,10 +4,23 @@ namespace DealerSelection.Api.Models; public class WebEngageEventData { - public WebEngageEventData( string phoneNumber) + public WebEngageEventData(string bookingID, string bookingStatus, string bookingAmount,string dealerFlag, string fullName, string phoneNumber, + string motorcycleName, string motorcycleCode, string location, string dealerName, + string dealerPhoneNumber, string bookingReceiptLink) { + BookingID = bookingID; + BookingStatus = bookingStatus; + BookingAmount = bookingAmount; + BookingReceiptLink = bookingReceiptLink; + DealerFlag = dealerFlag; + FullName = fullName; + PhoneNumber = phoneNumber; + MotorcycleName = motorcycleName; + MotorcycleCode = motorcycleCode; + Location = location; + DealerName = dealerName; + DealerPhoneNumber = dealerPhoneNumber; - PhoneNumber = phoneNumber; } @@ -21,6 +34,12 @@ public class WebEngageEventData [JsonProperty("Booking Amount")] public string BookingAmount { get; } + [JsonProperty("Booking Receipt Link")] + public string BookingReceiptLink { get; } + + [JsonProperty("Dealer Flag")] + public string DealerFlag { get; } + [JsonProperty("Full Name")] public string FullName { get; } @@ -42,14 +61,6 @@ public class WebEngageEventData [JsonProperty("Dealer Phone Number")] public string DealerPhoneNumber { get; } - [JsonProperty("Booking Receipt Link")] - public string BookingReceiptLink { get; } - - [JsonProperty("Landing page URL")] - public string LandingPageURL { get; } - - - } public class WebEngageEvent { diff --git a/Source/DealerSelection.Api/AssignDealerApi.cs b/Source/DealerSelection.Api/AssignDealerApi.cs index ddfc59e..2842b28 100644 --- a/Source/DealerSelection.Api/AssignDealerApi.cs +++ b/Source/DealerSelection.Api/AssignDealerApi.cs @@ -1,6 +1,6 @@ using DealerSelection.Api.CommonUtil; using DealerSelection.Api.Infrastructure.AssignDealer; -using DealerSelection.Api.Infrastructure.CustomerDetail; +using CustomerDetailRepo = DealerSelection.Api.Infrastructure.CustomerDetail; using DealerSelection.Api.Infrastructure.Mulesoft; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; @@ -12,6 +12,9 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Org.BouncyCastle.Asn1.Tsp; using RestSharp; +using System; +using DealerSelection.Api.Models.Enum; +using JasperFx.CodeGeneration.Frames; public class AssignDealerApi : IAssignDealerApi { @@ -62,13 +65,13 @@ public class AssignDealerApi : IAssignDealerApi #endregion private readonly ILogger _logger; - private IAssignDealerRepository Repository { get; } - private DealerSelection.Api.Infrastructure.CustomerDetail.IRepository CustomerDetailRepository { get; } + private DealerSelection.Api.Infrastructure.AssignDealer.IRepository Repository { get; } + private CustomerDetailRepo.IRepository CustomerDetailRepository { get; } private IMulesoftApi MulesoftApi { get; } private IHttpClientHandler ClientHandler { get; } private readonly IMemoryCache _memoryCache; - public AssignDealerApi(IAssignDealerRepository repository, IMulesoftApi mulesoftApi, DealerSelection.Api.Infrastructure.CustomerDetail.IRepository customerRepo, + public AssignDealerApi(DealerSelection.Api.Infrastructure.AssignDealer.IRepository repository, IMulesoftApi mulesoftApi, CustomerDetailRepo.IRepository customerRepo, IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger logger) { Repository = repository; @@ -82,72 +85,66 @@ public class AssignDealerApi : IAssignDealerApi { try { - - MulesoftCustomerInfoDto customerInfo= await CustomerDetailRepository.GetCustomerData( buId, recordId); + _logger.LogInformation($"DS GetCustomerDataForJob Api called for:- BU:- {buId} and Record Id {recordId}"); + await CustomerDetailRepository.UpdateDealerSelectionJobStatus(buId, recordId, DealerSelectionJobStatus.Picked); // Record is picked by Job for Dealer Seclection + MulesoftCustomerInfoDto customerInfo = await CustomerDetailRepository.GetCustomerData(buId, recordId); await AssignDealers(customerInfo); } catch (Exception ex) { - _logger.LogError("Api:- GetDealers:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:- GetCustomerDataForJob:- " + ex.StackTrace.ToString()); } } private async Task AssignDealers(MulesoftCustomerInfoDto customerInfo) { - try + try { - MulesoftResponse dealerResponse = await MulesoftApi.GetDealers(customerInfo.BuId, customerInfo.BuName, customerInfo.CustomerLat, customerInfo.CustomerLong); - if (dealerResponse!=null && dealerResponse.IsRequestSuccessfull) + CustomCfg cfg = CustomCfg.GetCustomCfg(customerInfo.BuId); + MulesoftResponse dealerResponse = await MulesoftApi.GetDealers(customerInfo.BuId, customerInfo.BuCode, customerInfo.CustomerLat, customerInfo.CustomerLong); + if (dealerResponse != null && dealerResponse.IsRequestSuccessfull) { JObject obj = JObject.Parse(dealerResponse.Result); if (obj != null && obj["Data"] != null && obj["Data"].Count() > 0) - { + { if (obj["Data"].Count() == 1) { + _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} Api:- AssignDealers with 1 Dealer"); //Save dealer Detail and Send to LSQ JToken jArrResultData = (JToken)obj["Data"][0]; if (jArrResultData != null) { customerInfo.DealerCode = (JValue)jArrResultData["Code"] != null ? Convert.ToString(((JValue)jArrResultData["Code"]).Value) : "0"; customerInfo.DealerName = (JValue)jArrResultData["DisplayName"] != null ? Convert.ToString(((JValue)jArrResultData["DisplayName"]).Value) : "0"; - - try - { - var responseApi = await MulesoftApi.CallLSQBookingApi(customerInfo); - - if (responseApi != null && responseApi.IsRequestSuccessfull) - await UpdateDealerDetail(customerInfo, DealerSelectionJobStatus.Complete); - else - await UpdateDealerDetail(customerInfo, DealerSelectionJobStatus.ReadyForJob); - } - catch (Exception ex) - { - await UpdateDealerDetail(customerInfo, DealerSelectionJobStatus.ReadyForJob); - _logger.LogError("Error in LSQ " + ex.StackTrace.ToString()); - } + customerInfo.DealerSelectedMode = DealerSelectedMode.Auto.ToString(); + await MulesoftApi.InsertLSQData(customerInfo); } } - else + else if (obj["Data"].Count() > 1) { - //Send to Webengage - CustomCfg cfg = CustomCfg.GetCustomCfg(customerInfo.BuId); - WebEngageEventData eventData = new WebEngageEventData(customerInfo.MobileNumber); + _logger.LogInformation($"DS Api:- BU:- {customerInfo.BuId} Api:- Inititate Bot more then 1 Dealer"); + + // Send to Webengage to Initiate BOT + + WebEngageEventData eventData = new WebEngageEventData(customerInfo.BookingId, "SUCCESS", customerInfo.AmountPaid, "", "N", + customerInfo.CustomerName, customerInfo.MobileNumber, customerInfo.ModelName, customerInfo.ModelCode, customerInfo.CustomerLat, "", ""); WebEngageEvent events = new WebEngageEvent(customerInfo.MobileNumber, cfg.WebengageEventName, eventData); - await WebEngageEventsAPICall(events, cfg); + await WebEngageEventsAPICall(events, cfg, customerInfo.RecordId); } + } } } catch (Exception ex) { - _logger.LogError("BU:- " + customerInfo.BuId + "Api:- GetDealers:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:- BU:- {customerInfo.BuId} Api:- AssignDealers:- {ex.StackTrace.ToString()}"); } } - private async Task WebEngageEventsAPICall(WebEngageEvent message, CustomCfg cfg) + private async Task WebEngageEventsAPICall(WebEngageEvent message, CustomCfg cfg, int recordId) { - _logger.LogInformation("WebEngageEventsAPICall Started: " + JsonConvert.SerializeObject(message)); + _logger.LogInformation($"DS Api:-WebEngageEventsAPICall Started: " + JsonConvert.SerializeObject(message)); try { var json = JsonConvert.SerializeObject(message); @@ -164,27 +161,20 @@ public class AssignDealerApi : IAssignDealerApi RestResponse response = await client.ExecuteAsync(request); var content = response.Content; - _logger.LogInformation("WebEngageEventsAPICall End: " + content); + JObject obj = JObject.Parse(content); + if (obj != null && obj["response"] != null) + { + JToken jArrResultData = (JToken)obj["response"]["status"]; + if (jArrResultData != null && Convert.ToString(((JValue)jArrResultData).Value) == "queued") + await CustomerDetailRepository.UpdateDealerSelectionJobStatus(cfg.BuId, recordId, DealerSelectionJobStatus.SentToBot); + + } + _logger.LogInformation($"DS Api:-WebEngageEventsAPICall End: " + content); } catch (Exception ex) { - _logger.LogError("PendingStatusUpdateApi:- WebEngageEventsAPICall:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-PendingStatusUpdateApi:- WebEngageEventsAPICall:- " + ex.Message.ToString()); } } - - private async Task UpdateDealerDetail(MulesoftCustomerInfoDto customerInfo, DealerSelectionJobStatus jobStatus) - { - CustomerDealerInfoRequestDto dto = new CustomerDealerInfoRequestDto - { - BuId = customerInfo.BuId, - DealerName = jobStatus == DealerSelectionJobStatus.Complete ? customerInfo.DealerName : "", - DealerCode = jobStatus == DealerSelectionJobStatus.Complete ? customerInfo.DealerCode : "", - DealerSelectionJobStatus = jobStatus == DealerSelectionJobStatus.Complete ? DealerSelectionJobStatus.Complete : DealerSelectionJobStatus.ReadyForJob, - RecordId = customerInfo.RecordId - - }; - await CustomerDetailRepository.UpdateDealerDetail(dto); - } - } \ No newline at end of file diff --git a/Source/DealerSelection.Api/BatchJobApi.cs b/Source/DealerSelection.Api/BatchJobApi.cs new file mode 100644 index 0000000..0dc6edc --- /dev/null +++ b/Source/DealerSelection.Api/BatchJobApi.cs @@ -0,0 +1,42 @@ +using DealerSelection.Api.CommonUtil; +using DealerSelection.Api.Infrastructure.BatchJob; +using DealerSelection.Api.Infrastructure.Mulesoft; +using DealerSelection.Api.Interface; +using DealerSelection.Api.Models.Enum; +using Microsoft.Extensions.Logging; +using System.Collections.Generic; + +public class BatchJobApi : IBatchJobApi +{ + + private readonly ILogger _logger; + private DealerSelection.Api.Infrastructure.BatchJob.IRepository Repository { get; } + private IMulesoftApi MulesoftApi { get; } + public BatchJobApi(DealerSelection.Api.Infrastructure.BatchJob.IRepository repository, ILogger logger, IMulesoftApi mulesoftApi) + { + Repository = repository; + _logger = logger; + MulesoftApi = mulesoftApi; + } + public async Task Process24HrOldRecords() + { + try + { + List customerInfo = await Repository.Get24HrOldRecordsForJobProcessing(); + + foreach (var item in customerInfo) + { + CustomCfg cfg = CustomCfg.GetCustomCfg(item.BuId); + item.DealerCode = cfg.DeafaultDealerCode; + item.DealerSelectedMode = DealerSelectedMode.Dummy.ToString(); + await MulesoftApi.InsertLSQData(item); + } + } + catch (Exception ex) + { + _logger.LogError($"DS Api:-Api:- BatchJob:- " + ex.StackTrace.ToString()); + } + } + + +} \ No newline at end of file diff --git a/Source/DealerSelection.Api/CCAvenue/MCPG.CCA.Util.dll b/Source/DealerSelection.Api/CCAvenue/MCPG.CCA.Util.dll new file mode 100644 index 0000000..05e2d39 Binary files /dev/null and b/Source/DealerSelection.Api/CCAvenue/MCPG.CCA.Util.dll differ diff --git a/Source/DealerSelection.Api/CCAvenueApi.cs b/Source/DealerSelection.Api/CCAvenueApi.cs new file mode 100644 index 0000000..2cd58af --- /dev/null +++ b/Source/DealerSelection.Api/CCAvenueApi.cs @@ -0,0 +1,190 @@ +using DealerSelection.Api.CommonUtil; +using DealerSelection.Api.Infrastructure.CCAvenue; +using DealerSelection.Api.Interface; +using DealerSelection.Common.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Net; +using CCA.Util; +using DealerSelection.Api.Models; +using FastExpressionCompiler; +using JasperFx.Core; +using System.Security.Cryptography; + +public class CCAvenueApi : ICCAvenueApi +{ + + private readonly ILogger _logger; + private IRepository Repository { get; } + private IMulesoftApi MulesoftApi { get; } + private string? CCAvenueApiPayUrl = ConfigurationHelper.GetSetting("CCAvenueApiPayUrl", true); + public CCAvenueApi(ILogger logger, IRepository repository) + { + _logger = logger; + Repository = repository; + } + public async Task RefundOrder(string bookingId, string transactionId) + { + Dto customerInfo = await Repository.GetBookingDetail(bookingId, transactionId); + //Dto customerInfo = new Dto() + //{ + // AmountPaid = "4499", + // BuId = 1, + // RecordId = 800 + //}; + + RefundApiResponse response = null; + if (customerInfo != null) + { + CustomCfg cfg = CustomCfg.GetCustomCfg(customerInfo.BuId); + try + { + int rnd = RandomNumberGenerator.GetInt32(100000,999999); + string refundRefNo= cfg.BuCode + customerInfo.RecordId + rnd; + string orderStatusQueryJson = "{\"reference_no\":\"" + transactionId + "\",\"refund_amount\": \"" + customerInfo.AmountPaid + "\"," + + "\"refund_ref_no\": \"" + refundRefNo + "\" }"; + string encJson = ""; + string queryUrl = CCAvenueApiPayUrl + "/apis/servlet/DoWebTrans?"; + + CCACrypto ccaCrypto = new CCACrypto(); + encJson = ccaCrypto.Encrypt(orderStatusQueryJson, cfg.CCAvenueWorkingKey); // + + + string authQueryUrlParam = "enc_request=" + encJson + "&access_code=" + cfg.CCAvenueAccessCode + + "&command=refundOrder&request_type=JSON&response_type=JSON"; + + string message = await SendRequestToGateWay(queryUrl, authQueryUrlParam); + NameValueCollection param = GetResponseCollection(message); + string status = ""; + string encResJson = ""; + if (param != null && param.Count == 2) + { + //for (int i = 0; i < param.Count; i++) + //{ + // if ("status".Equals(param.Keys[i])) + // { + // status = param[i]; + // } + // if ("enc_response".Equals(param.Keys[i])) + // { + // encResJson = param[i]; + // } + //} + if (message.Contains("status") && message.Contains("enc_response")) + { + status = param.Get("status"); + encResJson = param.Get("enc_response"); + } + + string ResJson = ""; + + // response.Status = status; + RefundStatusResponse _refundStatusResponse = new(); + if (!"".Equals(status) && status.Equals("0")) + { + ResJson = ccaCrypto.Decrypt(encResJson, cfg.CCAvenueWorkingKey); + dynamic objResult = JObject.Parse(ResJson); + _refundStatusResponse.reason = objResult.Refund_Order_Result.reason; + _refundStatusResponse.refund_status = objResult.Refund_Order_Result.refund_status; + + _refundStatusResponse.error_code = objResult.Refund_Order_Result.error_code; + + //_refundStatusResponse = JsonConvert.DeserializeObject(ResJson); + + _logger.LogInformation($"DS Api:-BU:- {customerInfo.BuId} + Refund Api Response for bookingId:- {bookingId} and Response:- {ResJson}"); + + //if (_refundStatusResponse != null) + //{ + // response.refundStatusResponse = _refundStatusResponse; + //} + } + else if (!"".Equals(status) && status.Equals("1")) + { + _refundStatusResponse.reason = encResJson; + } + await Repository.UpdateRefundStatus(customerInfo.BuId,bookingId, transactionId, refundRefNo, _refundStatusResponse); + + response = new RefundApiResponse(status, _refundStatusResponse); + } + return response; + } + catch (Exception ex) + { + _logger.LogError($"DS Api:-BU:- {customerInfo.BuId} + RefundOrder Error for bookingId:- {bookingId} - {ex.StackTrace}"); + throw ex; + } + } + else + { + RefundStatusResponse _refundStatusResponse = new(); + { + _refundStatusResponse.refund_status = 1; + _refundStatusResponse.reason = "No record found"; + }; + response = new RefundApiResponse("1", _refundStatusResponse); + response.Status = "1"; + + } + return response; + + } + private static async Task SendRequestToGateWay(string queryUrl, string urlParam) + { + + string message = ""; + try + { + StreamWriter myWriter = null;// it will open a http connection with provided url + WebRequest objRequest = WebRequest.Create(queryUrl);//send data using objxmlhttp object + objRequest.Method = "POST"; + objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type + myWriter = new StreamWriter(objRequest.GetRequestStream()); + myWriter.Write(urlParam);//send data + myWriter.Close();//closed the myWriter object + + // Getting Response + HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object + using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) + { + message = sr.ReadToEnd(); + } + } + catch (Exception ex) + { + throw ex; + } + return message; + + } + + private static NameValueCollection GetResponseCollection(string message) + { + NameValueCollection Params = new NameValueCollection(); + try + { + if (message != null || !"".Equals(message)) + { + string[] segments = message.Split('&'); + foreach (string seg in segments) + { + string[] parts = seg.Split('='); + if (parts.Length > 0) + { + string Key = parts[0].Trim(); + string Value = parts[1].Trim(); + Params.Add(Key, Value); + } + } + } + } + catch (Exception ex) + { + throw ex; + } + return Params; + } + +} \ No newline at end of file diff --git a/Source/DealerSelection.Api/CommonUtil/CustomConfig.cs b/Source/DealerSelection.Api/CommonUtil/CustomConfig.cs index c8dba12..68acb89 100644 --- a/Source/DealerSelection.Api/CommonUtil/CustomConfig.cs +++ b/Source/DealerSelection.Api/CommonUtil/CustomConfig.cs @@ -6,6 +6,7 @@ namespace DealerSelection.Api.CommonUtil { public int BuId { get; set; } public string BuCode { get; set; } + public string DeafaultDealerCode { get; set; } public string InfoBipAppilcationId { get; set; } public string InfoBipMessageId { get; set; } public string InfoBipFroms { get; set; } @@ -35,93 +36,27 @@ namespace DealerSelection.Api.CommonUtil CustomCfg cfg = new CustomCfg(); switch (buId) { - case 1: - cfg.InfoBipAppilcationId = ConfigurationHelper.GetSetting("KtmCfg:InfoBipAppilcationId", true); - cfg.InfoBipMessageId = ConfigurationHelper.GetSetting("KtmCfg:InfoBipMessageId", true); - cfg.InfoBipFroms = ConfigurationHelper.GetSetting("KtmCfg:InfoBipFrom", true); - + case 1: + cfg.BuCode= ConfigurationHelper.GetSetting("KtmCfg:BuCode", true); cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting("KtmCfg:CCAvenueAccessCode", true); - cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting("KtmCfg:CCAvenueMerchantCode", true); - cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting("KtmCfg:CCAvenueBaseUrl", true); - cfg.BookingPrice = ConfigurationHelper.GetSetting("KtmCfg:BookingPrice", true); + cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting("KtmCfg:CCAvenueMerchantCode", true); cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting("KtmCfg:CCAvenueWorkingKey", true); - cfg.BuCode= ConfigurationHelper.GetSetting("KtmCfg:BuCode", true); - cfg.WebengageLandingPageUrl= ConfigurationHelper.GetSetting("KtmCfg:LandingPageUrl", true); cfg.WebengageEventName = ConfigurationHelper.GetSetting("KtmCfg:WebengageEventName", true); cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting("KtmCfg:WebEngageLicenseCode", true); cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting("KtmCfg:WebEngageAuthToken", true); - cfg.WebengageApiHost = ConfigurationHelper.GetSetting("KtmCfg:WebengageApiHost", true); - cfg.ValidateDuplicate = ConfigurationHelper.GetSetting("KtmCfg:ValidateDuplicate", true); - cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting("KtmCfg:ValidateDuplicateHr", true); - cfg.BuId = buId; - - cfg.ClientId = ConfigurationHelper.GetSetting("KtmCfg:ClientId", true); - cfg.ClientSecret = ConfigurationHelper.GetSetting("KtmCfg:ClientSecret", true); - cfg.Key = ConfigurationHelper.GetSetting("KtmCfg:Key", true); - cfg.Audience = ConfigurationHelper.GetSetting("KtmCfg:Audience", true); - cfg.Issuer = ConfigurationHelper.GetSetting("KtmCfg:Issuer", true); - cfg.Role = ConfigurationHelper.GetSetting("KtmCfg:Role", true); - cfg.ExpireMinutes = ConfigurationHelper.GetSetting("KtmCfg:ExpireMinutes", true); - break; - case 2: - cfg.InfoBipAppilcationId = ConfigurationHelper.GetSetting("BajajCfg:InfoBipAppilcationId", true); - cfg.InfoBipMessageId = ConfigurationHelper.GetSetting("BajajCfg:InfoBipMessageId", true); - cfg.InfoBipFroms = ConfigurationHelper.GetSetting("BajajCfg:InfoBipFrom", true); - cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting("BajajCfg:CCAvenueAccessCode", true); - cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting("BajajCfg:CCAvenueMerchantCode", true); - cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting("BajajCfg:CCAvenueBaseUrl", true); - cfg.BookingPrice = ConfigurationHelper.GetSetting("BajajCfg:BookingPrice", true); - cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting("BajajCfg:CCAvenueWorkingKey", true); - cfg.BuCode = ConfigurationHelper.GetSetting("BajajCfg:BuCode", true); - cfg.WebengageLandingPageUrl = ConfigurationHelper.GetSetting("BajajCfg:LandingPageUrl", true); - cfg.WebengageEventName = ConfigurationHelper.GetSetting("BajajCfg:WebengageEventName", true); - cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting("BajajCfg:WebEngageLicenseCode", true); - cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting("BajajCfg:WebEngageAuthToken", true); - cfg.WebengageApiHost = ConfigurationHelper.GetSetting("BajajCfg:WebengageApiHost", true); - cfg.ValidateDuplicate = ConfigurationHelper.GetSetting("BajajCfg:ValidateDuplicate", true); - cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting("BajajCfg:ValidateDuplicateHr", true); + cfg.WebengageApiHost = ConfigurationHelper.GetSetting("KtmCfg:WebengageApiHost", true); cfg.BuId = buId; - - cfg.ClientId = ConfigurationHelper.GetSetting("BajajCfg:ClientId", true); - cfg.ClientSecret = ConfigurationHelper.GetSetting("BajajCfg:ClientSecret", true); - cfg.Key = ConfigurationHelper.GetSetting("BajajCfg:Key", true); - cfg.Audience = ConfigurationHelper.GetSetting("BajajCfg:Audience", true); - cfg.Issuer = ConfigurationHelper.GetSetting("BajajCfg:Issuer", true); - cfg.Role = ConfigurationHelper.GetSetting("BajajCfg:Role", true); - cfg.ExpireMinutes = ConfigurationHelper.GetSetting("BajajCfg:ExpireMinutes", true); - break; - case 3: - cfg.InfoBipAppilcationId = ConfigurationHelper.GetSetting("TriumphCfg:InfoBipAppilcationId", true); - cfg.InfoBipMessageId = ConfigurationHelper.GetSetting("TriumphCfg:InfoBipMessageId", true); - cfg.InfoBipFroms = ConfigurationHelper.GetSetting("TriumphCfg:InfoBipFrom", true); - cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting("TriumphCfg:CCAvenueAccessCode", true); - cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting("TriumphCfg:CCAvenueMerchantCode", true); - cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting("TriumphCfg:CCAvenueBaseUrl", true); - cfg.BookingPrice = ConfigurationHelper.GetSetting("TriumphCfg:BookingPrice", true); - cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting("TriumphCfg:CCAvenueWorkingKey", true); - cfg.BuCode = ConfigurationHelper.GetSetting("TriumphCfg:BuCode", true); - cfg.WebengageLandingPageUrl = ConfigurationHelper.GetSetting("TriumphCfg:LandingPageUrl", true); - cfg.WebengageEventName = ConfigurationHelper.GetSetting("TriumphCfg:WebengageEventName", true); - cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting("TriumphCfg:WebEngageLicenseCode", true); - cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting("TriumphCfg:WebEngageAuthToken", true); - cfg.WebengageApiHost = ConfigurationHelper.GetSetting("TriumphCfg:WebengageApiHost", true); - cfg.ValidateDuplicate = ConfigurationHelper.GetSetting("TriumphCfg:ValidateDuplicate", true); - cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting("TriumphCfg:ValidateDuplicateHr", true); - cfg.BuId = buId; - - cfg.ClientId = ConfigurationHelper.GetSetting("TriumphCfg:ClientId", true); - cfg.ClientSecret = ConfigurationHelper.GetSetting("TriumphCfg:ClientSecret", true); - cfg.Key = ConfigurationHelper.GetSetting("TriumphCfg:Key", true); - cfg.Audience = ConfigurationHelper.GetSetting("TriumphCfg:Audience", true); - cfg.Issuer = ConfigurationHelper.GetSetting("TriumphCfg:Issuer", true); - cfg.Role = ConfigurationHelper.GetSetting("TriumphCfg:Role", true); - cfg.ExpireMinutes = ConfigurationHelper.GetSetting("TriumphCfg:ExpireMinutes", true); - break; + cfg.DeafaultDealerCode = ConfigurationHelper.GetSetting("KtmCfg:DefaultDealerCode", true); + //cfg.ClientId = ConfigurationHelper.GetSetting("KtmCfg:ClientId", true); + //cfg.ClientSecret = ConfigurationHelper.GetSetting("KtmCfg:ClientSecret", true); + // cfg.Key = ConfigurationHelper.GetSetting("KtmCfg:Key", true); + // cfg.Audience = ConfigurationHelper.GetSetting("KtmCfg:Audience", true); + // cfg.Issuer = ConfigurationHelper.GetSetting("KtmCfg:Issuer", true); + // cfg.Role = ConfigurationHelper.GetSetting("KtmCfg:Role", true); + // cfg.ExpireMinutes = ConfigurationHelper.GetSetting("KtmCfg:ExpireMinutes", true); + break; default: - cfg.InfoBipAppilcationId = ""; - cfg.InfoBipMessageId = ""; - cfg.InfoBipFroms = ""; - cfg.BuId = buId; + cfg.BuId = buId; break; } return cfg; diff --git a/Source/DealerSelection.Api/InfoBipSmsServiceApi.cs b/Source/DealerSelection.Api/InfoBipSmsServiceApi.cs index a8a97ae..f4d7c6b 100644 --- a/Source/DealerSelection.Api/InfoBipSmsServiceApi.cs +++ b/Source/DealerSelection.Api/InfoBipSmsServiceApi.cs @@ -50,7 +50,7 @@ public class InfoBipSmsServiceApi : IInfoBipSmsServiceApi } catch (Exception ex) { - _logger.LogError("Api:- sendOTP:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-Api:- sendOTP:- " + ex.StackTrace.ToString()); } return obj; @@ -79,7 +79,7 @@ public class InfoBipSmsServiceApi : IInfoBipSmsServiceApi catch (Exception ex) { errorMessage = ex.Message; - _logger.LogError("BUID:- " + buId + "Api:- resendOTP:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-BUID:- " + buId + "Api:- resendOTP:- " + ex.Message.ToString()); } @@ -103,7 +103,7 @@ public class InfoBipSmsServiceApi : IInfoBipSmsServiceApi } catch (Exception ex) { - _logger.LogError("BUID:- " + buId + " Api:- verifyOTP:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-BUID:- " + buId + " Api:- verifyOTP:- " + ex.StackTrace.ToString()); } @@ -123,7 +123,7 @@ public class InfoBipSmsServiceApi : IInfoBipSmsServiceApi JObject obj = JObject.Parse(await response.Content.ReadAsStringAsync()); - _logger.LogError($"BuId: {buId}, MobileNumber: {strMobile}, OTP Type: {otpRequestType}, ApiRequest: {data} , ApiResponse: {response}"); + _logger.LogError($"DS Api:-BuId: {buId}, MobileNumber: {strMobile}, OTP Type: {otpRequestType}, ApiRequest: {data} , ApiResponse: {response}"); return obj; } diff --git a/Source/DealerSelection.Api/JwtTokenApi.cs b/Source/DealerSelection.Api/JwtTokenApi.cs index 371f0a5..072292b 100644 --- a/Source/DealerSelection.Api/JwtTokenApi.cs +++ b/Source/DealerSelection.Api/JwtTokenApi.cs @@ -2,6 +2,7 @@ using DealerSelection.Api.Infrastructure.Jwt; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; +using DealerSelection.Common.Configuration; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; @@ -12,7 +13,12 @@ public class JwtTokenApi : IJwtTokenApi { private IJwtRepository Repository { get; } private readonly ILogger _logger; - + public static string _key = ConfigurationHelper.GetSetting("Jwt:Key", true); + public static string _expireMinutes = ConfigurationHelper.GetSetting("Jwt:ExpireMinutes", true); + public static string _issuer = ConfigurationHelper.GetSetting("Jwt:Issuer", true); + public static string _audience = ConfigurationHelper.GetSetting("Jwt:Audience", true); + public static string _clientId = ConfigurationHelper.GetSetting("Jwt:ClientId", true); + public static string _clientSecret = ConfigurationHelper.GetSetting("Jwt:ClientSecret", true); public JwtTokenApi(IJwtRepository repository, ILogger logger) { Repository = repository; @@ -27,16 +33,14 @@ public class JwtTokenApi : IJwtTokenApi if (isValidUser) { AuthModel auth = new AuthModel - { - BuId = user.BuId, - ClientId = user.ClientId, - SecretId = user.SecretId, + { + ClientId = user.client_id, + SecretId = user.client_secret, Role = "Admin" - }; - CustomCfg cfg = CustomCfg.GetCustomCfg(auth.BuId); + }; - var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg.Key)); - string expireMinutes = cfg.ExpireMinutes; + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)); + string expireMinutes = _expireMinutes; int tokenExpireMinutes = string.IsNullOrEmpty(expireMinutes) ? 1439 : int.Parse(expireMinutes); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] @@ -45,8 +49,8 @@ public class JwtTokenApi : IJwtTokenApi new Claim(ClaimTypes.Role,auth.Role), }; var token = new JwtSecurityToken( - cfg.Issuer, - cfg.Audience, + _issuer, + _audience, claims, expires: DateTime.UtcNow.AddMinutes(tokenExpireMinutes), signingCredentials: credentials); @@ -55,7 +59,7 @@ public class JwtTokenApi : IJwtTokenApi } catch (Exception ex) { - _logger.LogError("JwtTokenApi Api GenerateToken:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-JwtTokenApi Api GenerateToken:- " + ex.Message.ToString()); } return null; @@ -64,15 +68,14 @@ public class JwtTokenApi : IJwtTokenApi public async Task Authenticate(AuthValidateModel userLogin) { try - { - CustomCfg cfg = CustomCfg.GetCustomCfg(userLogin.BuId); + { - return cfg.ClientId.ToLower() == userLogin.ClientId.ToLower() && - cfg.ClientSecret.ToLower() == userLogin.SecretId.ToLower(); + return _clientId.ToLower() == userLogin.client_id.ToLower() && + _clientSecret.ToLower() == userLogin.client_secret.ToLower(); } catch (Exception ex) { - _logger.LogError("JwtTokenApi Api Authenticate:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-JwtTokenApi Api Authenticate:- " + ex.Message.ToString()); } return false; } @@ -95,7 +98,7 @@ public class JwtTokenApi : IJwtTokenApi } catch (Exception ex) { - _logger.LogError("JwtTokenApi Api IsTokenExpired:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-JwtTokenApi Api IsTokenExpired:- " + ex.Message.ToString()); return tokenValid; } } diff --git a/Source/DealerSelection.Api/MulesoftApi.cs b/Source/DealerSelection.Api/MulesoftApi.cs index 921af0b..065631f 100644 --- a/Source/DealerSelection.Api/MulesoftApi.cs +++ b/Source/DealerSelection.Api/MulesoftApi.cs @@ -1,7 +1,9 @@ using DealerSelection.Api.CommonUtil; +using CustomerDetailRepo = DealerSelection.Api.Infrastructure.CustomerDetail; using DealerSelection.Api.Infrastructure.Mulesoft; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; using DealerSelection.Common.Configuration; using DealerSelection.Common.Interfaces.HttpClient; using DealerSelection.Common.Logging; @@ -64,8 +66,8 @@ public class MulesoftApi : IMulesoftApi private IMulesoftTokenApi MulesoftTokenApi { get; } private IHttpClientHandler ClientHandler { get; } private readonly IMemoryCache _memoryCache; - - public MulesoftApi(IRepository repository, IMulesoftTokenApi mulesoftTokenApi, + private CustomerDetailRepo.IRepository CustomerDetailRepository { get; } + public MulesoftApi(IRepository repository, IMulesoftTokenApi mulesoftTokenApi, CustomerDetailRepo.IRepository customerRepo, IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger logger) { Repository = repository; @@ -73,6 +75,7 @@ public class MulesoftApi : IMulesoftApi ClientHandler = clientHandler; _memoryCache = memoryCache; _logger = logger; + CustomerDetailRepository = customerRepo; } @@ -106,7 +109,7 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("BU:- " + buId + "Api:- GetDealers:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-BUID:- " + buId + "Api:- GetDealers:- " + ex.StackTrace.ToString()); } return response; } @@ -144,265 +147,54 @@ public class MulesoftApi : IMulesoftApi _memoryCache.Set(cacheKey, response, cacheExpiryOptions); } } - _logger.LogError("Api:- GetAndInsertDealerDetails From Cache:- " + cacheKey); + _logger.LogError($"DS Api:-GetAndInsertDealerDetails From Cache:- {cacheKey}"); } catch (Exception ex) { - _logger.LogError("Api:- GetAndInsertDealerDetails:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:- GetAndInsertDealerDetails:- {ex.Message.ToString()}"); } return response; } - public async Task GetStateWisePrice(int buId, string stateCode, string itemId) + public async Task InsertLSQData(MulesoftCustomerInfoDto customerInfo) { - MulesoftResponse response = null; try { - var cacheKey = "getStateWisePrice_" + buId + stateCode + itemId; - if (!_memoryCache.TryGetValue(cacheKey, out response)) + try { - _logger.LogError("Api:- GetStateWisePrice API:- " + cacheKey); - - string authToken = await MulesoftTokenApi.FetchToken(); - string message = "{\"statecode\": \"" + stateCode.ToUpper() + "\",\"itemId\": \"" - + itemId + "\",\"masterSchemaId\": \"" + muleSoftPricemasterSchemaId + "\"}"; - - if (!string.IsNullOrEmpty(authToken)) - { - string password = GenerateRandomString.GenerateString(32); - string encstring = AESEncryption.ReturnEncKey(password, message); + await UpdateDetails(customerInfo, DealerSelectionJobStatus.Complete); + var responseApi = await CallLSQBookingApi(customerInfo); - var plainTextBytes = Encoding.UTF8.GetBytes(password); - string encKeyToHeader = Convert.ToBase64String(plainTextBytes); - - var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, - encstring, muleSoftStateWisePrice, authToken, encKeyToHeader); - response = await ValidateMuleSoftResponse(buId, response2); - var jsonresult = JObject.Parse(response.Result); - - if (Convert.ToBoolean(jsonresult["IsRequestSuccessfull"]) && jsonresult["Data"] != null) - { - string exShowroomPrice = jsonresult["Data"][0]["ExPrice"].ToString(); - MulesoftResponse mulesoftResponse = new MulesoftResponse(buId, 0, Convert.ToBoolean(jsonresult["IsRequestSuccessfull"]), - exShowroomPrice, "", ""); - - var cacheExpiryOptions = new MemoryCacheEntryOptions - { - AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheGetPriceOnState), - Priority = CacheItemPriority.High - }; - _memoryCache.Set(cacheKey, mulesoftResponse, cacheExpiryOptions); - - return mulesoftResponse; - } - else - { - return new MulesoftResponse(buId, 0, false, response.Result, "", ""); - } - } } - _logger.LogError("Api:- GetStateWisePrice From Cache :- " + cacheKey); - } - catch (Exception ex) - { - _logger.LogError("Api:- GetStateWisePrice:- " + ex.Message.ToString()); - } - return response; - } - - public async Task GetModelOnBrand(int buId, string brand) - { - MulesoftResponse response = null; - try - { - var cacheKey = "getModelOnBrand_" + buId + brand; - if (!_memoryCache.TryGetValue(cacheKey, out response)) + catch (Exception ex) { - _logger.LogError("Api:- GetModelOnBrand API:- " + cacheKey); - - string authToken = await MulesoftTokenApi.FetchToken(); - string message = "{\"brand\": \"" + brand.ToUpper() + - "\",\"masterSchemaId\": \"" + muleSoftModelmasterSchemaId + "\"}"; - - if (!string.IsNullOrEmpty(authToken)) - { - string password = GenerateRandomString.GenerateString(32); - string encstring = AESEncryption.ReturnEncKey(password, message); - - var plainTextBytes = Encoding.UTF8.GetBytes(password); - string encKeyToHeader = Convert.ToBase64String(plainTextBytes); - - var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, - encstring, muleSoftBrandWiseModel, authToken, encKeyToHeader); - response = await ValidateMuleSoftResponse(buId, response2); - - var cacheExpiryOptions = new MemoryCacheEntryOptions - { - AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheGetModelOnBrand), - Priority = CacheItemPriority.High - }; - _memoryCache.Set(cacheKey, response, cacheExpiryOptions); - } + //await UpdateDetails(customerInfo, DealerSelectionJobStatus.ReadyForJob); + _logger.LogError($"DS Api:-Error in LSQ " + ex.StackTrace.ToString()); } - _logger.LogError("Api:- GetModelOnBrand From Cache:- " + cacheKey); } catch (Exception ex) { - _logger.LogError("Api:- GetModelOnBrand:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-Api:- GetDealers:- " + ex.StackTrace.ToString()); } - return response; } - public async Task GetActiveState(int buId) - { - CustomCfg cfg = CustomCfg.GetCustomCfg(buId); - MulesoftResponse response = null; - try - { - var cacheKey = "getActiveState_" + buId; - if (!_memoryCache.TryGetValue(cacheKey, out response)) - { - _logger.LogError("Api:- GetActiveState API:- " + cacheKey); - - string authToken = await MulesoftTokenApi.FetchToken(); - string message = "{\"bu\": \"" + cfg.BuCode.ToUpper() + - "\",\"masterSchemaId\": \"" + muleSoftStateMasterSchemaId + "\"}"; - - if (!string.IsNullOrEmpty(authToken)) - { - string password = GenerateRandomString.GenerateString(32); - string encstring = AESEncryption.ReturnEncKey(password, message); - - var plainTextBytes = Encoding.UTF8.GetBytes(password); - string encKeyToHeader = Convert.ToBase64String(plainTextBytes); - - var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, encstring, - muleSoftStateMasterSchemaApi, authToken, encKeyToHeader); - response = await ValidateMuleSoftResponse(0, response2); + #region Private Methods - var cacheExpiryOptions = new MemoryCacheEntryOptions - { - AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheGetActiveState), - Priority = CacheItemPriority.High - }; - _memoryCache.Set(cacheKey, response, cacheExpiryOptions); - } - } - _logger.LogError("Api:- GetActiveState from Cache:- " + cacheKey); - } - catch (Exception ex) - { - _logger.LogError("Api:- GetActiveState:- " + ex.Message.ToString()); - } - return response; - } - - public async Task GetActiveCity(int buId, string stateCode) + private async Task CallLSQBookingApi(MulesoftCustomerInfoDto customerInfo) { - CustomCfg cfg = CustomCfg.GetCustomCfg(buId); - MulesoftResponse response = null; - try - { - var cacheKey = "getActiveCity_" + buId + stateCode; - if (!_memoryCache.TryGetValue(cacheKey, out response)) - { - _logger.LogError("Api GetActiveCity:- API:- " + cacheKey); - - string authToken = await MulesoftTokenApi.FetchToken(); - string message = "{\"bu\": \"" + cfg.BuCode.ToUpper() + "\",\"stateId\": \"" + stateCode.ToUpper() + - "\",\"masterSchemaId\": \"" + muleSoftCityMasterSchemaId + "\"}"; - - if (!string.IsNullOrEmpty(authToken)) - { - string password = GenerateRandomString.GenerateString(32); - string encstring = AESEncryption.ReturnEncKey(password, message); - - var plainTextBytes = Encoding.UTF8.GetBytes(password); - string encKeyToHeader = Convert.ToBase64String(plainTextBytes); - - var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, - encstring, muleSoftCityMasterSchemaApi, - authToken, encKeyToHeader); - response = await ValidateMuleSoftResponse(0, response2); - - var cacheExpiryOptions = new MemoryCacheEntryOptions - { - AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheGetActiveCity), - Priority = CacheItemPriority.High - }; - _memoryCache.Set(cacheKey, response, cacheExpiryOptions); - } - } - - _logger.LogError("Api:- GetStateWisePrice:- API:- From Cache" + cacheKey); - } - catch (Exception ex) - { - _logger.LogError("Api:- GetActiveCity:- " + ex.Message.ToString()); - } - return response; - } - - public async Task ModelDetailsByItemCode(int buId, string itemId) - { - MulesoftResponse response = null; - try - { - var cacheKey = "modelDetailsItemCode_" + buId + itemId; - if (!_memoryCache.TryGetValue(cacheKey, out response)) - { - _logger.LogError("Api:- GetStateWisePrice:- API:- From Cache" + cacheKey); - - string authToken = await MulesoftTokenApi.FetchToken(); - string message = "{\"itemid\": \"" + itemId + "\",\"masterSchemaId\": \"" - + muleSoftModelMasterSchemaItemId + "\"}"; - - if (!string.IsNullOrEmpty(authToken)) - { - string password = GenerateRandomString.GenerateString(32); - string encstring = AESEncryption.ReturnEncKey(password, message); - - var plainTextBytes = Encoding.UTF8.GetBytes(password); - string encKeyToHeader = Convert.ToBase64String(plainTextBytes); - - var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, - encstring, muleSoftModelMasterSchemaItemApi, authToken, encKeyToHeader); - response = await ValidateMuleSoftResponse(0, response2); - - var cacheExpiryOptions = new MemoryCacheEntryOptions - { - AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheModelDetails), - Priority = CacheItemPriority.High - }; - _memoryCache.Set(cacheKey, response, cacheExpiryOptions); - } - } - - _logger.LogError("Api:- GetStateWisePrice:- API:- From Cache" + cacheKey); - } - catch (Exception ex) - { - _logger.LogError("Api:- GetStateWisePrice:- " + ex.Message.ToString()); - } - return response; - } - - public async Task GetCustomerInfo(int buId, string bookingId) - { - return await Repository.GetCustomerInfo(buId, bookingId); - } - - public async Task CallLSQBookingApi( MulesoftCustomerInfoDto customerInfo) - { - _logger.LogInformation($"BU:- {customerInfo.BuId} at MulesofApi:- CallBookingApi for Booking Id:- {customerInfo.BookingId}"); + CustomCfg cfg = CustomCfg.GetCustomCfg(customerInfo.BuId); + _logger.LogInformation($"DS Api:-BU:- {customerInfo.BuId} at MulesofApi:- CallBookingApi for Booking Id:- {customerInfo.BookingId}"); try { if (customerInfo != null) { string mx_Composite_Key = string.Empty, enquiryClassification = string.Empty, - leadPlatform = "Website", autoModel = string.Empty, - bookingStatus = string.Empty, isSuccessBooking = "True"; + autoModel = string.Empty, dealerCode = string.Empty, status = string.Empty, + bookingId = string.Empty, cCTransactionId = string.Empty, receiptId = string.Empty, + amountPaid = string.Empty, leadPlatform = "Website", isSuccessBooking = "True", isDefaultDealer="No"; + + string utmSource = GetUTMDetails(customerInfo.ReferralUrl, "utm_source"); string utmMedium = GetUTMDetails(customerInfo.ReferralUrl, "utm_medium"); string sourceCampaign = GetUTMDetails(customerInfo.ReferralUrl, "utm_campaign"); @@ -424,11 +216,18 @@ public class MulesoftApi : IMulesoftApi mx_Enquiry_Sub_source = customerInfo.UtmCustomDetails2; } + dealerCode = customerInfo.DealerCode; + status = customerInfo.Status; + bookingId = customerInfo.BookingId; + cCTransactionId = customerInfo.CCTransactionId; + receiptId = customerInfo.ReceiptId; + amountPaid = customerInfo.AmountPaid; + if (customerInfo.IsRegisterInterestRequest || string.IsNullOrWhiteSpace(customerInfo.DealerCode) || string.IsNullOrWhiteSpace(customerInfo.ModelCode)) { enquiryClassification = "Cold"; autoModel = "No"; - customerInfo.DealerCode = string.Empty; + dealerCode = string.Empty; } else { @@ -437,22 +236,27 @@ public class MulesoftApi : IMulesoftApi } if (customerInfo.Status != "Successful") { - customerInfo.Status = string.Empty; - customerInfo.BookingId = string.Empty; - customerInfo.CCTransactionId = string.Empty; - customerInfo.ReceiptId = string.Empty; - customerInfo.AmountPaid = string.Empty; + status = string.Empty; + bookingId = string.Empty; + cCTransactionId = string.Empty; + receiptId = string.Empty; + amountPaid = string.Empty; isSuccessBooking = "False"; + isDefaultDealer = ""; + } + if(customerInfo.DealerCode==cfg.DeafaultDealerCode) + { + isDefaultDealer = "Yes"; } string pincode = customerInfo.PinCode; //default pincode value, incase pincode column is empty for the record if (string.IsNullOrEmpty(pincode)) pincode = "400070"; - string message = "{\"bu\": \"PB\", \"model_Code\": \"" + customerInfo.ModelCode + "\"," + + string message = "{\"bu\": \"" + customerInfo.BuCode + "\", \"model_Code\": \"" + customerInfo.ModelCode + "\"," + "\"color\": \"" + customerInfo.ColorCode + "\"," + "\"customer_Name\": \"" + customerInfo.CustomerName + "\"" + - ", \"location_of_the_customer\": \"\", \"dealer_Code\": \"" + customerInfo.DealerCode + "\", " + + ", \"location_of_the_customer\": \"\", \"dealer_Code\": \"" + dealerCode + "\", " + "\"mobile\": \"" + customerInfo.MobileNumber + "\"" + ", \"otp_verified\": \"true\", \"pincode\": \"" + pincode + "\"," + " \"enquiry_mode\": \"Digital\"" + @@ -460,20 +264,20 @@ public class MulesoftApi : IMulesoftApi " \"referral_URL\": \"\"" + ", \"composite_Key\": \"" + mx_Composite_Key + "\", \"enquiry_Classification\": \"" + enquiryClassification + "\"," + " \"auto_model\": \"" + autoModel + "\"" + - ", \"bu_Sub_type\": \"\", \"sitcore_Booking_ID\": \"" + customerInfo.BookingId + "\", " + - "\"booking_Status\": \"" + customerInfo.Status + "\"" + - ", \"cc_Avenue_Transaction_ID\": \"" + customerInfo.CCTransactionId + "\"," + - " \"booking_receipt_Number\": \"" + customerInfo.ReceiptId + "\"," + - " \"booking_amount_TRM\": \"" + customerInfo.AmountPaid + "\"," + + ", \"bu_Sub_type\": \"\", \"sitcore_Booking_ID\": \"" + bookingId + "\", " + + "\"booking_Status\": \"" + status + "\"" + + ", \"cc_Avenue_Transaction_ID\": \"" + cCTransactionId + "\"," + + " \"booking_receipt_Number\": \"" + receiptId + "\"," + + " \"booking_amount_TRM\": \"" + amountPaid + "\"," + " \"test_ride_date\": \"\", \"test_ride_slot\": \"\"" + ", \"test_ride_location\": \"\"," + "\"utmSource\": \"" + utmSource + "\", \"utmMedium\":\"" + utmMedium + "\"," + " \"sourceCampaign\": \"" + sourceCampaign + "\", \"utmContent\":\"" + utmContent + "\"," + - " \"consentToWhatsapp\": \"" + customerInfo.IsWhatsappOptIn + "\",\"leadPlatform\": \"" + leadPlatform + "\" }"; + " \"consentToWhatsapp\": \"" + customerInfo.IsWhatsappOptIn + "\",\"leadPlatform\": \"" + leadPlatform + "\" ,\"isDefaultDealer\": \"" + isDefaultDealer + "\"}"; - - string authToken = await MulesoftTokenApi.FetchToken(); + + string authToken = await MulesoftTokenApi.FetchToken(); if (!string.IsNullOrEmpty(authToken)) { @@ -494,16 +298,11 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("Api:- CallBookingApi:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-Api:- CallBookingApi:- " + ex.StackTrace.ToString()); } return new Response(customerInfo.BuId, 0, false, "false", "", ""); } - public async Task> GetDataForLsqPush(int buId) - { - return await Repository.GetDataForLsqPush(buId); - } - private LeadData DecryptBookingApi(HttpResponseMessage response) { LeadData _leadData = new LeadData(); @@ -532,7 +331,7 @@ public class MulesoftApi : IMulesoftApi { _leadData.ApiResponse = AESEncryption.DecryptString(encResult2, pass); - _logger.LogInformation("DecryptBookingApi decrpted message: " + _leadData.ApiResponse); + _logger.LogInformation($"DS Api:-DecryptBookingApi decrpted message: " + _leadData.ApiResponse); JObject obj1 = JObject.Parse(_leadData.ApiResponse); string lead_status_code = (string)obj1["statusCode"]; @@ -569,7 +368,7 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("Api:- DecryptBookingApi:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-Api:- DecryptBookingApi:- " + ex.StackTrace.ToString()); } return _leadData; } @@ -620,7 +419,7 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("Api:- ValidateMuleSoftResponse:- " + ex.StackTrace.ToString()); + _logger.LogError($"DS Api:-Api:- ValidateMuleSoftResponse:- " + ex.StackTrace.ToString()); } return new MulesoftResponse(buId, 0, false, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), ""); } @@ -694,7 +493,7 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("Api:- DecryptDealerDetail:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-Api:- DecryptDealerDetail:- " + ex.Message.ToString()); } return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), ""); } @@ -715,8 +514,37 @@ public class MulesoftApi : IMulesoftApi } catch (Exception ex) { - _logger.LogError("Api:- GetUTMDetails:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:- GetUTMDetails:- " + ex.Message.ToString()); } return ""; } + + private async Task UpdateDetails(MulesoftCustomerInfoDto customerInfo, DealerSelectionJobStatus jobStatus) + { + try + { + + CustomerDetailRepo.CustomerDealerInfoRequestDto dto = new() + { + BuId = customerInfo.BuId, + RecordId = customerInfo.RecordId, + MobileNumber = customerInfo.MobileNumber, + DealerName = jobStatus == DealerSelectionJobStatus.Complete ? customerInfo.DealerName : "", + DealerCode = jobStatus == DealerSelectionJobStatus.Complete ? customerInfo.DealerCode : "", + DealerSelectionJobStatus = jobStatus == DealerSelectionJobStatus.Complete ? DealerSelectionJobStatus.Complete : DealerSelectionJobStatus.ReadyForJob, + PinCode = customerInfo.PinCode, + Latitude = customerInfo.CustomerLat, + Longitude = customerInfo.CustomerLong, + DealerSelectedMode = customerInfo.DealerSelectedMode + }; + await CustomerDetailRepository.UpdateDealerDetail(dto); + } + catch (Exception ex) + { + _logger.LogError($"DS Api:- UpdateDetails:- " + ex.Message.ToString()); + } + } + + + #endregion } \ No newline at end of file diff --git a/Source/DealerSelection.Api/MulesoftTokenApi.cs b/Source/DealerSelection.Api/MulesoftTokenApi.cs index 2ca5a04..0d15b4f 100644 --- a/Source/DealerSelection.Api/MulesoftTokenApi.cs +++ b/Source/DealerSelection.Api/MulesoftTokenApi.cs @@ -46,13 +46,13 @@ public class MulesoftTokenApi : IMulesoftTokenApi token = tokenmodel.Value; - _logger.LogInformation("MulesoftTokenApi at FetchToken - token Generated Successfully :- " + DateTime.Now); + _logger.LogInformation($"DS Api:-MulesoftTokenApi at FetchToken - token Generated Successfully :- " + DateTime.Now); } } } catch (Exception ex) { - _logger.LogError("MulesoftTokenApi Api:- FetchToken:- " + ex.Message.ToString()); + _logger.LogError($"DS Api:-MulesoftTokenApi Api:- FetchToken:- " + ex.Message.ToString()); } return token; } @@ -61,7 +61,7 @@ public class MulesoftTokenApi : IMulesoftTokenApi { // get api implementation happens here // returns a token model - _logger.LogInformation("MulesoftTokenApi at GetTokenFromApi Started :- " + DateTime.Now); + _logger.LogInformation($"DS Api:-MulesoftTokenApi at GetTokenFromApi Started :- " + DateTime.Now); MulesoftToken token = await MuleSoftIntegration.generateToken(ClientHandler); return token; } diff --git a/Source/DealerSelection.Api/YellowAIApi.cs b/Source/DealerSelection.Api/YellowAIApi.cs index c47c0c7..251ccd7 100644 --- a/Source/DealerSelection.Api/YellowAIApi.cs +++ b/Source/DealerSelection.Api/YellowAIApi.cs @@ -1,67 +1,83 @@ -using DealerSelection.Api.Infrastructure.CustomerDetail; +using CustomerDetailRepo = DealerSelection.Api.Infrastructure.CustomerDetail; +using DealerSelection.Api.Infrastructure.YellowAI; using DealerSelection.Api.Interface; using DealerSelection.Api.Models; using DealerSelection.Common.Exceptions; using Microsoft.Extensions.Logging; using System.Text.RegularExpressions; +using MulesoftRepo = DealerSelection.Api.Infrastructure.Mulesoft; +using static iTextSharp.text.pdf.AcroFields; +using DealerSelection.Api.Models.Enum; namespace DealerSelection.Api; public class YellowAIApi : IYellowAIApi { private readonly ILogger _logger; - private IRepository CustomerDetailRepository { get; } - - public YellowAIApi(IRepository customerRepo, ILogger logger) + private CustomerDetailRepo.IRepository CustomerDetailRepository { get; } + private IRepository Repository { get; } + private IMulesoftApi MulesoftApi { get; } + public YellowAIApi(CustomerDetailRepo.IRepository customerRepo, ILogger logger, IMulesoftApi mulesoftApi, IRepository repository) { CustomerDetailRepository = customerRepo; _logger = logger; + MulesoftApi = mulesoftApi; + Repository = repository; } - + public async Task UpdateSelectedDealer(CustomerDealerInfoRequest request) { - if (IsValidData(request.MobileNumber, request.DealerCode, request.DealerName)) + try { - var isDuplicate = await IsDuplicateMobileNumber(request.MobileNumber); - if (!isDuplicate) + if (IsValidData(request.MobileNumber, request.DealerCode, request.DealerName)) { - - //Push to LSQ then make it complete - - - - // - CustomerDealerInfoRequestDto dto = new CustomerDealerInfoRequestDto + CustomerDetailRepo.CustomerDto customerinfo = await GetCustomerDetailByBuCode(request.MobileNumber, request.BuCode, request.BuSubType); + if (customerinfo != null) { - BuId = request.BuId, - RecordId = request.RecordId, - MobileNumber = request.MobileNumber, - ModelCode = request.ModelCode, - ModelName = request.ModelName, - ModelVariant = request.ModelVariant, - DealerName = request.DealerName, - DealerCode = request.DealerCode, - PinCode = request.PinCode, - Latitude = request.Latitude, - Longitude = request.Longitude, - DealerSelectionJobStatus = DealerSelectionJobStatus.Complete //Marking JobStatus Complete once we receive response from Yellow API - }; - await CustomerDetailRepository.UpdateDealerDetail(dto); + MulesoftRepo.MulesoftCustomerInfoDto customerDetailInfo = await CustomerDetailRepository.GetCustomerData(customerinfo.BuId, customerinfo.RecordId); + + customerDetailInfo.DealerCode = request.DealerCode; + customerDetailInfo.DealerName = request.DealerName; + customerDetailInfo.PinCode = request.PinCode; + customerDetailInfo.CustomerLat = request.Latitude; + customerDetailInfo.CustomerLong = request.Longitude; + customerDetailInfo.DealerSelectedMode = DealerSelectedMode.Bot.ToString(); + await MulesoftApi.InsertLSQData(customerDetailInfo); + } } else - _logger.LogWarning($"Duplicate MobileNumber exist. Data Details: {request.RequestDetail()}."); + { + _logger.LogWarning($"Invalid data. Data Details: {request.RequestDetail()}."); + throw new ValidationException("Invalid data."); + } } - else + catch(Exception ex) { - _logger.LogWarning($"Invalid data. Data Details: {request.RequestDetail()}."); - throw new ValidationException("Invalid data."); + _logger.LogError($"Some error occured: {ex.StackTrace}."); + throw new ValidationException($"Some error occured: {ex.StackTrace}."); + } } - private static bool IsValidData(int mobileNumber, string dealerCode, string dealerName) + public async Task GetModelDetails(string mobileNumber, string buCode, string buSubType) { - bool valid = Regex.IsMatch(mobileNumber.ToString(), @"^[0-9]{10}$"); + ModelDetailDto dto = await Repository.GetModelDetails(mobileNumber, buCode, buSubType); + ModelDetail response = null; + if (dto !=null) + { + response = new ModelDetail(dto.ModelCode); + + } + + return response; + } + + #region Private Member + + private static bool IsValidData(string mobileNumber, string dealerCode, string dealerName) + { + bool valid = Regex.IsMatch(mobileNumber, @"^[0-9]{10}$"); if (valid && string.IsNullOrWhiteSpace(dealerCode) && string.IsNullOrWhiteSpace(dealerName)) valid = false; @@ -69,9 +85,14 @@ public class YellowAIApi : IYellowAIApi return valid; } - private async Task IsDuplicateMobileNumber(int mobileNumber) + private async Task GetCustomerDetailByBuCode(string mobileNumber, string buCode,string buSubType) { - return await CustomerDetailRepository.IsDuplicateMobileNumber(mobileNumber); + return await CustomerDetailRepository.GetCustomerDetailByBuCode(mobileNumber, buCode, buSubType); } + #endregion + + + + } \ No newline at end of file diff --git a/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs b/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs index e94a58b..23b9ae0 100644 --- a/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs +++ b/Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs @@ -150,7 +150,9 @@ public abstract class StartupBase { audiences.Add(audience); } - builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => + if (Configuration.ConfigurationHelper.GetSetting("ValidateAudience", true) == "True") + { + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { @@ -163,6 +165,23 @@ public abstract class StartupBase IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; }); + } + else + { + builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = false, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = builder.Configuration["Jwt:Issuer"], + ValidAudiences = new List(audiences), + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) + }; + }); + } } private void SetupSwaggerOptions(WebApplicationBuilder builder) diff --git a/Source/DealerSelection.DependencyInjection/ApiRegistry.cs b/Source/DealerSelection.DependencyInjection/ApiRegistry.cs index 96aff78..26929e7 100644 --- a/Source/DealerSelection.DependencyInjection/ApiRegistry.cs +++ b/Source/DealerSelection.DependencyInjection/ApiRegistry.cs @@ -27,9 +27,18 @@ public class ApiRegistry : ServiceRegistry For() .Use() .Singleton(); + For() .Use() .Singleton(); + For() + .Use() + .Singleton(); + + For() + .Use() + .Singleton(); + } } diff --git a/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs b/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs index 8b8b1d2..43eb1a4 100644 --- a/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs +++ b/Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs @@ -1,10 +1,11 @@ using Lamar; -using InfoBipRepo = DealerSelection.Api.Infrastructure.InfoBip; +using YellowAIRepo = DealerSelection.Api.Infrastructure.YellowAI; using MulesoftRepo = DealerSelection.Api.Infrastructure.Mulesoft; using AssignDealerRepo = DealerSelection.Api.Infrastructure.AssignDealer; using Customerdetail = DealerSelection.Api.Infrastructure.CustomerDetail; using JwtRepo = DealerSelection.Api.Infrastructure.Jwt; +using CCAvenue = DealerSelection.Api.Infrastructure.CCAvenue; namespace DealerSelection.DependencyInjection; public class InfrastructureRegistry : ServiceRegistry @@ -22,7 +23,7 @@ public class InfrastructureRegistry : ServiceRegistry .Ctor().Is("BOOKING") .Transient(); - For() + For() .Use() .Ctor().Is("BOOKING") .Transient(); @@ -32,6 +33,16 @@ public class InfrastructureRegistry : ServiceRegistry .Ctor().Is("BOOKING") .Transient(); + For() + .Use() + .Ctor().Is("BOOKING") + .Transient(); + + For() + .Use() + .Ctor().Is("BOOKING") + .Transient(); + } } diff --git a/Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs b/Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs index 7dd09ab..49008fd 100644 --- a/Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs +++ b/Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs @@ -1,7 +1,7 @@  namespace DealerSelection.Api.Infrastructure.AssignDealer; -public interface IAssignDealerRepository +public interface IRepository { } \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/AssignDealer/Repository.cs b/Source/DealerSelection.Infrastructure/AssignDealer/Repository.cs index abff6b9..f6e5356 100644 --- a/Source/DealerSelection.Infrastructure/AssignDealer/Repository.cs +++ b/Source/DealerSelection.Infrastructure/AssignDealer/Repository.cs @@ -6,7 +6,7 @@ using System.Data; using System.Data.SqlClient; namespace DealerSelection.Api.Infrastructure.AssignDealer; -public class Repository : RepositoryBaseDapperAsync, IAssignDealerRepository +public class Repository : RepositoryBaseDapperAsync, IRepository { private readonly ILogger _logger; public Repository(string cxnName, ILogger logger) : base(cxnName) diff --git a/Source/DealerSelection.Infrastructure/BatchJob/IRepository.cs b/Source/DealerSelection.Infrastructure/BatchJob/IRepository.cs new file mode 100644 index 0000000..4c37b6a --- /dev/null +++ b/Source/DealerSelection.Infrastructure/BatchJob/IRepository.cs @@ -0,0 +1,9 @@ + +using DealerSelection.Api.Infrastructure.Mulesoft; + +namespace DealerSelection.Api.Infrastructure.BatchJob; + +public interface IRepository +{ + Task> Get24HrOldRecordsForJobProcessing(); +} \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/BatchJob/Repository.cs b/Source/DealerSelection.Infrastructure/BatchJob/Repository.cs new file mode 100644 index 0000000..822e044 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/BatchJob/Repository.cs @@ -0,0 +1,37 @@ +using Dapper; +using DealerSelection.Api.Infrastructure.Mulesoft; +using DealerSelection.Api.Models; +using DealerSelection.Common.Data.Dapper; +using Microsoft.Extensions.Logging; +using System.Data; +using System.Data.SqlClient; + +namespace DealerSelection.Api.Infrastructure.BatchJob; + +public class Repository : RepositoryBaseDapperAsync, IRepository +{ + private readonly ILogger _logger; + public Repository(string cxnName, ILogger logger) : base(cxnName) + { + _logger = logger; + } + + public async Task> Get24HrOldRecordsForJobProcessing() + { + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.Get24HrOldRecordsForJobProcessing, + commandType: CommandType.StoredProcedure); + return cusotmerInfo.ToList(); + } + } + catch (Exception ex) + { + _logger.LogError($"DS Repo:-Error at Repository:BatchJob in Get24HrOldRecordsForJobProcessing.", ex.StackTrace); + throw new UnexpectedDataException("Error at Repository:BatchJob in Get24HrOldRecordsForJobProcessing.", ex); + } + } + +} \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/CCAvenue/Dto.cs b/Source/DealerSelection.Infrastructure/CCAvenue/Dto.cs new file mode 100644 index 0000000..8e7f957 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/CCAvenue/Dto.cs @@ -0,0 +1,16 @@ + +namespace DealerSelection.Api.Infrastructure.CCAvenue; + +public class Dto +{ + public int BuId { get; set; } + public int RecordId { get; set; } + public string AmountPaid { get; set; } + + + + public string RequestDetail() + { + return $"BuId: {BuId}, RecordId: {RecordId}"; + } +} diff --git a/Source/DealerSelection.Infrastructure/CCAvenue/IRepository.cs b/Source/DealerSelection.Infrastructure/CCAvenue/IRepository.cs new file mode 100644 index 0000000..1265a39 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/CCAvenue/IRepository.cs @@ -0,0 +1,8 @@ +using DealerSelection.Api.Models; + +namespace DealerSelection.Api.Infrastructure.CCAvenue; +public interface IRepository +{ + Task GetBookingDetail(string bookingId, string transactionId); + Task UpdateRefundStatus(int buId,string bookingId, string transactionId,string refundReferenceNo, RefundStatusResponse refundStatusResponse); +} \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/CCAvenue/Repository.cs b/Source/DealerSelection.Infrastructure/CCAvenue/Repository.cs new file mode 100644 index 0000000..8275182 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/CCAvenue/Repository.cs @@ -0,0 +1,74 @@ +using DealerSelection.Api.Models; +using DealerSelection.Common.Data.Dapper; +using Dapper; +using System.Data; +using System.Data.SqlClient; +using Microsoft.Extensions.Logging; +using DealerSelection.Api.Infrastructure.CCAvenue; +using DealerSelection.Api.Models.Enum; + +namespace DealerSelection.Api.Infrastructure.CCAvenue; + +public class Repository : RepositoryBaseDapperAsync, IRepository +{ + private readonly ILogger _logger; + public Repository(string cxnName, ILogger logger) : base(cxnName) + { + _logger = logger; + } + + public async Task GetBookingDetail(string bookingId,string transactionId) + { + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.GetBokingDetailOnBookingId, + new + { + bookingId, + transactionId + }, + commandType: CommandType.StoredProcedure); + return cusotmerInfo.ToList().FirstOrDefault(); + } + } + catch (Exception ex) + { + _logger.LogError($"DS Repo:-BookingId:- " + bookingId.ToString() + " Error at Repository:CCAvenueRefund in GetPendingOrderStatusList " + ex.Message.ToString()); + throw new UnexpectedDataException($"Error at Repository:PendingStatusUpdate in CCAvenueRefund for BookingId: {bookingId}.", ex); + } + + } + + public async Task UpdateRefundStatus(int BuId,string bookingId, string transactionId, string refundReferenceNo, RefundStatusResponse request) + { + string failreason = request.error_code + ' ' + request.reason; + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + await cxn.QueryAsync(Procedure.UpdateRefundStatus, + new + { + BuId, + bookingId, + CCTransactionId=transactionId, + RefundReferenceNo=refundReferenceNo, + CCTransactionStatus = request.refund_status == 0 ? CCAvenueTransactionStatus.Refunded.ToString() : CCAvenueTransactionStatus.RefundFailed.ToString(), + CCTransactionStatusReason = failreason + }, + commandType: CommandType.StoredProcedure); + + } + } + catch (Exception ex) + { + _logger.LogError($"DS Repo:-BookingId:-{bookingId}, TransactionId: {transactionId} Error at Repository:CCAvenue in UpdateRefundStatus" + ex.StackTrace); + } + + } + + + +} \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerDto.cs b/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerDto.cs new file mode 100644 index 0000000..ab36064 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerDto.cs @@ -0,0 +1,14 @@ + +namespace DealerSelection.Api.Infrastructure.CustomerDetail; + +public class CustomerDto +{ + public int BuId { get; set; } + public int RecordId { get; set; } + + + public string RequestDetail() + { + return $"BuId: {BuId}, RecordId: {RecordId}"; + } +} diff --git a/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerInfoDto.cs b/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerInfoDto.cs index a45e7c7..be3fc94 100644 --- a/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerInfoDto.cs +++ b/Source/DealerSelection.Infrastructure/CustomerDetail/CustomerInfoDto.cs @@ -1,4 +1,4 @@ -using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; namespace DealerSelection.Api.Infrastructure.CustomerDetail; @@ -6,7 +6,7 @@ public class CustomerDealerInfoRequestDto { public int BuId { get; set; } public int RecordId { get; set; } - public int MobileNumber { get; set; } + public string MobileNumber { get; set; } public string ModelCode { get; set; } public string ModelName { get; set; } public string ModelVariant { get; set; } @@ -16,6 +16,7 @@ public class CustomerDealerInfoRequestDto public string Latitude { get; set; } public string Longitude { get; set; } public DealerSelectionJobStatus DealerSelectionJobStatus { get; set; } + public string DealerSelectedMode { get; set; } public string RequestDetail() { diff --git a/Source/DealerSelection.Infrastructure/CustomerDetail/IRepository.cs b/Source/DealerSelection.Infrastructure/CustomerDetail/IRepository.cs index 0abd3cd..c3bfa59 100644 --- a/Source/DealerSelection.Infrastructure/CustomerDetail/IRepository.cs +++ b/Source/DealerSelection.Infrastructure/CustomerDetail/IRepository.cs @@ -1,13 +1,14 @@ using DealerSelection.Api.Infrastructure.Mulesoft; -using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; namespace DealerSelection.Api.Infrastructure.CustomerDetail; public interface IRepository { - Task UpdateDealerDetail(CustomerDealerInfoRequestDto customerInfo); + Task UpdateDealerDetail(CustomerDealerInfoRequestDto customerInfo); // Task GetCustomerData(); Task GetCustomerData(int buid, int recordId); - Task IsDuplicateMobileNumber(int mobileNumber); - Task UpdateDealerSelectionJobStatus(int buId, int recordId, int mobileNumber, DealerSelectionJobStatus dealerSelectionJobStatus); + Task IsDuplicateMobileNumber(int mobileNumber, string buName); + Task GetCustomerDetailByBuCode(string mobileNumber, string buName, string buSubType); + Task UpdateDealerSelectionJobStatus(int buId, int recordId, DealerSelectionJobStatus dealerSelectionJobStatus); } \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs b/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs index 8196f16..c6c70b9 100644 --- a/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs +++ b/Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs @@ -1,6 +1,7 @@ using Dapper; using DealerSelection.Api.Infrastructure.Mulesoft; using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; using DealerSelection.Common.Data.Dapper; using DealerSelection.Common.Exceptions; using Microsoft.Extensions.Logging; @@ -18,98 +19,130 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } - public async Task UpdateDealerDetail(CustomerDealerInfoRequestDto dto) + public async Task UpdateDealerDetail(CustomerDealerInfoRequestDto dto) { try { using (SqlConnection cxn = await OpenCxnAsync()) { - int receivedBookingId = await cxn.ExecuteScalarAsync(Procedure.UpdateDealerDetails, + await cxn.ExecuteScalarAsync(Procedure.UpdateDealerDetails, new { dto.BuId, dto.RecordId, - dto.MobileNumber, - dto.ModelCode, - dto.ModelName, - dto.ModelVariant, + dto.MobileNumber, dto.DealerName, dto.DealerCode, dto.PinCode, - dto.Latitude, - dto.Longitude, - dto.DealerSelectionJobStatus + CustomerLat= dto.Latitude, + CustomerLong=dto.Longitude, + dto.DealerSelectionJobStatus, + dto.DealerSelectedMode }, - commandType: CommandType.StoredProcedure); - return receivedBookingId; + commandType: CommandType.StoredProcedure); } } catch (Exception ex) { - _logger.LogError($"BU:- {dto.BuId}. Error at Repository:CustomerDetail in UpdateDealerDetail for Request: {dto.RequestDetail()}.", ex.StackTrace); + _logger.LogError($"DS Repo:- BU:- {dto.BuId}. Error at Repository:CustomerDetail in UpdateDealerDetail for Request: {dto.RequestDetail()}.", ex.StackTrace); throw new UnexpectedDataException($"Error at Repository:CustomerDetail in UpdateDealerDetail for Request: {dto.RequestDetail()}.", ex); } } public async Task GetCustomerData(int buId, int recordId) { + _logger.LogInformation($"DS Repo:- GetCustomerData strated"); try { using (SqlConnection cxn = await OpenCxnAsync()) { IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.GetCustomerDataForJob, + new + { + buId, + recordId + + }, commandType: CommandType.StoredProcedure); return cusotmerInfo.ToList().FirstOrDefault(); } } catch (Exception ex) { - _logger.LogError("Error at Repository:CustomerDetail in UpdateDealerDetail for Request: {customerInfo.RequestDetail()}.", ex.StackTrace); - throw new UnexpectedDataException($"Error at Repository:CustomerDetail in UpdateDealerDetail for Request: ", ex); + _logger.LogError($"DS Repo :- Error at Repository:CustomerDetail in GetCustomerData for buId: {buId}.", ex.StackTrace); + throw new UnexpectedDataException($"Error at Repository:CustomerDetail in GetCustomerData for Request: ", ex); } } - public async Task IsDuplicateMobileNumber(int mobileNumber) + public async Task IsDuplicateMobileNumber(int mobileNumber, string buName) { try { using (SqlConnection cxn = await OpenCxnAsync()) { - bool isDuplicate = await cxn.QueryFirstAsync(Procedure.IsDuplicateMobileNumber, + IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.IsDuplicateMobileNumber, new { + buName, mobileNumber }, commandType: CommandType.StoredProcedure); - return isDuplicate; + return cusotmerInfo.ToList().FirstOrDefault(); + } + } + catch (Exception ex) + { + _logger.LogError($"DS Repo:- Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}. ErrorMessage", ex.StackTrace); + throw new DuplicateException($"Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}."); + } + } + + public async Task GetCustomerDetailByBuCode(string mobileNumber, string buCode, string buSubType) + { + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.GetCustomerDetailByBuCode, + new + { + buCode, + mobileNumber, + buSubType, + @DealerSelectionJobStatus=DealerSelectionJobStatus.SentToBot + }, + commandType: CommandType.StoredProcedure); + return cusotmerInfo.ToList().FirstOrDefault(); } } catch (Exception ex) { - _logger.LogError($"Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}. ErrorMessage", ex.StackTrace); + _logger.LogError($"DS Repo:- Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}. ErrorMessage", ex.StackTrace); throw new DuplicateException($"Error at Repository:CustomerDetail in IsDuplicateMobileNumber for MobileNumber: {mobileNumber}."); } } - public async Task UpdateDealerSelectionJobStatus(int buId, int recordId, int mobileNumber, DealerSelectionJobStatus dealerSelectionJobStatus) + public async Task UpdateDealerSelectionJobStatus(int buId, int recordId, DealerSelectionJobStatus dealerSelectionJobStatus) { try { using (SqlConnection cxn = await OpenCxnAsync()) { - await cxn.QueryFirstAsync(Procedure.UpdateDealerSelectionJobStatus, + await cxn.ExecuteScalarAsync(Procedure.UpdateDealerSelectionJobStatus, new { - buId, recordId, mobileNumber, dealerSelectionJobStatus + buId, + recordId, + dealerSelectionJobStatus }, commandType: CommandType.StoredProcedure); } } catch (Exception ex) { - _logger.LogError($"Error at Repository:CustomerDetail in UpdateDealerSelectionJobStatus for BuId: {buId}, RecordId: {recordId}, MobileNumber: {mobileNumber}, DealerSelectionJobStatus: {dealerSelectionJobStatus}. ErrorMessage", ex.StackTrace); - throw new DuplicateException($"Error at Repository:CustomerDetail in UpdateDealerSelectionJobStatus for BuId: {buId}, RecordId: {recordId}, MobileNumber: {mobileNumber}, DealerSelectionJobStatus: {dealerSelectionJobStatus}"); + _logger.LogError($"DS Repo:- Error at Repository:CustomerDetail in UpdateDealerSelectionJobStatus for BuId: {buId}, RecordId: {recordId}, DealerSelectionJobStatus: {dealerSelectionJobStatus}. ErrorMessage", ex.StackTrace); + throw new DuplicateException($"Error at Repository:CustomerDetail in UpdateDealerSelectionJobStatus for BuId: {buId}, RecordId: {recordId}, DealerSelectionJobStatus: {dealerSelectionJobStatus}"); } } diff --git a/Source/DealerSelection.Infrastructure/InfoBip/Repository.cs b/Source/DealerSelection.Infrastructure/InfoBip/Repository.cs index 1bfb404..531be18 100644 --- a/Source/DealerSelection.Infrastructure/InfoBip/Repository.cs +++ b/Source/DealerSelection.Infrastructure/InfoBip/Repository.cs @@ -36,7 +36,7 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } catch (Exception ex) { - _logger.LogError("BU:- " + buId.ToString() + $"Error at Repository:InfoBip in SaveResponse for BuId: {buId}, Mobile: {strMobile}," + + _logger.LogError($"DS Repo:-BU:- " + buId.ToString() + $"Error at Repository:InfoBip in SaveResponse for BuId: {buId}, Mobile: {strMobile}," + $"request_name: {request_name}, api_request: {api_request}, api_response: {api_response}, error_message: {error_message}." + ex.Message.ToString()); throw new UnexpectedDataException($"Error at Repository:InfoBip in SaveResponse for BuId: {buId}, Mobile: {strMobile}," + $"request_name: {request_name}, api_request: {api_request}, api_response: {api_response}, error_message: {error_message}.", ex); diff --git a/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs b/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs index 00ca14f..adc135e 100644 --- a/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs +++ b/Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs @@ -1,12 +1,10 @@  -using System; - namespace DealerSelection.Api.Infrastructure.Mulesoft; public class MulesoftCustomerInfoDto { public int BuId { get; set; } - public string BuName { get; set; } + public string BuCode { get; set; } public int RecordId { get; set; } public string BookingId { get; set; } public string CustomerName { get; set; } @@ -25,12 +23,11 @@ public class MulesoftCustomerInfoDto public string ReceiptId { get; set; } public string AmountPaid { get; set; } public string ReferralUrl { get; set; } - public bool IsWhatsappOptIn { get; set; } public int LeadTransferred { get; set; } public string CustomerLat { get; set; } public string CustomerLong { get; set; } - + public string DealerSelectedMode { get; set; } } diff --git a/Source/DealerSelection.Infrastructure/Mulesoft/Repository.cs b/Source/DealerSelection.Infrastructure/Mulesoft/Repository.cs index 601fe7f..5e79b78 100644 --- a/Source/DealerSelection.Infrastructure/Mulesoft/Repository.cs +++ b/Source/DealerSelection.Infrastructure/Mulesoft/Repository.cs @@ -32,7 +32,7 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } catch (Exception ex) { - _logger.LogError("BU:- " + buId.ToString() + " Error at Repository:Mulesoft in GetCustomerInfo." + ex.Message.ToString()); + _logger.LogError($"DS Repo:-BU:- " + buId.ToString() + " Error at Repository:Mulesoft in GetCustomerInfo." + ex.Message.ToString()); throw new UnexpectedDataException($"Error at Repository:Mulesoft in GetCustomerInfo for BuId: {buId} and BookingId: {bookingId}.", ex); } } @@ -63,7 +63,7 @@ public class Repository : RepositoryBaseDapperAsync, IRepository catch (Exception ex) { - _logger.LogError("BU:- " + buId.ToString() + $"Error at Repository:Mulesoft in UpdateMulesoftResponse for buId: {buId}, recordId: {recordId}, " + + _logger.LogError($"DS Repo:-BU:- " + buId.ToString() + $"Error at Repository:Mulesoft in UpdateMulesoftResponse for buId: {buId}, recordId: {recordId}, " + $"leadData.Lead_transferred: {leadData.Lead_transferred}, message: {message},leadData.ApiResponse: {leadData.ApiResponse}, " + $"leadData.Prospect_id:{leadData.Prospect_id}, leadData.Opportunity_id: {leadData.Opportunity_id}, " + $"isSuccessBooking: {isSuccessBooking} " + ex.Message.ToString()); @@ -104,7 +104,7 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } catch (Exception ex) { - _logger.LogError("BU:- " + dto.BuId.ToString() + " Error at Repository:Mulesoft in InsertAndUpdateDealerRecord for InfoBip Request: {dto.RequestDetail()}" + ex.Message.ToString()); + _logger.LogError($"DS Repo:-BU:- " + dto.BuId.ToString() + " Error at Repository:Mulesoft in InsertAndUpdateDealerRecord for InfoBip Request: {dto.RequestDetail()}" + ex.Message.ToString()); throw new UnexpectedDataException($"Error at Repository:Mulesoft in InsertAndUpdateDealerRecord for InfoBip Request: {dto.RequestDetail()}", ex); } } @@ -126,7 +126,7 @@ public class Repository : RepositoryBaseDapperAsync, IRepository } catch (Exception ex) { - _logger.LogError("BU:- " + buId.ToString() + "Error at Repository:Mulesoft in GetDataForLsqPush " + ex.Message.ToString()); + _logger.LogError($"DS Repo-BU:- " + buId.ToString() + "Error at Repository:Mulesoft in GetDataForLsqPush " + ex.Message.ToString()); throw new UnexpectedDataException($"Error at Repository:Mulesoft in GetDataForLsqPush for BuId: {buId}.", ex); } diff --git a/Source/DealerSelection.Infrastructure/YellowAI/IRepository.cs b/Source/DealerSelection.Infrastructure/YellowAI/IRepository.cs new file mode 100644 index 0000000..67746b7 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/YellowAI/IRepository.cs @@ -0,0 +1,8 @@ + + +namespace DealerSelection.Api.Infrastructure.YellowAI; + +public interface IRepository +{ + Task GetModelDetails(string mobileNumber, string buName, string buSubType); +} \ No newline at end of file diff --git a/Source/DealerSelection.Infrastructure/YellowAI/ModelDetailDto.cs b/Source/DealerSelection.Infrastructure/YellowAI/ModelDetailDto.cs new file mode 100644 index 0000000..d204d4e --- /dev/null +++ b/Source/DealerSelection.Infrastructure/YellowAI/ModelDetailDto.cs @@ -0,0 +1,14 @@ + +namespace DealerSelection.Api.Infrastructure.YellowAI; + +public class ModelDetailDto +{ + public string ModelCode { get; set; } + + + + public string RequestDetail() + { + return $"ModelCode: {ModelCode}"; + } +} diff --git a/Source/DealerSelection.Infrastructure/YellowAI/Repository.cs b/Source/DealerSelection.Infrastructure/YellowAI/Repository.cs new file mode 100644 index 0000000..cf9eed7 --- /dev/null +++ b/Source/DealerSelection.Infrastructure/YellowAI/Repository.cs @@ -0,0 +1,44 @@ +using Dapper; +using DealerSelection.Api.Infrastructure.Mulesoft; +using DealerSelection.Api.Models; +using DealerSelection.Api.Models.Enum; +using DealerSelection.Common.Data.Dapper; +using Microsoft.Extensions.Logging; +using System.Data; +using System.Data.SqlClient; + +namespace DealerSelection.Api.Infrastructure.YellowAI; + +public class Repository : RepositoryBaseDapperAsync, IRepository +{ + private readonly ILogger _logger; + public Repository(string cxnName, ILogger logger) : base(cxnName) + { + _logger = logger; + } + + public async Task GetModelDetails(string mobileNumber, string buCode, string buSubType) + { + try + { + using (SqlConnection cxn = await OpenCxnAsync()) + { + IEnumerable cusotmerInfo = await cxn.QueryAsync(Procedure.GetModelDetails, + new + { + buCode, + buSubType, + mobileNumber + }, + commandType: CommandType.StoredProcedure); + return cusotmerInfo.ToList().FirstOrDefault(); + } + } + catch (Exception ex) + { + _logger.LogError($"DS Repo:Error at Repository:YellowAi in GetModelDetails for MobileNumber: {mobileNumber}, BuName: {buCode}.", ex.StackTrace); + throw new UnexpectedDataException("Error at Repository:YellowAi in GetModelDetails for MobileNumber: {mobileNumber}, BuName: {buName}.", ex); + } + } + +} \ No newline at end of file diff --git a/Source/DealerSelection.Interface/IBatchJobApi.cs b/Source/DealerSelection.Interface/IBatchJobApi.cs new file mode 100644 index 0000000..7b73db8 --- /dev/null +++ b/Source/DealerSelection.Interface/IBatchJobApi.cs @@ -0,0 +1,7 @@ +namespace DealerSelection.Api.Interface; + +public interface IBatchJobApi +{ + Task Process24HrOldRecords(); + +} \ No newline at end of file diff --git a/Source/DealerSelection.Interface/ICCAvenueApi.cs b/Source/DealerSelection.Interface/ICCAvenueApi.cs new file mode 100644 index 0000000..f5f2074 --- /dev/null +++ b/Source/DealerSelection.Interface/ICCAvenueApi.cs @@ -0,0 +1,9 @@ +using DealerSelection.Api.Models; + +namespace DealerSelection.Api.Interface; + +public interface ICCAvenueApi +{ + Task RefundOrder(string BookingId, string TransactionId); + +} \ No newline at end of file diff --git a/Source/DealerSelection.Interface/IMulesoftApi.cs b/Source/DealerSelection.Interface/IMulesoftApi.cs index e1cefd4..10af9c1 100644 --- a/Source/DealerSelection.Interface/IMulesoftApi.cs +++ b/Source/DealerSelection.Interface/IMulesoftApi.cs @@ -6,15 +6,7 @@ namespace DealerSelection.Api.Interface; public interface IMulesoftApi { Task GetDealers(int buId, string buUnit, string strlat, string strLong); - Task GetAndInsertDealerDetails(int buId, string dealerCode); - Task GetStateWisePrice(int buId, string stateCode, string itemId); - Task GetModelOnBrand(int buId, string brand); - Task CallLSQBookingApi( MulesoftCustomerInfoDto customerInfo); - Task GetCustomerInfo(int buId, string bookingId); - Task> GetDataForLsqPush (int buId); - Task GetActiveState(int buId); + Task GetAndInsertDealerDetails(int buId, string dealerCode); - Task GetActiveCity(int buId, string stateCode); - - Task ModelDetailsByItemCode(int buId, string itemId); + Task InsertLSQData(MulesoftCustomerInfoDto customerInfo); } \ No newline at end of file diff --git a/Source/DealerSelection.Interface/IYellowAIApi.cs b/Source/DealerSelection.Interface/IYellowAIApi.cs index df6082f..58214f9 100644 --- a/Source/DealerSelection.Interface/IYellowAIApi.cs +++ b/Source/DealerSelection.Interface/IYellowAIApi.cs @@ -5,6 +5,6 @@ namespace DealerSelection.Api.Interface; public interface IYellowAIApi { - Task UpdateSelectedDealer(CustomerDealerInfoRequest request); - + Task UpdateSelectedDealer(CustomerDealerInfoRequest request); + Task GetModelDetails(string mobileNumber, string buCode, string buSubType); } \ No newline at end of file diff --git a/Source/DealerSelection.WebApi.Models/CustomerInfoRequest.cs b/Source/DealerSelection.WebApi.Models/CustomerInfoRequest.cs index 277386d..7f005b7 100644 --- a/Source/DealerSelection.WebApi.Models/CustomerInfoRequest.cs +++ b/Source/DealerSelection.WebApi.Models/CustomerInfoRequest.cs @@ -3,12 +3,9 @@ namespace DealerSelection.WebApi.Models; public class CustomerDealerInfoRequest { - public int BuId { get; set; } - public int RecordId { get; set; } - public int MobileNumber { get; set; } - public string ModelCode { get; set; } - public string ModelName { get; set; } - public string ModelVariant { get; set; } + public string BuCode { get; set; } + public string BuSubType { get; set; } + public string MobileNumber { get; set; } public string DealerName { get; set; } public string DealerCode { get; set; } public string PinCode { get; set; } diff --git a/Source/DealerSelection.WebApi.Models/ModelDetail.cs b/Source/DealerSelection.WebApi.Models/ModelDetail.cs new file mode 100644 index 0000000..00fc023 --- /dev/null +++ b/Source/DealerSelection.WebApi.Models/ModelDetail.cs @@ -0,0 +1,6 @@ +namespace DealerSelection.WebApi.Models; + +public class ModelDetail +{ + public string ModelCode { get; set; } +} \ No newline at end of file diff --git a/Source/DealerSelection.WebApi.Models/ModelDetailRequest.cs b/Source/DealerSelection.WebApi.Models/ModelDetailRequest.cs new file mode 100644 index 0000000..697e490 --- /dev/null +++ b/Source/DealerSelection.WebApi.Models/ModelDetailRequest.cs @@ -0,0 +1,9 @@ + +namespace DealerSelection.WebApi.Models; + +public class ModelDetailRequest +{ + public string BuCode { get; set; } + public string BuSubType { get; set; } + public string MobileNumber { get; set; } +} diff --git a/Source/DealerSelection.WebApi.Models/RefundRequest.cs b/Source/DealerSelection.WebApi.Models/RefundRequest.cs new file mode 100644 index 0000000..a41a417 --- /dev/null +++ b/Source/DealerSelection.WebApi.Models/RefundRequest.cs @@ -0,0 +1,8 @@ + +namespace DealerSelection.WebApi.Models; + +public class RefundRequest +{ + public string bookingId { get; set; } + public string transactionId { get; set; } +} diff --git a/Source/DealerSelection.WebApi.Models/RefundResponse.cs b/Source/DealerSelection.WebApi.Models/RefundResponse.cs new file mode 100644 index 0000000..1295d21 --- /dev/null +++ b/Source/DealerSelection.WebApi.Models/RefundResponse.cs @@ -0,0 +1,13 @@ +namespace DealerSelection.WebApi.Models; + +public class RefundResponse +{ + public string status { get; set; } + public RefundStatusResponse RefundStatusResponse { get; set; } +} +public class RefundStatusResponse +{ + public int? refund_status { get; set; } + public string reason { get; set; } + public string error_code { get; set; } +} diff --git a/Source/DealerSelection.WebApi/App_Start/Mapper.cs b/Source/DealerSelection.WebApi/App_Start/Mapper.cs index 5231cd2..773848b 100644 --- a/Source/DealerSelection.WebApi/App_Start/Mapper.cs +++ b/Source/DealerSelection.WebApi/App_Start/Mapper.cs @@ -12,8 +12,11 @@ public static class MapperConfig Config = new MapperConfiguration( cfg => { + cfg.CreateMap(); cfg.CreateMap(); + cfg.CreateMap(); cfg.CreateMap(); + cfg.CreateMap(); cfg.CreateMap(); }); } @@ -28,6 +31,16 @@ public static class MapperConfig return Config.CreateMapper().Map(from); } + public static ModelDetail MapModelDetails(Api.Models.ModelDetail from) + { + return Config.CreateMapper().Map(from); + } + public static RefundResponse MapRefundResponse(Api.Models.RefundApiResponse from) + { + return Config.CreateMapper().Map(from); + } + + public static Api.Models.CustomerDealerInfoRequest MapCustomerDealerInfoRequest(CustomerDealerInfoRequest from) { return Config.CreateMapper().Map(from); diff --git a/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs b/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs new file mode 100644 index 0000000..1be8506 --- /dev/null +++ b/Source/DealerSelection.WebApi/Controllers/BatchJobController.cs @@ -0,0 +1,32 @@ +using DealerSelection.Api.Interface; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.Annotations; + +namespace DealerSelection.WebApi.Controllers; + +[ApiController] +[Route("BatchJob")] +public class BatchJobController : ControllerBase +{ + + private IBatchJobApi Api { get; } + public BatchJobController(IBatchJobApi api) + { + Api = api; + } + + /// + /// + /// + /// + [Authorize] + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [SwaggerOperation(Tags = new[] { "Process24HrOldRecords" })] + [Route("BatchJob")] + public async Task Process24HrOldRecords() + { + await Api.Process24HrOldRecords(); + } +} \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Controllers/CCAvenueController.cs b/Source/DealerSelection.WebApi/Controllers/CCAvenueController.cs new file mode 100644 index 0000000..b25c06d --- /dev/null +++ b/Source/DealerSelection.WebApi/Controllers/CCAvenueController.cs @@ -0,0 +1,35 @@ +using DealerSelection.Api.Interface; +using Model = DealerSelection.Api.Models; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.Annotations; +using DealerSelection.WebApi.Models; + +namespace DealerSelection.WebApi.Controllers; + +[ApiController] +public class CCAvenueController : ControllerBase +{ + + private ICCAvenueApi Api { get; } + public CCAvenueController(ICCAvenueApi api) + { + Api = api; + } + + /// + /// + /// + /// + [Authorize] + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [SwaggerOperation(Tags = new[] { "Cancellation" })] + [Route("cancelorder")] + public async Task RefundOrder(RefundRequest details) + { + Model.RefundApiResponse apiresponse= await Api.RefundOrder(details.bookingId, details.transactionId); + RefundResponse response = MapperConfig.MapRefundResponse(apiresponse); + return response; + } +} \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Controllers/DealerSelectionController.cs b/Source/DealerSelection.WebApi/Controllers/DealerSelectionController.cs index 9e86bba..522e55b 100644 --- a/Source/DealerSelection.WebApi/Controllers/DealerSelectionController.cs +++ b/Source/DealerSelection.WebApi/Controllers/DealerSelectionController.cs @@ -6,7 +6,6 @@ using Swashbuckle.AspNetCore.Annotations; namespace DealerSelection.WebApi.Controllers; [ApiController] -[Route("DealerSelection")] public class DealerSelectionController : ControllerBase { @@ -26,9 +25,7 @@ public class DealerSelectionController : ControllerBase [SwaggerOperation(Tags = new[] { "DealerSelection" })] [Route("DealerSelection")] public async Task AssignDealer(int buId,int recordId) - { - // return 1; - + { await Api.GetCustomerDataForJob( buId, recordId); } } \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Controllers/JWTAuthController.cs b/Source/DealerSelection.WebApi/Controllers/JWTAuthController.cs index bbdc9b1..8b5f7de 100644 --- a/Source/DealerSelection.WebApi/Controllers/JWTAuthController.cs +++ b/Source/DealerSelection.WebApi/Controllers/JWTAuthController.cs @@ -7,7 +7,7 @@ using Swashbuckle.AspNetCore.Annotations; namespace BajajAutoBooking.WebApi.Controllers { [ApiController] - [Route("JWTAuth")] + [Route("jwtauth")] public class JWTAuthController : ControllerBase { private readonly ILogger _logger; @@ -27,7 +27,7 @@ namespace BajajAutoBooking.WebApi.Controllers [AllowAnonymous] [HttpPost] [SwaggerOperation(Tags = new[] { "JWTAuth" })] - [Route("GetAuthToken")] + [Route("gettoken")] public async Task> GetAuthToken(AuthValidateModel userLogin) { string token = await Api.GenerateToken(userLogin); diff --git a/Source/DealerSelection.WebApi/Controllers/MulesoftController.cs b/Source/DealerSelection.WebApi/Controllers/MulesoftController.cs index 9ab5f87..1261ae6 100644 --- a/Source/DealerSelection.WebApi/Controllers/MulesoftController.cs +++ b/Source/DealerSelection.WebApi/Controllers/MulesoftController.cs @@ -61,27 +61,7 @@ public class MulesoftController : ControllerBase Model.MulesoftResponse responseApi = await Api.GetAndInsertDealerDetails(buId, dealerCode); return responseApi.Result; } - - - - /// - /// Call Booking API - /// - /// - /// - /// - [Authorize] - [HttpGet] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(MulesoftResponse))] - [SwaggerOperation(Tags = new[] { "Mulesoft" })] - [Route("MulesoftBookingApi")] - public async Task> CallBookingApi([Required] int buId, [Required] string bookingId) - { - MulesoftCustomerInfoDto customerInfo = await Api.GetCustomerInfo(buId, bookingId); - var responseApi = await Api.CallLSQBookingApi(customerInfo); - Response response = MapperConfig.MapResponse(responseApi); - return response; - } + } \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Controllers/YellowController.cs b/Source/DealerSelection.WebApi/Controllers/YellowController.cs index 7f541c5..667a2d4 100644 --- a/Source/DealerSelection.WebApi/Controllers/YellowController.cs +++ b/Source/DealerSelection.WebApi/Controllers/YellowController.cs @@ -3,11 +3,12 @@ using DealerSelection.WebApi.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; +using Model = DealerSelection.Api.Models; namespace DealerSelection.WebApi.Controllers; [ApiController] -[Route("YellowAI")] +[Route("")] public class YellowController : ControllerBase { @@ -18,17 +19,33 @@ public class YellowController : ControllerBase } /// - /// + /// Update Yellow AI response of Selected Dealer data in DB /// /// [Authorize] - [HttpGet] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))] + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] [SwaggerOperation(Tags = new[] { "YellowAI" })] - [Route("UpdateSelectedDealer")] + [Route("updateselecteddealer")] public async Task UpdateSelectedDealer(CustomerDealerInfoRequest customerDealerInfoRequest) { Api.Models.CustomerDealerInfoRequest request = MapperConfig.MapCustomerDealerInfoRequest(customerDealerInfoRequest); await Api.UpdateSelectedDealer(request); } + + /// + /// Get Model Code against Mobile Number and BU Code + /// + /// + [Authorize] + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [SwaggerOperation(Tags = new[] { "YellowAI" })] + [Route("getmodelcode")] + public async Task GetModelDetails(string buCode,string buSubType,string mobileNumber) + { + Model.ModelDetail apiResponse = await Api.GetModelDetails(mobileNumber, buCode,buSubType); + ModelDetail response = MapperConfig.MapModelDetails(apiResponse); + return response; + } } \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Scripts/001.AlterTable.sql b/Source/DealerSelection.WebApi/Scripts/001.AlterTable.sql new file mode 100644 index 0000000..7cb0b48 --- /dev/null +++ b/Source/DealerSelection.WebApi/Scripts/001.AlterTable.sql @@ -0,0 +1,27 @@ +ALTER TABLE [dbo].[tbl_transaction_details] + ADD RefundReferenceNo varchar(50) + + ALTER TABLE [dbo].[tbl_customer_information] + ADD DealerSelectedMode varchar(50) + + ALTER TABLE [dbo].[tbl_customer_information] + ADD DealerSelectionJobStatus int + + ALTER TABLE [dbo].[tbl_businessUnit] + ADD BuCode varchar(10) + + ALTER TABLE [dbo].[tbl_businessUnit] + ADD BuSubType varchar(10) + + UPDATE [dbo].[tbl_businessUnit] + set BuSubType='KTM' where BuId =1 + + UPDATE [dbo].[tbl_businessUnit] + set BuCode='PB' where BuId in(1,4) + + UPDATE [dbo].[tbl_businessUnit] + set BuCode='MC' where BuId =2 + + + UPDATE [dbo].[tbl_businessUnit] + set BuSubType='HUS' where BuId =4 \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Scripts/002.AddDealerSelectionSchema.sql b/Source/DealerSelection.WebApi/Scripts/002.AddDealerSelectionSchema.sql new file mode 100644 index 0000000..a64c6b5 --- /dev/null +++ b/Source/DealerSelection.WebApi/Scripts/002.AddDealerSelectionSchema.sql @@ -0,0 +1,5 @@ +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'DealerSelection') + +EXEC('CREATE SCHEMA [DealerSelection] AUTHORIZATION [dbo]') + +GO \ No newline at end of file diff --git a/Source/DealerSelection.WebApi/Scripts/003.AddStoredProcedure.sql b/Source/DealerSelection.WebApi/Scripts/003.AddStoredProcedure.sql new file mode 100644 index 0000000..b9ad51a --- /dev/null +++ b/Source/DealerSelection.WebApi/Scripts/003.AddStoredProcedure.sql @@ -0,0 +1,285 @@ +/****** Object: StoredProcedure [DealerSelection].[usp_get_24HrOldRecordsFor_jobProcessing] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE PROCEDURE [DealerSelection].[usp_get_24HrOldRecordsFor_jobProcessing] + @BuId Int +AS +BEGIN + DECLARE @BuCode AS VARCHAR(10) + SELECT @BuCode = BuCode FROM tbl_businessUnit WHERE BuId=@buId + +SELECT top 1 cust.BuId,@BuCode as BuName,trans.BookingId,ModelName,ModelCode, ColorCode,CustomerName,CustomerLat,CustomerLong, + MobileNumber,Pincode,DealerCode,cust.RecordId,ReferrerUrl as ReferralUrl,IsWhatsAppOptIn,IsRegisterInterestRequest, + UtmCustomDetails1,UtmCustomDetails2, trans.Status,trans.CCTransactionId, + trans.ReceiptId,trans.AmountPaid +FROM [tbl_customer_information] cust INNER JOIN + [tbl_transaction_details] trans ON cust.RecordId = trans.RecordId + AND cust.BuId = trans.BuId + WHERE DealerSelectionJobStatus in (0,1,2)-- ReadyForJob,Picked,SentToBot + and trans.CompletionDate < DATEADD(HOUR, -24, GETDATE()) + and trans.Status='Successful' + order by trans.CreationDate desc + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_get_BookingDetail_OnBookingId] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE PROCEDURE [DealerSelection].[usp_get_BookingDetail_OnBookingId] +( +@bookingId VARCHAR(50), +@transactionId VARCHAR(50) + ) +AS +BEGIN + +SELECT t.BuId,t.RecordId,t.AmountPaid FROM tbl_transaction_details t +where t.BookingId=@bookingId and t.CCTransactionId=@transactionId +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_get_CustomerDataForJob] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +-- ============================================= +-- Author: +-- Create Date: +-- Description: +-- ============================================= +CREATE PROCEDURE [DealerSelection].[usp_get_CustomerDataForJob] +( + @buid int, + @recordId int +) +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON + DECLARE @BuCode AS VARCHAR(10) + SELECT @BuCode = BuCode FROM tbl_businessUnit WHERE BuId=@buId + + SELECT top 1 cus.BuId,@BuCode as BuCode,trans.BookingId,ModelName,ModelCode, ColorCode,CustomerName,CustomerLat,CustomerLong, + MobileNumber,Pincode,DealerCode,cus.RecordId,ReferrerUrl as ReferralUrl,IsWhatsAppOptIn,IsRegisterInterestRequest, + UtmCustomDetails1,UtmCustomDetails2, trans.Status,trans.CCTransactionId, + trans.ReceiptId,trans.AmountPaid + FROM [dbo].[tbl_customer_information] as cus + left join tbl_transaction_details as trans on cus.RecordId=trans.RecordId +WHERE trans.RecordId=@recordId and cus.BuId =@buid and cus.RecordId=@recordId and trans.BuId=@buid +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_get_CustomerDetailByBuCode] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO + +CREATE PROCEDURE [DealerSelection].[usp_get_CustomerDetailByBuCode] +( +@BuCode VARCHAr(10), +@MobileNumber VARCHAr(50), +@BuSubType varchar(10), +@DealerSelectionJobStatus int + ) +AS +BEGIN + + SELECT c.BuId,c.RecordId FROM tbl_transaction_details T + LEFT JOIN tbl_customer_information C ON + T.RecordId = C.RecordId + WHERE T.BuId=C.BuId AND C.BuId in(select BuId from tbl_businessUnit where BuCode=@BuCode and BuSubType=@BuSubType ) + AND C.MobileNumber = @mobileNumber + AND (UPPER([CCTransactionStatus]) = 'SUCCESS' OR UPPER(CCTransactionStatus) = 'SHIPPED') + --AND c.DealerSelectionJobStatus=@dealerSelectionJobStatus + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_get_dealer_selection_for_job] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +-- ============================================= +-- Author: +-- Create Date: +-- Description: +-- ============================================= +CREATE PROCEDURE [DealerSelection].[usp_get_dealer_selection_for_job] +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON + + SELECT top 1 buid,recordid from tbl_customer_information order by RecordId desc + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_get_ModelDetails] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE PROCEDURE [DealerSelection].[usp_get_ModelDetails] +( +@buCode VARCHAR(10), +@BuSubType varchar(10), +@mobileNumber VARCHAR(12) + ) +AS +BEGIN + +SELECT c.ModelCode FROM tbl_customer_information C +LEFT JOIN tbl_businessUnit b +ON c.buId = b.buId +where c.MobileNumber=@mobileNumber and b.BuCode=@buCode and b.BuSubType=@BuSubType + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_isDuplicateMobileNumber] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO + +-- ============================================= +-- Author: +-- Create Date: +-- Description: +-- ============================================= + +CREATE PROCEDURE [DealerSelection].[usp_isDuplicateMobileNumber] +( +@buName VARCHAr(50), +@mobileNumber int, +@dealerSelectionJobStatus int + ) +AS +BEGIN + DECLARE @SucessCount INT = 0 + DECLARE @BuId INT=0 + SET @BuId=(SELECT BUID FROM tbl_businessUnit WHERE BuName=@buName) + + SELECT c.BuId,c.RecordId FROM tbl_transaction_details T + LEFT JOIN tbl_customer_information C ON + T.RecordId = C.RecordId + WHERE T.BuId=C.BuId AND C.BuId = @BuId + AND C.MobileNumber = @mobileNumber + AND (UPPER([CCTransactionStatus]) = 'SUCCESS' OR UPPER(CCTransactionStatus) = 'SHIPPED') + AND c.DealerSelectionJobStatus=@dealerSelectionJobStatus + + + --IF @SucessCount > 1 + --BEGIN + -- SELECT @SucessCount AS SucessCount + -- RETURN + --END + + --SELECT BookingId,T.CreationDate FROM tbl_transaction_details T + --LEFT JOIN tbl_customer_information C ON + --T.RecordId = C.RecordId + --WHERE T.BuId=C.BuId AND C.BuId = 1 + --AND C.MobileNumber = @mobileNumber + --AND (CCTransactionStatus IS NULL OR UPPER(CCTransactionStatus) = 'AWAITED') + --order by t.CreationDate desc + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_update_dealer_details] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE PROCEDURE [DealerSelection].[usp_update_dealer_details] +( + -- Add the parameters for the stored procedure here + @BuId INT, + @RecordId INT, + @MobileNumber varchar(12), + @DealerCode varchar(100), + @DealerName varchar(100), + @CustomerLat varchar(100), + @CustomerLong varchar(100), + @Pincode varchar(100) = '', + @DealerSelectionJobStatus INT, + @DealerSelectedMode varchar(50) +) +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON + + +UPDATE [dbo].[tbl_customer_information] + SET + [DealerCode]=@DealerCode + ,[DealerName] = @DealerName + ,[CustomerLat]=@CustomerLat + ,[CustomerLong]=@CustomerLong + ,[Pincode] = @Pincode + ,[DealerSelectionJobStatus]=@DealerSelectionJobStatus + ,[DealerSelectedMode] = @DealerSelectedMode + WHERE RecordId=@RecordId and BuId = @BuId and MobileNumber=@MobileNumber + +END +GO +/****** Object: StoredProcedure [DealerSelection].[usp_update_RefundStatus] Script Date: 1/2/2024 12:08:07 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO + CREATE PROCEDURE [DealerSelection].[usp_update_RefundStatus] + ( + -- Add the parameters for the stored procedure here + @BuId INT, + @BookingId varchar(50), + @CCTransactionId varchar(50), + @RefundReferenceNo varchar(50), + @CCTransactionStatus varchar(50), + @CCTransactionStatusReason varchar(100) + ) + AS + BEGIN + SET NOCOUNT ON + + UPDATE [dbo].[tbl_transaction_details] + SET + RefundReferenceNo=@RefundReferenceNo, + CCTransactionStatus=@CCTransactionStatus, + CCTransactionStatusReason = @CCTransactionStatusReason + WHERE BookingId=@BookingId and CCTransactionId = @CCTransactionId and BuId=@BuId + + END +GO + +/****** Object: StoredProcedure [DealerSelection].[usp_update_dealer_details] Script Date: 1/3/2024 4:01:31 PM ******/ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +CREATE or ALTER PROCEDURE [DealerSelection].[usp_update_DealerSelectionJobStatus] +( + -- Add the parameters for the stored procedure here + @BuId INT, + @RecordId INT, + @DealerSelectionJobStatus INT +) +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON + + +UPDATE [dbo].[tbl_customer_information] + SET + [DealerSelectionJobStatus]=@DealerSelectionJobStatus + WHERE RecordId=@RecordId and BuId = @BuId + +END diff --git a/Source/DealerSelection.WebApi/appsettings.json b/Source/DealerSelection.WebApi/appsettings.json index 4a6dabf..1c5b7be 100644 --- a/Source/DealerSelection.WebApi/appsettings.json +++ b/Source/DealerSelection.WebApi/appsettings.json @@ -1,10 +1,12 @@ { - "BrowseSwagger": true, + "BrowseSwagger": true, + "ValidateAudience": false, + "CCAvenueApiPayUrl": "https://apitest.ccavenue.com", "WebsiteDomain": "https://www.ktm-uat2.bajajauto.com", "aZureWorkspaceId": "4247310d-8a93-4d54-8da5-505aa28817f1", "aZureSharedKey": "Rzbo3gQ6Y/ltNuWITVkhQKnlNolNxKzXSQLWYy9BNjFvClTXOByXqxyNmoGVp2QWXZlf9eWBiew1VnNj1jb3Eg==", "aZureLogType": "ASP_CL", - "aZureApiVersion": "2016-04-01", + "aZureApiVersion": "2016-04-01", "masterSchemaId": "609ea70c-2e28-472e-bad4-bd5fab0ed5c3", "masterDealerDetailSchemaId": "419620e3-e716-488e-ac07-12b3bbcc6032", "muleSoftAPIClientID": "4153b3740b224f32a1067cc57b0e155a", @@ -35,28 +37,26 @@ "KtmCfg": { "Buid": 1, "BuCode": "PB", - "ValidateDuplicate": "false", - "ValidateDuplicateHr": 1, + "DefaultDealerCode": "test", "CCAvenueAccessCode": "AVLM05KI16AB00MLBA", "CCAvenueMerchantCode": "350479", - "CCAvenueBaseUrl": "https://www.ktm-uat2.bajajauto.com/booking-payment-confirmation", - "BookingPrice": "4499", "CCAvenueWorkingKey": "F40694C5358CF9D2826C4545D6FAE337", - "InfoBipAppilcationId": "60F6C124CF5046E4C3ABCBD6FBB1ADDF", - "InfoBipMessageId": "124F63476054C62171E6A7967C11140E", - "InfoBipFrom": "KTMIND", - "LandingPageUrl": "https://www.ktm-uat2.bajajauto.com/booking", - "WebengageEventName": "KTM Booking Status", + "WebengageEventName": "KTM Booking Dealer Status", "WebEngageLicenseCode": "~71680635", "WebEngageAuthToken": "3b5e4004-cef4-4bde-86c6-c8a9944cd846", - "WebengageApiHost": "https://api.webengage.com/v1/accounts/", - "ClientId": "ee12e3d9cb9a4dc6af3599934cc4152b", - "ClientSecret": "92a2bede7b414cb19861efa3cc3a8c0d", - "Key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", - "Audience": "https://www.ktm-uat2.bajajauto.com", - "Issuer": "https://booking-dev.bajajauto.com/", - "Role": "Admin", - "ExpireMinutes": "30" + "WebengageApiHost": "https://api.webengage.com/v1/accounts/" + }, + "BajajCfg": { + "Buid": 2, + "BuCode": "MC", + "DefaultDealerCode": "test", + "CCAvenueAccessCode": "AVNL05KI17AO76LNOA", + "CCAvenueMerchantCode": "350479", + "CCAvenueWorkingKey": "6FD791AC3A7177E9139215B32278AFDB", + "WebengageEventName": "BA - Booking Status", + "WebEngageLicenseCode": "~71680635", + "WebEngageAuthToken": "3b5e4004-cef4-4bde-86c6-c8a9944cd846", + "WebengageApiHost": "https://api.webengage.com/v1/accounts/" }, "Logging": { "LogLevel": { @@ -70,9 +70,12 @@ "AZURE_LOGGING": "InstrumentationKey=2fead737-737a-4241-9e66-dfc5391583ba;IngestionEndpoint=https://centralindia-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralindia.livediagnostics.monitor.azure.com/" }, "Jwt": { - "ExpireMinutes": "30", + "ClientId": "5ef10013c846424cbe32aaffbdc2d408", + "ClientSecret": "4ca8d784dc9d4b8db9113d04770c0a7a", "Key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", - "Issuer": "https://booking-dev.bajajauto.com/", - "Audience": "https://www.ktm-uat2.bajajauto.com/,https://www.bajaj-uat2.bajajauto.com/,https://www.triumphindia-uat2.bajajauto.com/" + "Audience": "https://www.ktm-uat2.bajajauto.com,https://apidev.bajajauto.com", + "Issuer": "https://dealerselection-dev.bajajauto.com", + "Role": "Admin", + "ExpireMinutes": "30" } } diff --git a/Source/WebJobService/Service.cs b/Source/WebJobService/Service.cs index 4bff25c..37325ba 100644 --- a/Source/WebJobService/Service.cs +++ b/Source/WebJobService/Service.cs @@ -12,14 +12,14 @@ using System.Net.Http.Headers; using DealerSelection.Common.Interfaces.HttpClient; using static System.Net.Mime.MediaTypeNames; using System.Net.Http; +using Microsoft.VisualBasic; namespace WebJobService; public class Service : RepositoryBaseDapperAsync, IService { private readonly ILogger _logger; - private IHttpClientHandler ClientHandler { get; } - private string connectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["NoDealerBooking"]); + private IHttpClientHandler ClientHandler { get; } public Service(string cxnName, IHttpClientHandler clientHandler) : base(cxnName) { //_logger = logger; @@ -28,9 +28,11 @@ public class Service : RepositoryBaseDapperAsync, IService public void Run() { - ////_logger.LogInformation($"Service Started: {DateTime.Now}."); + Console.WriteLine($"Service Started: {DateTime.Now}."); + ////_logger.LogInformation($"DS Api:-($"Service Started: {DateTime.Now}."); GetRecordToProcess().Wait(); - ////_logger.LogInformation($"Service Completed: {DateTime.Now}."); + Console.WriteLine($"Service Completed: {DateTime.Now}."); + ////_logger.LogInformation($"DS Api:-($"Service Completed: {DateTime.Now}."); } private async Task GetRecordToProcess() @@ -39,15 +41,16 @@ public class Service : RepositoryBaseDapperAsync, IService { using (SqlConnection cxn = await OpenCxnAsync()) { - IEnumerable recordsToProcess = await cxn.QueryAsync("usp_get_dealer_selection_for_job", + IEnumerable recordsToProcess = await cxn.QueryAsync("DealerSelection.usp_get_dealer_selection_for_job", commandType: CommandType.StoredProcedure); var recordList = recordsToProcess.ToList(); - //_logger.LogInformation($"Records to Process: {recordList.Count}."); + Console.WriteLine($"Records to Process: {recordList.Count}."); + //_logger.LogInformation($"DS Api:-($"Records to Process: {recordList.Count}."); foreach (var item in recordList) { HitDeleareSelectionApi(item); } - //_logger.LogInformation($"Records processed sucessfully: {recordList.Count}."); + Console.WriteLine($"Records processed sucessfully: {recordList.Count}."); } } @@ -55,7 +58,6 @@ public class Service : RepositoryBaseDapperAsync, IService { throw exp; } - //sqlConnection1.Close(); } private async Task HitDeleareSelectionApi(SelectedData item) @@ -63,10 +65,7 @@ public class Service : RepositoryBaseDapperAsync, IService //item.BuId, item.RecorId string jwtToken = GenerateToken(); - string url = $"https://localhost:7122/DealerSelection/DealerSelection?buId={item.BuId}&recordId={item.RecordId}"; - //string resultJson = string.Empty; - - //string modelDetailsApi = string.Format("https://booking-preprod.bajajauto.com/DealerSelection/DealerSelection?buId=1&recordId=123"); + string url = string.Format($"https://dealerselection-dev.bajajauto.com/DealerSelection?buId={item.BuId}&recordId={item.RecordId}"); try { //using (var webClient = new WebClient { Encoding = Encoding.UTF8 }) @@ -93,15 +92,15 @@ public class Service : RepositoryBaseDapperAsync, IService //string requestJson = JsonConvert.SerializeObject(data); - - HttpClient request = ClientHandler.GetHttpClient(); + Console.WriteLine($"Deler Selection URl Request: {url}."); + HttpClient request = ClientHandler.GetHttpClient(); Uri requestUri = new (url); var httpContent = new MultipartFormDataContent(); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.DefaultRequestHeaders.Add("Authorization", "Bearer " + jwtToken); HttpResponseMessage response = request.PostAsync(url, null).Result; var contents = await response.Content.ReadAsStringAsync(); - Console.WriteLine(contents); + Console.WriteLine($"Deler Selection URl Response: {contents}"); } catch (Exception ex) { @@ -111,13 +110,13 @@ public class Service : RepositoryBaseDapperAsync, IService private string GenerateToken() { - string jwtTokenApiUrl = string.Format("{0}/JWTAuth/GetAuthToken", "https://localhost:7122"); + Console.WriteLine($"GenerateToken Started: {DateAndTime.Now}"); + string jwtTokenApiUrl = string.Format("{0}/jwtauth/gettoken", "https://dealerselection-dev.bajajauto.com"); var requestBody = new { - clientId = "ee12e3d9cb9a4dc6af3599934cc4152b", - secretId = "92a2bede7b414cb19861efa3cc3a8c0d", - buId = 1 + client_id = "5ef10013c846424cbe32aaffbdc2d408", + client_secret = "4ca8d784dc9d4b8db9113d04770c0a7a" }; string requestJson = JsonConvert.SerializeObject(requestBody); @@ -144,9 +143,12 @@ public class Service : RepositoryBaseDapperAsync, IService { jwtToken = reader.ReadToEnd(); } + Console.WriteLine($"GenerateToken End: {DateAndTime.Now} - Token :{jwtToken}"); } - catch (Exception e) + + catch (Exception ex) { + Console.WriteLine($"Exception at GenerateToken :- {ex.StackTrace}"); } return jwtToken; } diff --git a/Source/WebJobService/app.config b/Source/WebJobService/app.config index 4880127..f26b298 100644 --- a/Source/WebJobService/app.config +++ b/Source/WebJobService/app.config @@ -4,7 +4,7 @@ - + \ No newline at end of file diff --git a/Source/WebJobService/connectionString.json b/Source/WebJobService/connectionString.json index 1c239b5..f344134 100644 --- a/Source/WebJobService/connectionString.json +++ b/Source/WebJobService/connectionString.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { - "BOOKING": "user id=sqlAdmin;password=bFLW43%p40^;Data Source=mc-5f2bf602-449a-48b2-ae5a-5901-sql.database.windows.net,1433;Database=NoDealerBooking;", + "BOOKING": "user id=sqlAdmin;password=bFLW43%p40^;Data Source=mc-5f2bf602-449a-48b2-ae5a-5901-sql.database.windows.net,1433;Database=Booking;", "BAJAJ": "user id=sqlAdmin;password=bFLW43%p40^;Data Source=mc-5f2bf602-449a-48b2-ae5a-5901-sql.database.windows.net,1433;Database=bajaj;", "AZURE_LOGGING": "InstrumentationKey=2fead737-737a-4241-9e66-dfc5391583ba;IngestionEndpoint=https://centralindia-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralindia.livediagnostics.monitor.azure.com/" }