Browse Source

CCAvenue Integration

Release
Hema Janoti 1 year ago
parent
commit
48aa55953f
  1. 5
      Source/DealerSelection.Api.Models/AuthValidateModel.cs
  2. 28
      Source/DealerSelection.Api.Models/CustomerDealerInfoRequest.cs
  3. 10
      Source/DealerSelection.Api.Models/DealerSelectionJobStatus.cs
  4. 7
      Source/DealerSelection.Api.Models/Enum/CCAvenueTransactionStatus.cs
  5. 8
      Source/DealerSelection.Api.Models/Enum/DealerSelectedMode.cs
  6. 10
      Source/DealerSelection.Api.Models/Enum/DealerSelectionJobStatus.cs
  7. 12
      Source/DealerSelection.Api.Models/ModelDetail.cs
  8. 58
      Source/DealerSelection.Api.Models/MulesoftCustomerInfo.cs
  9. 16
      Source/DealerSelection.Api.Models/Procedure.cs
  10. 23
      Source/DealerSelection.Api.Models/RefundApiResponse.cs
  11. 31
      Source/DealerSelection.Api.Models/WebEngageEvent.cs
  12. 92
      Source/DealerSelection.Api/AssignDealerApi.cs
  13. 42
      Source/DealerSelection.Api/BatchJobApi.cs
  14. BIN
      Source/DealerSelection.Api/CCAvenue/MCPG.CCA.Util.dll
  15. 190
      Source/DealerSelection.Api/CCAvenueApi.cs
  16. 95
      Source/DealerSelection.Api/CommonUtil/CustomConfig.cs
  17. 8
      Source/DealerSelection.Api/InfoBipSmsServiceApi.cs
  18. 39
      Source/DealerSelection.Api/JwtTokenApi.cs
  19. 348
      Source/DealerSelection.Api/MulesoftApi.cs
  20. 6
      Source/DealerSelection.Api/MulesoftTokenApi.cs
  21. 95
      Source/DealerSelection.Api/YellowAIApi.cs
  22. 21
      Source/DealerSelection.Common/CommonBaseClass/StartupBase.cs
  23. 9
      Source/DealerSelection.DependencyInjection/ApiRegistry.cs
  24. 15
      Source/DealerSelection.DependencyInjection/InfrastructureRegistry.cs
  25. 2
      Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs
  26. 2
      Source/DealerSelection.Infrastructure/AssignDealer/Repository.cs
  27. 9
      Source/DealerSelection.Infrastructure/BatchJob/IRepository.cs
  28. 37
      Source/DealerSelection.Infrastructure/BatchJob/Repository.cs
  29. 16
      Source/DealerSelection.Infrastructure/CCAvenue/Dto.cs
  30. 8
      Source/DealerSelection.Infrastructure/CCAvenue/IRepository.cs
  31. 74
      Source/DealerSelection.Infrastructure/CCAvenue/Repository.cs
  32. 14
      Source/DealerSelection.Infrastructure/CustomerDetail/CustomerDto.cs
  33. 5
      Source/DealerSelection.Infrastructure/CustomerDetail/CustomerInfoDto.cs
  34. 9
      Source/DealerSelection.Infrastructure/CustomerDetail/IRepository.cs
  35. 79
      Source/DealerSelection.Infrastructure/CustomerDetail/Repository.cs
  36. 2
      Source/DealerSelection.Infrastructure/InfoBip/Repository.cs
  37. 7
      Source/DealerSelection.Infrastructure/Mulesoft/MulesoftCustomerInfoDto.cs
  38. 8
      Source/DealerSelection.Infrastructure/Mulesoft/Repository.cs
  39. 8
      Source/DealerSelection.Infrastructure/YellowAI/IRepository.cs
  40. 14
      Source/DealerSelection.Infrastructure/YellowAI/ModelDetailDto.cs
  41. 44
      Source/DealerSelection.Infrastructure/YellowAI/Repository.cs
  42. 7
      Source/DealerSelection.Interface/IBatchJobApi.cs
  43. 9
      Source/DealerSelection.Interface/ICCAvenueApi.cs
  44. 12
      Source/DealerSelection.Interface/IMulesoftApi.cs
  45. 4
      Source/DealerSelection.Interface/IYellowAIApi.cs
  46. 9
      Source/DealerSelection.WebApi.Models/CustomerInfoRequest.cs
  47. 6
      Source/DealerSelection.WebApi.Models/ModelDetail.cs
  48. 9
      Source/DealerSelection.WebApi.Models/ModelDetailRequest.cs
  49. 8
      Source/DealerSelection.WebApi.Models/RefundRequest.cs
  50. 13
      Source/DealerSelection.WebApi.Models/RefundResponse.cs
  51. 13
      Source/DealerSelection.WebApi/App_Start/Mapper.cs
  52. 32
      Source/DealerSelection.WebApi/Controllers/BatchJobController.cs
  53. 35
      Source/DealerSelection.WebApi/Controllers/CCAvenueController.cs
  54. 5
      Source/DealerSelection.WebApi/Controllers/DealerSelectionController.cs
  55. 4
      Source/DealerSelection.WebApi/Controllers/JWTAuthController.cs
  56. 22
      Source/DealerSelection.WebApi/Controllers/MulesoftController.cs
  57. 27
      Source/DealerSelection.WebApi/Controllers/YellowController.cs
  58. 27
      Source/DealerSelection.WebApi/Scripts/001.AlterTable.sql
  59. 5
      Source/DealerSelection.WebApi/Scripts/002.AddDealerSelectionSchema.sql
  60. 285
      Source/DealerSelection.WebApi/Scripts/003.AddStoredProcedure.sql
  61. 47
      Source/DealerSelection.WebApi/appsettings.json
  62. 42
      Source/WebJobService/Service.cs
  63. 2
      Source/WebJobService/app.config
  64. 2
      Source/WebJobService/connectionString.json

