You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

722 lines
35 KiB

using DealerSelection.Api.CommonUtil;
using DealerSelection.Api.Infrastructure.Mulesoft;
using DealerSelection.Api.Interface;
using DealerSelection.Api.Models;
using DealerSelection.Common.Configuration;
using DealerSelection.Common.Interfaces.HttpClient;
using DealerSelection.Common.Logging;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
public class MulesoftApi : IMulesoftApi
{
#region MuleSoft
public static string baseApiUrl = ConfigurationHelper.GetSetting<string>("muleSoftAPIDomain", true);
public static string dealerDetailApiUrl = ConfigurationHelper.GetSetting<string>("muleSoftDealerDetail", true);
public static string bookingApiUrl = ConfigurationHelper.GetSetting<string>("muleSoftBookingAPILeadSquareDomain", true);
public static string masterSchemaId = ConfigurationHelper.GetSetting<string>("masterSchemaId", true);
public static string masterDealerDetailSchemaId = ConfigurationHelper.GetSetting<string>("masterDealerDetailSchemaId", true);
public static string muleSoftStateWisePrice = ConfigurationHelper.GetSetting<string>("muleSoftStateWisePrice", true);
public static string muleSoftBrandWiseModel = ConfigurationHelper.GetSetting<string>("muleSoftBrandWiseModel", true);
public static string muleSoftPricemasterSchemaId = ConfigurationHelper.GetSetting<string>("muleSoftStateWisePricemasterSchemaId", true);
public static string muleSoftModelmasterSchemaId = ConfigurationHelper.GetSetting<string>("muleSoftBrandWiseModelmasterSchemaId", true);
public static string muleSoftStateMasterSchemaId = ConfigurationHelper.GetSetting<string>("muleSoftStateMasterSchemaId", true);
public static string muleSoftStateMasterSchemaApi = ConfigurationHelper.GetSetting<string>("muleSoftStateMasterSchemaApi", true);
public static string muleSoftCityMasterSchemaId = ConfigurationHelper.GetSetting<string>("muleSoftCityMasterSchemaId", true);
public static string muleSoftCityMasterSchemaApi = ConfigurationHelper.GetSetting<string>("muleSoftCityMasterSchemaApi", true);
public static string muleSoftModelMasterSchemaItemId = ConfigurationHelper.GetSetting<string>("muleSoftModelMasterSchemaItemId", true);
public static string muleSoftModelMasterSchemaItemApi = ConfigurationHelper.GetSetting<string>("muleSoftModelMasterSchemaItemApi", true);
#endregion
#region Caching
public static string CacheGetDealersDetail = ConfigurationHelper.GetSetting<string>("MuleSoftCacheGetDealersDetail", true);
private int _cacheGetDealersDetail = !string.IsNullOrEmpty(CacheGetDealersDetail) ? int.Parse(CacheGetDealersDetail) : 10;
public static string CacheGetPriceOnState = ConfigurationHelper.GetSetting<string>("MuleSoftCacheGetPriceOnState", true);
private int _cacheGetPriceOnState = !string.IsNullOrEmpty(CacheGetPriceOnState) ? int.Parse(CacheGetPriceOnState) : 10;
public static string CacheGetModelOnBrand = ConfigurationHelper.GetSetting<string>("MuleSoftCacheGetModelOnBrand", true);
private int _cacheGetModelOnBrand = !string.IsNullOrEmpty(CacheGetModelOnBrand) ? int.Parse(CacheGetModelOnBrand) : 10;
public static string CacheGetActiveState = ConfigurationHelper.GetSetting<string>("MuleSoftCacheGetActiveState", true);
private int _cacheGetActiveState = !string.IsNullOrEmpty(CacheGetActiveState) ? int.Parse(CacheGetActiveState) : 10;
public static string CacheGetActiveCity = ConfigurationHelper.GetSetting<string>("MuleSoftCacheGetActiveCity", true);
private int _cacheGetActiveCity = !string.IsNullOrEmpty(CacheGetActiveCity) ? int.Parse(CacheGetActiveCity) : 10;
public static string CacheModelDetails = ConfigurationHelper.GetSetting<string>("MuleSoftCacheModelDetails", true);
private int _cacheModelDetails = !string.IsNullOrEmpty(CacheModelDetails) ? int.Parse(CacheModelDetails) : 10;
#endregion
private readonly ILogger _logger;
private IRepository Repository { get; }
private IMulesoftTokenApi MulesoftTokenApi { get; }
private IHttpClientHandler ClientHandler { get; }
private readonly IMemoryCache _memoryCache;
public MulesoftApi(IRepository repository, IMulesoftTokenApi mulesoftTokenApi,
IHttpClientHandler clientHandler, IMemoryCache memoryCache, ILogger<MulesoftApi> logger)
{
Repository = repository;
MulesoftTokenApi = mulesoftTokenApi;
ClientHandler = clientHandler;
_memoryCache = memoryCache;
_logger = logger;
}
public async Task<MulesoftResponse> GetDealers(int buId, string buUnit, string strlat, string strLong)
{
MulesoftResponse response = null;
try
{
string authToken = await MulesoftTokenApi.FetchToken();
string message = "{\"bu\": \"" + buUnit + "\", \"latitude\": " + strlat + ", \"longitude\": "
+ strLong + ", \"masterSchemaId\": \"" + masterSchemaId + "\"}";
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, baseApiUrl, authToken, encKeyToHeader);
if (response2 != null)
{
response = await ValidateMuleSoftResponse(buId, response2);
}
}
}
catch (Exception ex)
{
_logger.LogError("BU:- " + buId + "Api:- GetDealers:- " + ex.StackTrace.ToString());
}
return response;
}
public async Task<MulesoftResponse> GetAndInsertDealerDetails(int buId, string dealerCode)
{
MulesoftResponse response = null;
try
{
var cacheKey = "getDealerDetails_" + buId + dealerCode;
if (!_memoryCache.TryGetValue(cacheKey, out response))
{
AzureLogHelper.LogMessage("Api:- GetAndInsertDealerDetails:- API:- " + cacheKey);
string authToken = await MulesoftTokenApi.FetchToken();
string message = "{\"branchCode\": \"" + dealerCode +
"\",\"masterSchemaId\": \"" + masterDealerDetailSchemaId + "\"}";
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, dealerDetailApiUrl, authToken, encKeyToHeader);
response = await DecryptDealerDetail(buId, response2);
var cacheExpiryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheGetDealersDetail),
Priority = CacheItemPriority.High
};
_memoryCache.Set(cacheKey, response, cacheExpiryOptions);
}
}
_logger.LogError("Api:- GetAndInsertDealerDetails From Cache:- " + cacheKey);
}
catch (Exception ex)
{
_logger.LogError("Api:- GetAndInsertDealerDetails:- " + ex.Message.ToString());
}
return response;
}
public async Task<MulesoftResponse> GetStateWisePrice(int buId, string stateCode, string itemId)
{
MulesoftResponse response = null;
try
{
var cacheKey = "getStateWisePrice_" + buId + stateCode + itemId;
if (!_memoryCache.TryGetValue(cacheKey, out response))
{
_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);
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))
{
_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);
}
}
_logger.LogError("Api:- GetModelOnBrand From Cache:- " + cacheKey);
}
catch (Exception ex)
{
_logger.LogError("Api:- GetModelOnBrand:- " + ex.Message.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);
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)
{
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}");
try
{
if (customerInfo != null)
{
string mx_Composite_Key = string.Empty, enquiryClassification = string.Empty,
leadPlatform = "Website", autoModel = string.Empty,
bookingStatus = string.Empty, isSuccessBooking = "True";
string utmSource = GetUTMDetails(customerInfo.ReferralUrl, "utm_source");
string utmMedium = GetUTMDetails(customerInfo.ReferralUrl, "utm_medium");
string sourceCampaign = GetUTMDetails(customerInfo.ReferralUrl, "utm_campaign");
string utmContent = GetUTMDetails(customerInfo.ReferralUrl, "utm_content");
if (!string.IsNullOrEmpty(customerInfo.DealerCode))
mx_Composite_Key = customerInfo.MobileNumber + customerInfo.DealerCode + "Open";
else
mx_Composite_Key = customerInfo.MobileNumber + "nullOpen";
string mx_Source_Of_Enquiry = "Organic"; string mx_Enquiry_Sub_source = "Website";
if (!string.IsNullOrEmpty(customerInfo.UtmCustomDetails1))
{
mx_Source_Of_Enquiry = customerInfo.UtmCustomDetails1;
}
if (!string.IsNullOrEmpty(customerInfo.UtmCustomDetails2))
{
mx_Enquiry_Sub_source = customerInfo.UtmCustomDetails2;
}
if (customerInfo.IsRegisterInterestRequest || string.IsNullOrWhiteSpace(customerInfo.DealerCode) || string.IsNullOrWhiteSpace(customerInfo.ModelCode))
{
enquiryClassification = "Cold";
autoModel = "No";
customerInfo.DealerCode = string.Empty;
}
else
{
enquiryClassification = "Hot";
autoModel = "Yes";
}
if (customerInfo.Status != "Successful")
{
customerInfo.Status = string.Empty;
customerInfo.BookingId = string.Empty;
customerInfo.CCTransactionId = string.Empty;
customerInfo.ReceiptId = string.Empty;
customerInfo.AmountPaid = string.Empty;
isSuccessBooking = "False";
}
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 + "\"," +
"\"color\": \"" + customerInfo.ColorCode + "\"," +
"\"customer_Name\": \"" + customerInfo.CustomerName + "\"" +
", \"location_of_the_customer\": \"\", \"dealer_Code\": \"" + customerInfo.DealerCode + "\", " +
"\"mobile\": \"" + customerInfo.MobileNumber + "\"" +
", \"otp_verified\": \"true\", \"pincode\": \"" + pincode + "\"," +
" \"enquiry_mode\": \"Digital\"" +
", \"source\": \"" + mx_Source_Of_Enquiry + "\", \"sub_source\": \"" + mx_Enquiry_Sub_source + "\"," +
" \"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 + "\"," +
" \"test_ride_date\": \"\", \"test_ride_slot\": \"\"" +
", \"test_ride_location\": \"\"," +
"\"utmSource\": \"" + utmSource + "\", \"utmMedium\":\"" + utmMedium + "\"," +
" \"sourceCampaign\": \"" + sourceCampaign + "\", \"utmContent\":\"" + utmContent + "\"," +
" \"consentToWhatsapp\": \"" + customerInfo.IsWhatsappOptIn + "\",\"leadPlatform\": \"" + leadPlatform + "\" }";
string authToken = await MulesoftTokenApi.FetchToken();
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 url = "";
var response2 = await MuleSoftIntegration.ReturnMuleSoftResponse(ClientHandler, encstring, bookingApiUrl, authToken, encKeyToHeader);
LeadData _leadData = DecryptBookingApi(response2);
await Repository.UpdateMulesoftResponse(customerInfo.BuId, customerInfo.RecordId, customerInfo.BookingId, message, isSuccessBooking, _leadData);
return new Response(customerInfo.BuId, 0, true, "true", "", "");
}
}
}
catch (Exception ex)
{
_logger.LogError("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();
JObject obj = JObject.Parse(response.Content.ReadAsStringAsync().Result);
try
{
if (response.StatusCode.ToString() == "OK")
{
if (obj["encData"] != null && !string.IsNullOrEmpty(Convert.ToString(obj["encData"])))
{
string pass = string.Empty;
string encResult2 = Convert.ToString(obj["encData"]);
// get enckey from response header
if (response.Headers.Contains("Enckey"))
{
var decodekey = response.Headers.GetValues("Enckey").First();
if (!string.IsNullOrEmpty(decodekey))
{
var base64EncodedBytes = Convert.FromBase64String(decodekey);
pass = Encoding.UTF8.GetString(base64EncodedBytes);
}
}
// Decrypt result by encKey
if (!string.IsNullOrEmpty(encResult2))
{
_leadData.ApiResponse = AESEncryption.DecryptString(encResult2, pass);
_logger.LogInformation("DecryptBookingApi decrpted message: " + _leadData.ApiResponse);
JObject obj1 = JObject.Parse(_leadData.ApiResponse);
string lead_status_code = (string)obj1["statusCode"];
if (lead_status_code == "200" && obj1["message"]?["IsSuccess"] != null)
{
_leadData.Lead_status = (string)obj1["message"]["IsSuccess"];
_leadData.LeadResponseStatus = lead_status_code;
if (_leadData.Lead_status.ToLower().Equals("true"))
{
_leadData.Lead_transferred = "y";
string[] ids = ((string)obj1["message"]["Value"]).Split(' ');
if (ids.Length == 1)
ids = ((string)obj1["message"]["Value"]).Split(',');
if (ids.Length > 0)
_leadData.Prospect_id = ids[0];
if (ids.Length > 1)
_leadData.Opportunity_id = ids[1];
}
else
{
_leadData.Lead_transferred = "n";
}
}
}
}
}
else
{
_leadData.Lead_transferred = "n";
_leadData.Lead_status = "Failure";
_leadData.ApiResponse = ((int)response.StatusCode) + JsonConvert.SerializeObject(obj, Formatting.None);
}
}
catch (Exception ex)
{
_logger.LogError("Api:- DecryptBookingApi:- " + ex.StackTrace.ToString());
}
return _leadData;
}
private async Task<MulesoftResponse> ValidateMuleSoftResponse(int buId, HttpResponseMessage response2)
{
JObject obj = JObject.Parse(await response2.Content.ReadAsStringAsync());
try
{
if (response2.StatusCode.ToString() == "OK")
{
if (obj["encData"] != null && !string.IsNullOrWhiteSpace(Convert.ToString(obj["encData"])))
{
string pass = string.Empty;
string encResult2 = Convert.ToString(obj["encData"]);
// get enckey from response header
if (response2.Headers.Contains("encKey"))
{
var decodekey = response2.Headers.GetValues("encKey").First();
if (!string.IsNullOrEmpty(decodekey))
{
var base64EncodedBytes = Convert.FromBase64String(decodekey);
pass = Encoding.UTF8.GetString(base64EncodedBytes);
}
}
// Decrypt result by encKey
if (!string.IsNullOrWhiteSpace(encResult2))
{
string decrypted = AESEncryption.DecryptString(encResult2, pass);
JObject obj1 = JObject.Parse(decrypted);
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj1, Formatting.None), "Dealer Found", "");
}
}
}
else if (((int)response2.StatusCode) == 404)
{
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), "No Dealer Found", "");
}
else if (((int)response2.StatusCode) == 401)
{
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), Convert.ToString(obj["error"]), "");
}
else
{
return new MulesoftResponse(buId, 0, false, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), "");
}
}
catch (Exception ex)
{
_logger.LogError("Api:- ValidateMuleSoftResponse:- " + ex.StackTrace.ToString());
}
return new MulesoftResponse(buId, 0, false, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), "");
}
private async Task<MulesoftResponse> DecryptDealerDetail(int buId, HttpResponseMessage response2)
{
JObject obj = JObject.Parse(await response2.Content.ReadAsStringAsync());
try
{
if (response2.StatusCode.ToString() == "OK")
{
if (obj["encData"] != null && !string.IsNullOrWhiteSpace(Convert.ToString(obj["encData"])))
{
string pass = string.Empty;
string encResult2 = Convert.ToString(obj["encData"]);
// get enckey from response header
if (response2.Headers.Contains("encKey"))
{
var decodekey = response2.Headers.GetValues("encKey").First();
if (!string.IsNullOrEmpty(decodekey))
{
var base64EncodedBytes = Convert.FromBase64String(decodekey);
pass = Encoding.UTF8.GetString(base64EncodedBytes);
}
}
// Decrypt result by encKey
if (!string.IsNullOrWhiteSpace(encResult2))
{
string decrypted = AESEncryption.DecryptString(encResult2, pass);
JObject obj1 = JObject.Parse(decrypted);
if (obj1 != null)
{
JToken jArrResultData = (JToken)obj1["Data"];
if (jArrResultData != null)
{
DealerDetailDto dto = new DealerDetailDto();
dto.BuId = buId;
dto.DealerCode = (JValue)jArrResultData["Code"] != null ? Convert.ToString(((JValue)jArrResultData["Code"]).Value) : "0";
dto.Address1 = (JValue)jArrResultData["AddressLine1"] != null ? Convert.ToString(((JValue)jArrResultData["AddressLine1"]).Value) : "0";
dto.Address2 = (JValue)jArrResultData["AddressLine2"] != null ? Convert.ToString(((JValue)jArrResultData["AddressLine2"]).Value) : "0";
dto.City = (JValue)jArrResultData["CityName"] != null ? Convert.ToString(((JValue)jArrResultData["CityName"]).Value) : "0";
dto.State = (JValue)jArrResultData["StateName"] != null ? Convert.ToString(((JValue)jArrResultData["StateName"]).Value) : "0";
dto.Zip = (JValue)jArrResultData["Zip"] != null ? Convert.ToString(((JValue)jArrResultData["Zip"]).Value) : "0";
dto.DisplayName = (JValue)jArrResultData["DisplayName"] != null ? Convert.ToString(((JValue)jArrResultData["DisplayName"]).Value) : "0";
dto.ContactCard = (JValue)jArrResultData["ContactCard"] != null ? Convert.ToString(((JValue)jArrResultData["ContactCard"]).Value) : "0";
dto.SalesPersonMail = (JValue)jArrResultData["SalesPersonEmail"] != null ? Convert.ToString(((JValue)jArrResultData["SalesPersonEmail"]).Value) : "0";
dto.SaleMobileNumber = (JValue)jArrResultData["SalesPersonContact"] != null ? Convert.ToString(((JValue)jArrResultData["SalesPersonContact"]).Value) : "0";
dto.EcomSalesAddress = (JValue)jArrResultData["EcomSalesAddress"] != null ? Convert.ToString(((JValue)jArrResultData["EcomSalesAddress"]).Value) : "0";
await Repository.InsertAndUpdateDealerRecord(dto);
return new MulesoftResponse(buId, 0, true, dto.Zip, "Dealer Detail Updated", "");
}
}
}
}
}
else if (((int)response2.StatusCode) == 404)
{
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), "No Dealer Found", "");
}
else if (((int)response2.StatusCode) == 401)
{
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), Convert.ToString(obj["error"]), "");
}
else
{
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), "");
}
}
catch (Exception ex)
{
_logger.LogError("Api:- DecryptDealerDetail:- " + ex.Message.ToString());
}
return new MulesoftResponse(buId, 0, true, JsonConvert.SerializeObject(obj, Formatting.None), "System Down" + JsonConvert.SerializeObject(obj, Formatting.None), "");
}
private string GetUTMDetails(string referrerUrl, string utmName)
{
try
{
Uri referrerUri = new(referrerUrl);
var query = referrerUri.Query.Replace("?", "");
if (!string.IsNullOrWhiteSpace(query))
{
var dict = query.Split('&').Select(q => q.Split('=')).ToDictionary(k => k[0], v => v[1]);
if (dict.ContainsKey(utmName))
return dict[utmName];
}
}
catch (Exception ex)
{
_logger.LogError("Api:- GetUTMDetails:- " + ex.Message.ToString());
}
return "";
}
}