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.
 
 
 

671 lines
29 KiB

using Business.KFTCBusiness;
using Business.TPApi;
using Business.Utility;
using Common;
using Common.Helper;
using Common.Language;
using Common.Model;
using Common.Model.Config;
using Common.Model.Notification;
using Common.Model.SendMoney;
using Common.Model.TPSendMoney;
using log4net;
using Newtonsoft.Json;
using PushNotification;
using Repository.Coupon;
using Repository.Mobile;
using Repository.Reward;
using Repository.SendMoney;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Notify = Common.Model.Notification;
namespace Business.SendMoney
{
public class SendMoneyBusiness : ISendMoneyBusiness
{
private readonly ISendMoneyRepository _repo;
private readonly IKftcProcessBusiness _kftcBuss;
private readonly IRewardRepository _irewardrepo;
private readonly ICouponRepository icouponrepo;
private readonly IMobileServicesRepo _requestServices;
private readonly ThirdPartyAPI _tpApi = new ThirdPartyAPI();
private static readonly ILog Log = LogManager.GetLogger(typeof(SendMoneyBusiness));
public SendMoneyBusiness(ISendMoneyRepository repo, IKftcProcessBusiness kftcBuss, IRewardRepository irewardrepo, ICouponRepository icouponrepo, IMobileServicesRepo requestServices)
{
_repo = repo;
_kftcBuss = kftcBuss;
_irewardrepo = irewardrepo;
this.icouponrepo = icouponrepo;
_requestServices = requestServices;
}
public JsonRxResponse LoadCountryServiceDetail(CountryServiceModel request)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
jsonRx.SetResponse("1", "Error");
CountryServiceDetail res = _repo.LoadCountryServiceDetail(request);
if (res == null)
{
Log.Debug("LoadCountryServiceDetail | Returning null while fetching country service details.");
return jsonRx;
}
Log.Debug("LoadCountryServiceDetail | Calling LoadCountryServiceDetail Success...");
jsonRx.SetResponse("0", "Success");
var path = GetStatic.ReadWebConfig("ServiceType_Resource", "");
var text = File.ReadAllText(path);
List<ServiceTypeDetails> sd = JsonConvert.DeserializeObject<List<ServiceTypeDetails>>(text);
var lang = Convert.ToString(CallContext.GetData(Constants.Language));
if (string.IsNullOrEmpty(lang))
{
lang = "en";
}
var idx = sd.FindIndex(x => x.countryCode == lang);
var data = new ServiceTypeDetails();
if (idx < 0)
{
data = sd[sd.FindIndex(x => x.countryCode == "en")];
}
else
{
data = sd[idx];
}
foreach (var item in res.PayoutMode)
{
switch (item.Mode.ToLower())
{
case "cash payment":
item.ModeDescription = data.cashPayment;
break;
case "bank deposit":
item.ModeDescription = data.bankDeposit;
break;
case "mobile wallet":
item.ModeDescription = data.mobileWallet;
break;
case "home delivery":
item.ModeDescription = data.homeDelivery;
break;
case "card payment":
item.ModeDescription = data.cardPayment;
break;
}
}
jsonRx.Data = res;
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Unable to fetch the country service details.");
return jsonRx;
}
}
public JsonRxResponse LoadBankBranch(string country, string bank, string search)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
jsonRx.SetResponse("1", "Sorry, No branch found.");
List<BankBranch> res = _repo.LoadBankBranch(country, bank, search);
if (res == null)
{
Log.Debug("LoadCountryBankServiceDetail | Returning null while fetching the list of bank branches details.");
return jsonRx;
}
Log.Debug("LoadBankBranch | DB Call Success..");
jsonRx.SetResponse("0", "Success");
jsonRx.Data = res;
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Unable to fetch the list of bank branches details.");
return jsonRx;
}
}
public JsonRxResponse Calculate(ExRateCalculateRequest m)
{
JsonRxResponse response = new JsonRxResponse();
APIJsonResponse jsonResponse = new APIJsonResponse();
try
{
ExRateCalculate model = new ExRateCalculate()
{
SBranch = Convert.ToInt32(GetStatic.ReadWebConfig("sBranch", "")),
SSuperAgent = Convert.ToInt32(GetStatic.ReadWebConfig("sSuperAgent", "")),
AgentRefId = "",
CalcBy = m.calcBy,
CAmount = Convert.ToDecimal(m.cAmount == "" ? "0" : m.cAmount),
CardOnline = "",
CollCurrency = m.sCurrency,
CouponCode = m.DeviceType,
CustomerId = 0,
IsManualSc = false,
IsOnline = false,
ManualSc = 0,
PAgentId = Convert.ToInt32(m.pAgent == "" ? "0" : m.pAgent),
PAgentName = "",
PAmount = Convert.ToDecimal(m.pAmount == "" ? "0" : m.pAmount),
PaymentType = m.paymentType,
PayoutPartner = Convert.ToInt32(m.payoutPartner == "" ? "0" : m.payoutPartner),
PCountry = Convert.ToInt32(m.pCountry == "" ? "0" : m.pCountry),
pCountryCode = m.pCountryName,
PCountryName = m.pCountryName,
PCurrency = m.pCurrency,
ProcessFor = "send",
ProcessId = m.processId == "" ? Guid.NewGuid().ToString() : m.processId,
ProviderId = "",
RequestedBy = "mobile",
SAgent = 0,
SchemeId = m.schemeId,
SCountry = Convert.ToInt32(m.sCountry == "" ? "0" : m.sCountry),
SCurrency = m.sCurrency,
ServiceType = m.serviceType,
SessionId = Guid.NewGuid().ToString(),
tPExRate = m.tpExRate,
UserName = m.userId,
//DiscountedFee = Convert.ToDecimal(string.IsNullOrEmpty(m.discountedFee) ? "0" : m.discountedFee)
DiscountedFee = m.discountedFee ?? "0"
};
Log.Debug("Calculate | DATA SENT TO TPAPI : " + JsonConvert.SerializeObject(model));
APIJsonResponse result = _tpApi.ThirdPartyApiGetDataOnly<ExRateCalculate, APIJsonResponse>(model, "TP/ExRate", out jsonResponse);
Log.Debug("Calculate | TPAPI RRESPONSE : " + JsonConvert.SerializeObject(result));
response = new JsonRxResponse()
{
ErrorCode = result.ResponseCode,
Id = result.Id,
Msg = result.Msg,
Data = result.Data,
Extra = result.Extra,
Extra2 = result.Extra1,
FootNoteMessage = result.FootNoteMessage
};
return response;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
response.SetResponse("1", "Error occured while calculating ex-rate");
return response;
}
}
public JsonRxResponse TrackTransaction(TrackTransactionParam param)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
jsonRx = _repo.TrackTransaction(param);
Log.Debug("TrackTransaction | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
if (!jsonRx.ErrorCode.Equals("0"))
{
Log.Debug("TrackTransaction | Error occurred while calling TrackTransaction..." + "ControlNo: " + param.ControlNo);
return jsonRx;
}
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Error occurred while fetching the paystatus of the transaction.");
return jsonRx;
}
}
public JsonRxResponse AmendTransaction(TrackTransactionParam param)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
jsonRx = _repo.AmendTransaction(param);
Log.Debug("AmendTransaction | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
if (!jsonRx.ErrorCode.Equals("0"))
{
return jsonRx;
}
string body = "Hello JME Support, <br>";
body += param.UserId + " Send Amendment request for JME No: " + param.ControlNo;
body += param.Body;
//EmailParameters _emailParams = new EmailParameters()
//{
// To = ApplicationConfig.ReadWebConfig("JMESupport"),
// MsgSubject = "Amendment request for JME No: " + param.ControlNo,
// MsgBody = body
//};
//Task.Run(() => GetStatic.SendEmail(_emailParams));
//Task.Run(() =>
//{
// SendNotificationRequest request = new SendNotificationRequest()
// {
// IsBulkNotification = false,
// UserName = param.UserId,
// ProcessId = param.ControlNo,
// ProviderId = param.ControlNo,
// NotificationTypeId = NOTIFICATION_TYPE.EMAIL.ToString(),
// Template = Common.Model.Enum.NotifyTemplate.RESET_PASSWORD,
// Recipients = new List<RecipientViewModel>()
// {
// new RecipientViewModel()
// {
// NotificationContent = new NotificationDTO() {
// Body = body,
// //Title will be set by mapping json
// },
// Address= ApplicationConfig.ReadWebConfig("JMESupport")
// }
// }
// };
// NotifierV2.SendNotification(request, NOTIFICATION_TYPE.EMAIL);
//});
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Error occurred while requesting the transaction amendment request.");
return jsonRx;
}
}
public JsonRxResponse AmendTransactionV2(AmendTransactionParam param)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
var xml = GetXMLValues(param);
jsonRx = _repo.AmendTransactionV2(param, xml);
Log.Debug("AmendTransactionV2 | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
if (!jsonRx.ErrorCode.Equals("0"))
{
return jsonRx;
}
//string body = "Hello JME Support, <br>";
//body += param.UserId + " Send Amendment request for JME No: " + param.ControlNo;
//body += param.Body;
//EmailParameters _emailParams = new EmailParameters()
//{
// To = ApplicationConfig.ReadWebConfig("JMESupport"),
// MsgSubject = "Amendment request for JME No: " + param.ControlNo,
// MsgBody = body
//};
//Task.Run(() => GetStatic.SendEmail(_emailParams));
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Error occurred while requesting the transaction amendment request.");
return jsonRx;
}
}
private string GetXMLValues(AmendTransactionParam param)
{
StringBuilder sb = new StringBuilder("<root>");
foreach (var item in param.ChangeParams)
{
sb.Append("<row");
sb.Append(string.Format(" CloumnName=\"{0}\" ColumnValue=\"{1}\"", item.Key, item.Value));
sb.Append(" />");
}
sb.AppendLine("</root>");
return sb.ToString();
}
public JsonRxResponse CancelTransaction(TrackTransactionParam param)
{
JsonRxResponse jsonRx = new JsonRxResponse();
try
{
jsonRx = _repo.CancelTransaction(param);
Log.Debug("CancelTransaction | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
if (!jsonRx.ErrorCode.Equals("0"))
{
return jsonRx;
}
//string body = "Hello JME Support, <br>";
//body += param.UserId + " Send cancellation request for JME No: " + param.ControlNo;
//body += param.Body;
//EmailParameters _emailParams = new EmailParameters()
//{
// To = ApplicationConfig.ReadWebConfig("JMESupport"),
// MsgSubject = "Cancellation request for JME No: " + param.ControlNo,
// MsgBody = body
//};
//Task.Run(() => GetStatic.SendEmail(_emailParams));
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Error occurred while requesting the transaction cancel.");
return jsonRx;
}
}
public JsonRxResponse RejectTransaction(RejectTransactionParam param)
{
JsonRxResponse jsonRx = new JsonRxResponse();
//JsonRxResponse response = new JsonRxResponse();
APIJsonResponse jsonResponse = new APIJsonResponse();
try
{
DbResult _dbRes = _repo.GetTxnApproveData(param.UserId, param.TranId);
Log.Debug("RejectTransaction | GetTxnApproveData RESPONSE : " + JsonConvert.SerializeObject(_dbRes));
if (_dbRes.Extra == "True" || _dbRes.Extra == "1")//is realtime
{
CancelTxnPartner model = new CancelTxnPartner()
{
ProviderId = _dbRes.Msg,
PartnerPinNo = _dbRes.Id,
CancelReason = "41",
ProcessId = param.ProcessId
};
Log.Debug("RejectTransaction | DATA SENT TO TPAPI : " + JsonConvert.SerializeObject(model));
APIJsonResponse result = _tpApi.ThirdPartyApiGetDataOnly<CancelTxnPartner, APIJsonResponse>(model, "TP/cancelTxn", out jsonResponse);
Log.Debug("RejectTransaction | TPAPI RRESPONSE : " + JsonConvert.SerializeObject(result));
if (result.ResponseCode == "0")
{
jsonRx = _repo.RejectTransaction(param);
}
else
{
jsonRx = new JsonRxResponse()
{
ErrorCode = result.ResponseCode,
Id = result.Id,
Msg = result.Msg,
Data = result.Data,
Extra = result.Extra,
Extra2 = result.Extra1
};
}
return jsonRx;
}
else
{
jsonRx = _repo.RejectTransaction(param);
Log.Debug("RejectTransaction | DB RESPONSE : " + JsonConvert.SerializeObject(jsonRx));
}
return jsonRx;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
jsonRx.SetResponse("1", "Error occurred while rejecting the transaction.");
return jsonRx;
}
}
public Common.Model.DbResult CheckLoginPassword(string user, string txnPassword, string paymentType, string customerId)
{
return _repo.CheckLoginPassword(user, txnPassword, paymentType, customerId);
}
public Common.Model.DbResult CheckLoginPIN(string user, string txnPassword, string paymentType, string customerId)
{
return _repo.CheckLoginPIN(user, txnPassword, paymentType, customerId);
}
public JsonRxResponse SendTransaction(MobileRemitRequest model)
{
JsonRxResponse response = new JsonRxResponse();
APIJsonResponse jsonResponse = new APIJsonResponse();
try
{
TpSendMoney tp = new TpSendMoney()
{
CalBy = model.CalBy,
CDDI = new CustomerDueDiligence()
{
PurposeOfRemittance = model.PurposeOfRemittance,
RelWithSender = model.RelWithSender,
SourceOfFund = model.SourceOfFund,
otherPurposeOfRemittance = model.otherPurposeOfRemittance,
otherSourceOfFund = model.otherSourceOfFund,
GoodsOrigin = model.GoodsOrigin,
GoodsType = model.GoodsType,
PortOfShipment = model.PortOfShipment
},
CollAmt = model.CollAmt,
CollCurr = model.CollCurr,
DeliveryMethodId = Convert.ToInt32(model.DeliveryMethodId == "" || model.DeliveryMethodId == null ? "0" : model.DeliveryMethodId),
ExRate = model.ExRate,
ForexSessionId = model.FOREX_SESSION_ID,
IsRealtime = false,
PaymentType = model.PaymentType,
PayoutAmt = model.PayoutAmt == "" ? "0" : model.PayoutAmt,
PayoutCurr = model.PCurr,
PayOutPartnerId = Convert.ToInt32(model.PayOutPartner == "" || model.PayOutPartner == null ? "0" : model.PayOutPartner),
// PBankId = model.DeliveryMethodId == "2" ? Convert.ToInt32(model.PAgent == "" || model.PAgent == null ? "0" : model.PAgent) : 0,
PBankId = Convert.ToInt32(model.PAgent == "" || model.PAgent == null ? "0" : model.PAgent),
PBranchId = Convert.ToInt32(model.PBranch == "" || model.PBranch == null ? "0" : model.PBranch),
PCountryId = 0,
ProcessId = model.ProcessId,
ProviderId = "",
Receiver = new ReceiverInfo() { ReceiverId = model.ReceiverId, AccountNo = model.ReceiverAccountNo },
RequestedBy = "mobile",
ScDiscount = model.Discount,
//SchemeId = model.schemeId,
SCountryId = 0,
SenderId = model.SenderId,
ServiceCharge = model.ServiceCharge,
SessionId = "",
SIpAddress = model.IpAddress,
SourceType = "",
TpExRate = model.TpExRate,
TpPCurr = model.TpPCurr,
TransferAmt = model.TransferAmt,
UserName = model.User,
DiscountedFee = model.DiscountedFee,
SiteId = ConfigurationManager.AppSettings["sitereference"].ToString(),
isPromoCode = model.isPromoCode,
promoRowId = model.promoRowId,
promoCode = model.promoCode
};
Log.Debug("DOTRANSACTION | DATA SENT TO TPAPI : " + JsonConvert.SerializeObject(tp));
APIJsonResponse result = _tpApi.ThirdPartyApiGetDataOnly<TpSendMoney, APIJsonResponse>(tp, "TP/mobileSendTxn", out jsonResponse);
Log.Debug("DOTRANSACTION | TPAPI RESPONSE : " + JsonConvert.SerializeObject(result));
response = new JsonRxResponse()
{
ErrorCode = result.ResponseCode,
Id = result.Id,
Msg = result.Msg,
Data = result.Data,
Extra = result.Extra,
Extra2 = result.Extra2,
Extra3 = result.Extra3,
Extra4 = result.Extra4
};
if (response.ErrorCode.Equals("0"))
{
//var randomPassword = PasswordGenerator.GenerateRandomPassword(new PasswordGenerator.PasswordOptions()
//{ RequireDigit = true, RequiredLength = 10, RequiredUniqueChars = 2, RequireLowercase = true, RequireNonAlphanumeric = true, RequireUppercase = true });
string eID = HttpUtility.UrlEncode(AesOperation.EncryptString(ConfigurationManager.AppSettings["encryptKey"].ToString(), result.Id));
string eCn = HttpUtility.UrlEncode(AesOperation.EncryptString(ConfigurationManager.AppSettings["encryptKey"].ToString(), result.Extra));
var trustpaymentCallback = ApplicationConfig.ReadWebConfig("trustpaymentCallback");
var trustpaymentSuccess = ApplicationConfig.ReadWebConfig("trustpaymentSuccess");
var trustpaymentFail = ApplicationConfig.ReadWebConfig("trustpaymentFail");
Gateway gateway = new Gateway()
{
Code = result.Extra2,
IsRedirect = result.Extra3.Equals("Y") ? true : false,
//Token = randomPassword,
RedirectURL = result.Extra3.Equals("Y") ? $"{trustpaymentCallback}?id={eID}&ref={response.Extra4}&cn={eCn}&token=" : "",
CheckSuccessURL = result.Extra3.Equals("Y") ? trustpaymentSuccess : "",
CheckFailURL = result.Extra3.Equals("Y") ? trustpaymentFail : ""
};
response.Data = gateway;
string email = model.User;
try
{
if (!result.Extra3.Equals("Y"))
{
UserDetails userDetails = _requestServices.GetUserDetails(email);
List<Notify.Mapping> bodyMappings = new List<Notify.Mapping>();
bodyMappings.Add(new Notify.Mapping() { SValue = "CustomerName", SText = userDetails.FullName });
bodyMappings.Add(new Notify.Mapping() { SValue = "CollectAmt", SText = GetStatic.ShowDecimal(model.CollAmt) });
SendNotificationRequest request = new SendNotificationRequest()
{
IsBulkNotification = false,
UserName = userDetails.Email,
ProviderId = "BankTransferTxnPendingStatus",
NotificationTypeId = NOTIFICATION_TYPE.EMAIL.ToString(),
Template = Common.Model.Enum.NotifyTemplate.BANK_TRANSFER_TXN_PENDING,
Recipients = new List<RecipientViewModel>()
{
new RecipientViewModel()
{
NotificationContent = new NotificationDTO() {
Body = JsonConvert.SerializeObject(bodyMappings),
//Title will be set by mapping json
},
Address= userDetails.Email
}
}
};
NotifierV2.SendNotification(request, NOTIFICATION_TYPE.EMAIL);
}
}
catch (Exception ex)
{
Log.Error("BankTransferTxnPendingStatus", ex);
}
}
return response;
}
catch (Exception ex)
{
Log.Error("Something Went Wrong, Please Try Again!!", ex);
response.SetResponse("1", "Error occured while SendTransaction");
return response;
}
}
public JsonRxResponse AccountValidation(AccountValidationModel model)
{
JsonRxResponse response = new JsonRxResponse();
APIJsonResponse jsonResponse = new APIJsonResponse();
try
{
string providerid = string.Empty;
string paymentMode = model.PaymentMode ?? "";
string remarks = string.Empty;
bool allowProceed = true;
AccountValidate accountValidate = new AccountValidate()
{
AccountNumber = model.AccountNumber,
BankCode = model.BankCode,
UserName = model.UserName,
ReceiverName = !string.IsNullOrEmpty(model.ReceiverName) ? model.ReceiverName : Utilities.GetFullName(model.FirstName, model.MiddleName, model.LastName),
ControlNo = model.ControlNo ?? "",
PaymentMode = model.PaymentMode,
SessionId = "",
ProcessId = model.ProcessId
};
if (string.IsNullOrEmpty(providerid))
{
if (model.BankCountry.Equals("BD"))
{
providerid = "394414";
paymentMode = model.Equals("2") ? "AC" : "MW";
}
else if (model.BankCountry.Equals("NP"))
{
providerid = "394397";
if (model.BankCode == "2454")
accountValidate.BankCode = "IMEPAY";
else if (model.BankCode == "2662")
accountValidate.BankCode = "KHALTI";
}
else if (model.BankCountry.Equals("LK"))
{
providerid = "394400";
}
else if (model.BankCountry.Equals("VD"))
{
providerid = "394132";
}
}
accountValidate.ProviderId = providerid;
Log.Debug("AccountValidation | DATA SENT TO TPAPI : " + JsonConvert.SerializeObject(accountValidate));
APIJsonResponse result = _tpApi.ThirdPartyApiGetDataOnly<AccountValidate, APIJsonResponse>(accountValidate, "TP/Verify", out jsonResponse);
Log.Debug("AccountValidation | TPAPI RESPONSE : " + JsonConvert.SerializeObject(result));
response = new JsonRxResponse()
{
ErrorCode = result.ResponseCode.Equals("0") ? "0" : "1",
Id = result.Id,
Msg = result.ResponseCode.Equals("0") ? "Validation Success" : "Validation Failed",
Data = result.Data,
Extra = allowProceed ? "Y" : "N",
Extra2 = result.Extra1,
Extra3 = result.Extra3
};
return response;
}
catch (Exception ex)
{
Log.Error("AccountValidation", ex);
response.SetResponse("1", "Error occured while AccountValidation");
return response;
}
}
}
}