5
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

28
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}";
}

10
Source/DealerSelection.Api.Models/DealerSelectionJobStatus.cs

@ -1,10 +0,0 @@
namespace DealerSelection.Api.Models;
public enum DealerSelectionJobStatus
{
OldData = -1,
ReadyForJob = 0,
Picked = 1,
SentToBot = 2,
Complete = 3,
}

7
Source/DealerSelection.Api.Models/Enum/CCAvenueTransactionStatus.cs

@ -0,0 +1,7 @@
namespace DealerSelection.Api.Models.Enum;
public enum CCAvenueTransactionStatus
{
Refunded = 0,
RefundFailed = 1
}

8
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
}

10
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
}

12
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; }
}
}

58
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; }
}

16
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";
}

23
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; }
}

31
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
{

92
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<MulesoftApi> 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);
}
}

42
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<MulesoftApi> logger, IMulesoftApi mulesoftApi)
{
Repository = repository;
_logger = logger;
MulesoftApi = mulesoftApi;
}
public async Task Process24HrOldRecords()
{
try
{
List<MulesoftCustomerInfoDto> 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());
}
}
}

BIN
Source/DealerSelection.Api/CCAvenue/MCPG.CCA.Util.dll

190
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<string>("CCAvenueApiPayUrl", true);
public CCAvenueApi(ILogger<MulesoftApi> logger, IRepository repository)
{
_logger = logger;
Repository = repository;
}
public async Task<RefundApiResponse> 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<RefundStatusResponse>(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<string> 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;
}
}

95
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<string>("KtmCfg:InfoBipAppilcationId", true);
cfg.InfoBipMessageId = ConfigurationHelper.GetSetting<string>("KtmCfg:InfoBipMessageId", true);
cfg.InfoBipFroms = ConfigurationHelper.GetSetting<string>("KtmCfg:InfoBipFrom", true);
case 1:
cfg.BuCode= ConfigurationHelper.GetSetting<string>("KtmCfg:BuCode", true);
cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting<string>("KtmCfg:CCAvenueAccessCode", true);
cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting<string>("KtmCfg:CCAvenueMerchantCode", true);
cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting<string>("KtmCfg:CCAvenueBaseUrl", true);
cfg.BookingPrice = ConfigurationHelper.GetSetting<string>("KtmCfg:BookingPrice", true);
cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting<string>("KtmCfg:CCAvenueMerchantCode", true);
cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting<string>("KtmCfg:CCAvenueWorkingKey", true);
cfg.BuCode= ConfigurationHelper.GetSetting<string>("KtmCfg:BuCode", true);
cfg.WebengageLandingPageUrl= ConfigurationHelper.GetSetting<string>("KtmCfg:LandingPageUrl", true);
cfg.WebengageEventName = ConfigurationHelper.GetSetting<string>("KtmCfg:WebengageEventName", true);
cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting<string>("KtmCfg:WebEngageLicenseCode", true);
cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting<string>("KtmCfg:WebEngageAuthToken", true);
cfg.WebengageApiHost = ConfigurationHelper.GetSetting<string>("KtmCfg:WebengageApiHost", true);
cfg.ValidateDuplicate = ConfigurationHelper.GetSetting<string>("KtmCfg:ValidateDuplicate", true);
cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting<int>("KtmCfg:ValidateDuplicateHr", true);
cfg.BuId = buId;
cfg.ClientId = ConfigurationHelper.GetSetting<string>("KtmCfg:ClientId", true);
cfg.ClientSecret = ConfigurationHelper.GetSetting<string>("KtmCfg:ClientSecret", true);
cfg.Key = ConfigurationHelper.GetSetting<string>("KtmCfg:Key", true);
cfg.Audience = ConfigurationHelper.GetSetting<string>("KtmCfg:Audience", true);
cfg.Issuer = ConfigurationHelper.GetSetting<string>("KtmCfg:Issuer", true);
cfg.Role = ConfigurationHelper.GetSetting<string>("KtmCfg:Role", true);
cfg.ExpireMinutes = ConfigurationHelper.GetSetting<string>("KtmCfg:ExpireMinutes", true);
break;
case 2:
cfg.InfoBipAppilcationId = ConfigurationHelper.GetSetting<string>("BajajCfg:InfoBipAppilcationId", true);
cfg.InfoBipMessageId = ConfigurationHelper.GetSetting<string>("BajajCfg:InfoBipMessageId", true);
cfg.InfoBipFroms = ConfigurationHelper.GetSetting<string>("BajajCfg:InfoBipFrom", true);
cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting<string>("BajajCfg:CCAvenueAccessCode", true);
cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting<string>("BajajCfg:CCAvenueMerchantCode", true);
cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting<string>("BajajCfg:CCAvenueBaseUrl", true);
cfg.BookingPrice = ConfigurationHelper.GetSetting<string>("BajajCfg:BookingPrice", true);
cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting<string>("BajajCfg:CCAvenueWorkingKey", true);
cfg.BuCode = ConfigurationHelper.GetSetting<string>("BajajCfg:BuCode", true);
cfg.WebengageLandingPageUrl = ConfigurationHelper.GetSetting<string>("BajajCfg:LandingPageUrl", true);
cfg.WebengageEventName = ConfigurationHelper.GetSetting<string>("BajajCfg:WebengageEventName", true);
cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting<string>("BajajCfg:WebEngageLicenseCode", true);
cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting<string>("BajajCfg:WebEngageAuthToken", true);
cfg.WebengageApiHost = ConfigurationHelper.GetSetting<string>("BajajCfg:WebengageApiHost", true);
cfg.ValidateDuplicate = ConfigurationHelper.GetSetting<string>("BajajCfg:ValidateDuplicate", true);
cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting<int>("BajajCfg:ValidateDuplicateHr", true);
cfg.WebengageApiHost = ConfigurationHelper.GetSetting<string>("KtmCfg:WebengageApiHost", true);
cfg.BuId = buId;
cfg.ClientId = ConfigurationHelper.GetSetting<string>("BajajCfg:ClientId", true);
cfg.ClientSecret = ConfigurationHelper.GetSetting<string>("BajajCfg:ClientSecret", true);
cfg.Key = ConfigurationHelper.GetSetting<string>("BajajCfg:Key", true);
cfg.Audience = ConfigurationHelper.GetSetting<string>("BajajCfg:Audience", true);
cfg.Issuer = ConfigurationHelper.GetSetting<string>("BajajCfg:Issuer", true);
cfg.Role = ConfigurationHelper.GetSetting<string>("BajajCfg:Role", true);
cfg.ExpireMinutes = ConfigurationHelper.GetSetting<string>("BajajCfg:ExpireMinutes", true);
break;
case 3:
cfg.InfoBipAppilcationId = ConfigurationHelper.GetSetting<string>("TriumphCfg:InfoBipAppilcationId", true);
cfg.InfoBipMessageId = ConfigurationHelper.GetSetting<string>("TriumphCfg:InfoBipMessageId", true);
cfg.InfoBipFroms = ConfigurationHelper.GetSetting<string>("TriumphCfg:InfoBipFrom", true);
cfg.CCAvenueAccessCode = ConfigurationHelper.GetSetting<string>("TriumphCfg:CCAvenueAccessCode", true);
cfg.CCAvenueMerchantCode = ConfigurationHelper.GetSetting<string>("TriumphCfg:CCAvenueMerchantCode", true);
cfg.CCAvenueBaseUrl = ConfigurationHelper.GetSetting<string>("TriumphCfg:CCAvenueBaseUrl", true);
cfg.BookingPrice = ConfigurationHelper.GetSetting<string>("TriumphCfg:BookingPrice", true);
cfg.CCAvenueWorkingKey = ConfigurationHelper.GetSetting<string>("TriumphCfg:CCAvenueWorkingKey", true);
cfg.BuCode = ConfigurationHelper.GetSetting<string>("TriumphCfg:BuCode", true);
cfg.WebengageLandingPageUrl = ConfigurationHelper.GetSetting<string>("TriumphCfg:LandingPageUrl", true);
cfg.WebengageEventName = ConfigurationHelper.GetSetting<string>("TriumphCfg:WebengageEventName", true);
cfg.WebEngageLicenseCode = ConfigurationHelper.GetSetting<string>("TriumphCfg:WebEngageLicenseCode", true);
cfg.WebEngageAuthToken = ConfigurationHelper.GetSetting<string>("TriumphCfg:WebEngageAuthToken", true);
cfg.WebengageApiHost = ConfigurationHelper.GetSetting<string>("TriumphCfg:WebengageApiHost", true);
cfg.ValidateDuplicate = ConfigurationHelper.GetSetting<string>("TriumphCfg:ValidateDuplicate", true);
cfg.ValidateDuplicateHour = ConfigurationHelper.GetSetting<int>("TriumphCfg:ValidateDuplicateHr", true);
cfg.BuId = buId;
cfg.ClientId = ConfigurationHelper.GetSetting<string>("TriumphCfg:ClientId", true);
cfg.ClientSecret = ConfigurationHelper.GetSetting<string>("TriumphCfg:ClientSecret", true);
cfg.Key = ConfigurationHelper.GetSetting<string>("TriumphCfg:Key", true);
cfg.Audience = ConfigurationHelper.GetSetting<string>("TriumphCfg:Audience", true);
cfg.Issuer = ConfigurationHelper.GetSetting<string>("TriumphCfg:Issuer", true);
cfg.Role = ConfigurationHelper.GetSetting<string>("TriumphCfg:Role", true);
cfg.ExpireMinutes = ConfigurationHelper.GetSetting<string>("TriumphCfg:ExpireMinutes", true);
break;
cfg.DeafaultDealerCode = ConfigurationHelper.GetSetting<string>("KtmCfg:DefaultDealerCode", true);
//cfg.ClientId = ConfigurationHelper.GetSetting<string>("KtmCfg:ClientId", true);
//cfg.ClientSecret = ConfigurationHelper.GetSetting<string>("KtmCfg:ClientSecret", true);
// cfg.Key = ConfigurationHelper.GetSetting<string>("KtmCfg:Key", true);
// cfg.Audience = ConfigurationHelper.GetSetting<string>("KtmCfg:Audience", true);
// cfg.Issuer = ConfigurationHelper.GetSetting<string>("KtmCfg:Issuer", true);
// cfg.Role = ConfigurationHelper.GetSetting<string>("KtmCfg:Role", true);
// cfg.ExpireMinutes = ConfigurationHelper.GetSetting<string>("KtmCfg:ExpireMinutes", true);
break;
default:
cfg.InfoBipAppilcationId = "";
cfg.InfoBipMessageId = "";
cfg.InfoBipFroms = "";
cfg.BuId = buId;
cfg.BuId = buId;
break;
}
return cfg;

8
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;
}

39
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<string>("Jwt:Key", true);
public static string _expireMinutes = ConfigurationHelper.GetSetting<string>("Jwt:ExpireMinutes", true);
public static string _issuer = ConfigurationHelper.GetSetting<string>("Jwt:Issuer", true);
public static string _audience = ConfigurationHelper.GetSetting<string>("Jwt:Audience", true);
public static string _clientId = ConfigurationHelper.GetSetting<string>("Jwt:ClientId", true);
public static string _clientSecret = ConfigurationHelper.GetSetting<string>("Jwt:ClientSecret", true);
public JwtTokenApi(IJwtRepository repository, ILogger<JwtTokenApi> 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<bool> 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;
}
}

348
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<MulesoftApi> 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<MulesoftResponse> 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<MulesoftResponse> 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<MulesoftResponse> 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<MulesoftResponse> GetActiveCity(int buId, string stateCode)
private async Task<Response> 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<MulesoftResponse> 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<MulesoftCustomerInfoDto> GetCustomerInfo(int buId, string bookingId)
{
return await Repository.GetCustomerInfo(buId, bookingId);
}
public async Task<Response> 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<List<MulesoftCustomerInfoDto>> 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
}

6
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;
}

95
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<YellowAIApi> logger)
private CustomerDetailRepo.IRepository CustomerDetailRepository { get; }
private IRepository Repository { get; }
private IMulesoftApi MulesoftApi { get; }
public YellowAIApi(CustomerDetailRepo.IRepository customerRepo, ILogger<YellowAIApi> 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<ModelDetail> 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<bool> IsDuplicateMobileNumber(int mobileNumber)
private async Task<CustomerDetailRepo.CustomerDto> GetCustomerDetailByBuCode(string mobileNumber, string buCode,string buSubType)
{
return await CustomerDetailRepository.IsDuplicateMobileNumber(mobileNumber);
return await CustomerDetailRepository.GetCustomerDetailByBuCode(mobileNumber, buCode, buSubType);
}
#endregion
}

21
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<string>("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<string>(audiences),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
}
}
private void SetupSwaggerOptions(WebApplicationBuilder builder)

9
Source/DealerSelection.DependencyInjection/ApiRegistry.cs

@ -27,9 +27,18 @@ public class ApiRegistry : ServiceRegistry
For<IHttpClientHandler>()
.Use<MyHttpClientHandler>()
.Singleton();
For<IMulesoftTokenApi>()
.Use<MulesoftTokenApi>()
.Singleton();
For<ICCAvenueApi>()
.Use<CCAvenueApi>()
.Singleton();
For<IYellowAIApi>()
.Use<YellowAIApi>()
.Singleton();
}
}

15
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<string>().Is("BOOKING")
.Transient();
For<AssignDealerRepo.IAssignDealerRepository>()
For<AssignDealerRepo.IRepository>()
.Use<AssignDealerRepo.Repository>()
.Ctor<string>().Is("BOOKING")
.Transient();
@ -32,6 +33,16 @@ public class InfrastructureRegistry : ServiceRegistry
.Ctor<string>().Is("BOOKING")
.Transient();
For<CCAvenue.IRepository>()
.Use<CCAvenue.Repository>()
.Ctor<string>().Is("BOOKING")
.Transient();
For<YellowAIRepo.IRepository>()
.Use<YellowAIRepo.Repository>()
.Ctor<string>().Is("BOOKING")
.Transient();
}
}

2
Source/DealerSelection.Infrastructure/AssignDealer/IAssignDealerRepository.cs

@ -1,7 +1,7 @@

namespace DealerSelection.Api.Infrastructure.AssignDealer;
public interface IAssignDealerRepository
public interface IRepository
{
}

2
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<Repository> logger) : base(cxnName)

9
Source/DealerSelection.Infrastructure/BatchJob/IRepository.cs

@ -0,0 +1,9 @@

using DealerSelection.Api.Infrastructure.Mulesoft;
namespace DealerSelection.Api.Infrastructure.BatchJob;
public interface IRepository
{
Task<List<MulesoftCustomerInfoDto>> Get24HrOldRecordsForJobProcessing();
}

37
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<Repository> logger) : base(cxnName)
{
_logger = logger;
}
public async Task<List<MulesoftCustomerInfoDto>> Get24HrOldRecordsForJobProcessing()
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
IEnumerable<MulesoftCustomerInfoDto> cusotmerInfo = await cxn.QueryAsync<MulesoftCustomerInfoDto>(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);
}
}
}

16
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}";
}
}

8
Source/DealerSelection.Infrastructure/CCAvenue/IRepository.cs

@ -0,0 +1,8 @@
using DealerSelection.Api.Models;
namespace DealerSelection.Api.Infrastructure.CCAvenue;
public interface IRepository
{
Task<Dto> GetBookingDetail(string bookingId, string transactionId);
Task UpdateRefundStatus(int buId,string bookingId, string transactionId,string refundReferenceNo, RefundStatusResponse refundStatusResponse);
}

74
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<Repository> logger) : base(cxnName)
{
_logger = logger;
}
public async Task<Dto> GetBookingDetail(string bookingId,string transactionId)
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
IEnumerable<Dto> cusotmerInfo = await cxn.QueryAsync<Dto>(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);
}
}
}

14
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}";
}
}

5
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()
{

9
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<int> UpdateDealerDetail(CustomerDealerInfoRequestDto customerInfo);
Task UpdateDealerDetail(CustomerDealerInfoRequestDto customerInfo);
// Task<MulesoftCustomerInfoDto> GetCustomerData();
Task<MulesoftCustomerInfoDto> GetCustomerData(int buid, int recordId);
Task<bool> IsDuplicateMobileNumber(int mobileNumber);
Task UpdateDealerSelectionJobStatus(int buId, int recordId, int mobileNumber, DealerSelectionJobStatus dealerSelectionJobStatus);
Task<CustomerDto> IsDuplicateMobileNumber(int mobileNumber, string buName);
Task<CustomerDto> GetCustomerDetailByBuCode(string mobileNumber, string buName, string buSubType);
Task UpdateDealerSelectionJobStatus(int buId, int recordId, DealerSelectionJobStatus dealerSelectionJobStatus);
}

79
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<int> UpdateDealerDetail(CustomerDealerInfoRequestDto dto)
public async Task UpdateDealerDetail(CustomerDealerInfoRequestDto dto)
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
int receivedBookingId = await cxn.ExecuteScalarAsync<int>(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<MulesoftCustomerInfoDto> GetCustomerData(int buId, int recordId)
{
_logger.LogInformation($"DS Repo:- GetCustomerData strated");
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
IEnumerable<MulesoftCustomerInfoDto> cusotmerInfo = await cxn.QueryAsync<MulesoftCustomerInfoDto>(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<bool> IsDuplicateMobileNumber(int mobileNumber)
public async Task<CustomerDto> IsDuplicateMobileNumber(int mobileNumber, string buName)
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
bool isDuplicate = await cxn.QueryFirstAsync<bool>(Procedure.IsDuplicateMobileNumber,
IEnumerable<CustomerDto> cusotmerInfo = await cxn.QueryAsync<CustomerDto>(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<CustomerDto> GetCustomerDetailByBuCode(string mobileNumber, string buCode, string buSubType)
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
IEnumerable<CustomerDto> cusotmerInfo = await cxn.QueryAsync<CustomerDto>(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}");
}
}

2
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);

7
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; }
}

8
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);
}

8
Source/DealerSelection.Infrastructure/YellowAI/IRepository.cs

@ -0,0 +1,8 @@

namespace DealerSelection.Api.Infrastructure.YellowAI;
public interface IRepository
{
Task<ModelDetailDto> GetModelDetails(string mobileNumber, string buName, string buSubType);
}

14
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}";
}
}

44
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<Repository> logger) : base(cxnName)
{
_logger = logger;
}
public async Task<ModelDetailDto> GetModelDetails(string mobileNumber, string buCode, string buSubType)
{
try
{
using (SqlConnection cxn = await OpenCxnAsync())
{
IEnumerable<ModelDetailDto> cusotmerInfo = await cxn.QueryAsync<ModelDetailDto>(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);
}
}
}

7
Source/DealerSelection.Interface/IBatchJobApi.cs

@ -0,0 +1,7 @@
namespace DealerSelection.Api.Interface;
public interface IBatchJobApi
{
Task Process24HrOldRecords();
}

9
Source/DealerSelection.Interface/ICCAvenueApi.cs

@ -0,0 +1,9 @@
using DealerSelection.Api.Models;
namespace DealerSelection.Api.Interface;
public interface ICCAvenueApi
{
Task<RefundApiResponse> RefundOrder(string BookingId, string TransactionId);
}

12
Source/DealerSelection.Interface/IMulesoftApi.cs

@ -6,15 +6,7 @@ namespace DealerSelection.Api.Interface;
public interface IMulesoftApi
{
Task<MulesoftResponse> GetDealers(int buId, string buUnit, string strlat, string strLong);
Task<MulesoftResponse> GetAndInsertDealerDetails(int buId, string dealerCode);
Task<MulesoftResponse> GetStateWisePrice(int buId, string stateCode, string itemId);
Task<MulesoftResponse> GetModelOnBrand(int buId, string brand);
Task<Response> CallLSQBookingApi( MulesoftCustomerInfoDto customerInfo);
Task<MulesoftCustomerInfoDto> GetCustomerInfo(int buId, string bookingId);
Task<List<MulesoftCustomerInfoDto>> GetDataForLsqPush (int buId);
Task<MulesoftResponse> GetActiveState(int buId);
Task<MulesoftResponse> GetAndInsertDealerDetails(int buId, string dealerCode);
Task<MulesoftResponse> GetActiveCity(int buId, string stateCode);
Task<MulesoftResponse> ModelDetailsByItemCode(int buId, string itemId);
Task InsertLSQData(MulesoftCustomerInfoDto customerInfo);
}

4
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<ModelDetail> GetModelDetails(string mobileNumber, string buCode, string buSubType);
}

9
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; }

6
Source/DealerSelection.WebApi.Models/ModelDetail.cs

@ -0,0 +1,6 @@
namespace DealerSelection.WebApi.Models;
public class ModelDetail
{
public string ModelCode { get; set; }
}

9
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; }
}

8
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; }
}

13
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; }
}

13
Source/DealerSelection.WebApi/App_Start/Mapper.cs

@ -12,8 +12,11 @@ public static class MapperConfig
Config = new MapperConfiguration(
cfg =>
{
cfg.CreateMap<Api.Models.ModelDetail, ModelDetail>();
cfg.CreateMap<Api.Models.Response, Response>();
cfg.CreateMap<Api.Models.RefundApiResponse, RefundResponse>();
cfg.CreateMap<Api.Models.MulesoftResponse, MulesoftResponse>();
cfg.CreateMap<Api.Models.RefundStatusResponse, RefundStatusResponse>();
cfg.CreateMap<CustomerDealerInfoRequest, Api.Models.CustomerDealerInfoRequest>();
});
}
@ -28,6 +31,16 @@ public static class MapperConfig
return Config.CreateMapper().Map<Api.Models.MulesoftResponse, MulesoftResponse>(from);
}
public static ModelDetail MapModelDetails(Api.Models.ModelDetail from)
{
return Config.CreateMapper().Map<ModelDetail>(from);
}
public static RefundResponse MapRefundResponse(Api.Models.RefundApiResponse from)
{
return Config.CreateMapper().Map<RefundResponse>(from);
}
public static Api.Models.CustomerDealerInfoRequest MapCustomerDealerInfoRequest(CustomerDealerInfoRequest from)
{
return Config.CreateMapper().Map<CustomerDealerInfoRequest, Api.Models.CustomerDealerInfoRequest>(from);

32
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;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[Authorize]
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(Tags = new[] { "Process24HrOldRecords" })]
[Route("BatchJob")]
public async Task Process24HrOldRecords()
{
await Api.Process24HrOldRecords();
}
}

35
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;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[Authorize]
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(Tags = new[] { "Cancellation" })]
[Route("cancelorder")]
public async Task<RefundResponse> RefundOrder(RefundRequest details)
{
Model.RefundApiResponse apiresponse= await Api.RefundOrder(details.bookingId, details.transactionId);
RefundResponse response = MapperConfig.MapRefundResponse(apiresponse);
return response;
}
}

5
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);
}
}

4
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<ActionResult<string>> GetAuthToken(AuthValidateModel userLogin)
{
string token = await Api.GenerateToken(userLogin);

22
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;
}
/// <summary>
/// Call Booking API
/// </summary>
/// <param name="buId"></param>
/// <param name="bookingId"></param>
/// <returns></returns>
[Authorize]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(MulesoftResponse))]
[SwaggerOperation(Tags = new[] { "Mulesoft" })]
[Route("MulesoftBookingApi")]
public async Task<ActionResult<Response>> 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;
}
}

27
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
}
/// <summary>
///
/// Update Yellow AI response of Selected Dealer data in DB
/// </summary>
/// <returns></returns>
[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);
}
/// <summary>
/// Get Model Code against Mobile Number and BU Code
/// </summary>
/// <returns></returns>
[Authorize]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[SwaggerOperation(Tags = new[] { "YellowAI" })]
[Route("getmodelcode")]
public async Task<ModelDetail> GetModelDetails(string buCode,string buSubType,string mobileNumber)
{
Model.ModelDetail apiResponse = await Api.GetModelDetails(mobileNumber, buCode,buSubType);
ModelDetail response = MapperConfig.MapModelDetails(apiResponse);
return response;
}
}

27
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

5
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

285
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: <Author, , Name>
-- Create Date: <Create Date, , >
-- Description: <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: <Author, , Name>
-- Create Date: <Create Date, , >
-- Description: <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: <Author, , Name>
-- Create Date: <Create Date, , >
-- Description: <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

47
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"
}
}

42
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<SelectedData> recordsToProcess = await cxn.QueryAsync<SelectedData>("usp_get_dealer_selection_for_job",
IEnumerable<SelectedData> recordsToProcess = await cxn.QueryAsync<SelectedData>("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;
}

2
Source/WebJobService/app.config

@ -4,7 +4,7 @@
<!-- The format of the connection string is "DefaultEndpointsProtocol=https;AccountName=NAME;AccountKey=KEY" -->
<!-- For local execution, the value can be set either in this config file or through environment variables -->
<add name="Booking" connectionString="user id=sqlAdmin;password=bFLW43%p40^;Data Source=mc-5f2bf602-449a-48b2-ae5a-5901-sql.database.windows.net,1433;Database=NoDealerBooking;" />
<add name="Booking" connectionString="user id=sqlAdmin;password=bFLW43%p40^;Data Source=mc-5f2bf602-449a-48b2-ae5a-5901-sql.database.windows.net,1433;Database=Booking;" />
</connectionStrings>
</configuration>

2
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/"
}
Loading…
Cancel
Save