Beispiel #1
0
 public SearchTests()
 {
     context     = new HotelRoomBookingDBContext();
     controller  = new SearchServiceController();
     controller1 = new AdminServiceController(context);
     controller2 = new PaymentServiceController();
 }
Beispiel #2
0
        private void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            //await semaphoreSlim.WaitAsync().ConfigureAwait(false);
            semaphoreSlim.Wait();
            MayFlower  dbContext       = new MayFlower();
            SqlCommand innerSqlCommand = new SqlCommand();

            try
            {
                Components.BookingList bookedList       = new Components.BookingList(dbContext, innerSqlCommand);
                IEnumerable <SuperPNR> bookingProcessed = null;
                List <string>          successProcessed = null;

                if (sender.GetType().Name == "String" && !string.IsNullOrWhiteSpace(sender.ToString()))
                {
                    string[] splitAttr  = sender.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    bool     includeEXP = splitAttr.Length == 2;

                    //bookedList.CheckUpdatePendingPayment(true, true, true, splitAttr[0]).ConfigureAwait(false).GetAwaiter().GetResult();
                    bookingProcessed = bookedList.GetBookingPaid(splitAttr[0], true, true, true);
                }
                else
                {
                    bookedList.CheckUpdatePendingPayment(true, true, true).ConfigureAwait(false).GetAwaiter().GetResult();
                    bookingProcessed = bookedList.GetAllBookingPaid(true, true, true);
                }

                // Save for released travel wallet / travel credit
                if (innerSqlCommand?.Transaction != null)
                {
                    try
                    {
                        innerSqlCommand.Transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        eventLog1.WriteEntry("Error when commit transaction for travel credit & travel wallet."
                                             + Environment.NewLine + Environment.NewLine
                                             + ex.GetBaseException().Message + Environment.NewLine + Environment.NewLine +
                                             ex.StackTrace, EventLogEntryType.Warning);
                    }
                }

                if (bookingProcessed != null)
                {
                    foreach (var item in bookingProcessed)
                    {
                        foreach (var order in item.SuperPNROrders)
                        {
                            int         paymentRecordCount = order.PaymentOrders.Count;
                            List <bool> _status            = new List <bool>();
                            foreach (var paymentRecord in order.PaymentOrders)
                            {
                                string _paymentMethod = paymentRecord.PaymentMethodCode.ToLower();
                                if (_paymentMethod == "ipafpx")
                                {
                                    try
                                    {
                                        logger.Info(string.Format("SuperPNR {0} - {1} update from '{2}' to '{3}'."
                                                                  , item.SuperPNRID, item.SuperPNRNo, paymentRecord.PaymentStatusCode, "PAID"));
                                        paymentRecord.PaymentStatusCode = "PAID";
                                        _status.Add(true);
                                    }
                                    catch (Exception ex)
                                    {
                                        logger.Error(ex, "Fail to update payment.", JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                                                new JsonSerializerSettings {
                                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                        }));
                                        _status.Add(false);
                                    }
                                }
                                else if (_paymentMethod == "ipacc")
                                {
                                    try
                                    {
                                        if (string.IsNullOrWhiteSpace(paymentRecord.Ipay88TransactionID))
                                        {
                                            throw new Exception($"Payment Order ({item.SuperPNRNo}) record transaction id empty or null, cannot recapture.");
                                        }
                                        else if (paymentRecord.PaymentStatusCode == "CAPT")
                                        {
                                            logger.Info(string.Format("SuperPNR {0} - {1} success captured before.", item.SuperPNRID, item.SuperPNRNo));
                                            _status.Add(true);
                                        }
                                        else
                                        {
                                            var respond = PaymentServiceController.iPay88
                                                          .CapturePayment(paymentRecord.Ipay88TransactionID, paymentRecord.CurrencyCode, paymentRecord.PaymentAmount.ToString("n2"));

                                            if (respond.Status == "1") //  && respond.Desc == "Captured" // iPay88 capture doesn't respond desc
                                            {
                                                paymentRecord.PaymentStatusCode = "CAPT";
                                                logger.Info(string.Format("SuperPNR {0} - {1} success captured.", item.SuperPNRID, item.SuperPNRNo));
                                                _status.Add(true);
                                            }
                                            else
                                            {
                                                paymentRecord.RequeryStatusCode = "FAIL";
                                                logger.Info(string.Format("SuperPNR {0} - {1} capture failed.", item.SuperPNRID, item.SuperPNRNo)
                                                            + Environment.NewLine + Environment.NewLine + JsonConvert.SerializeObject(respond, Formatting.Indented));
                                                _status.Add(false);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        paymentRecord.RequeryStatusCode = "ERR";
                                        string objSerialize = null;

                                        try
                                        {
                                            objSerialize = JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                       new JsonSerializerSettings {
                                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                            });
                                        }
                                        catch (Exception innerEX)
                                        {
                                            logger.Error(innerEX, "Error while serialize database object.");
                                        }

                                        logger.Error(ex, "Fail to capture payment." + Environment.NewLine + Environment.NewLine
                                                     + objSerialize);
                                        _status.Add(false);
                                    }
                                }
                                else if (_paymentMethod == "adyenc")
                                {
                                    try
                                    {
                                        if (string.IsNullOrWhiteSpace(paymentRecord.Ipay88TransactionID))
                                        {
                                            throw new Exception($"Payment Order ({item.SuperPNRNo}) record transaction id empty or null, cannot recapture.");
                                        }
                                        else if (paymentRecord.PaymentStatusCode == "CAPT")
                                        {
                                            logger.Info(string.Format("SuperPNR {0} - {1} success captured before.", item.SuperPNRID, item.SuperPNRNo));
                                            _status.Add(true);
                                        }
                                        else
                                        {
                                            var respond = PaymentServiceController.Adyen
                                                          .CapturePayment(paymentRecord.Ipay88RefNo, paymentRecord.Ipay88TransactionID, paymentRecord.CurrencyCode, paymentRecord.PaymentAmount.ToString("n2"));

                                            if (respond.Status == "1") //  && respond.Desc == "Captured"
                                            {
                                                paymentRecord.PaymentStatusCode = "CAPT";
                                                logger.Info(string.Format("SuperPNR {0} - {1} success captured.", item.SuperPNRID, item.SuperPNRNo));
                                                _status.Add(true);
                                            }
                                            else
                                            {
                                                paymentRecord.RequeryStatusCode = "FAIL";
                                                logger.Info(string.Format("SuperPNR {0} - {1} capture failed.", item.SuperPNRID, item.SuperPNRNo)
                                                            + Environment.NewLine + Environment.NewLine + JsonConvert.SerializeObject(respond, Formatting.Indented));
                                                _status.Add(false);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        paymentRecord.RequeryStatusCode = "ERR";
                                        string objSerialize = null;

                                        try
                                        {
                                            objSerialize = JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                       new JsonSerializerSettings {
                                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                            });
                                        }
                                        catch (Exception innerEX)
                                        {
                                            logger.Error(innerEX, "Error while serialize database object.");
                                        }

                                        logger.Error(ex, "Fail to capture payment." + Environment.NewLine + Environment.NewLine
                                                     + objSerialize);
                                        _status.Add(false);
                                    }
                                }
                                else if (_paymentMethod == "sc" || _paymentMethod == "ac")
                                {
                                    if (paymentRecord.PaymentStatusCode != "PAID")
                                    {
                                        SqlCommand sqlCommand = new SqlCommand();

                                        try
                                        {
                                            if (_paymentMethod == "sc")
                                            {
                                                PaymentServiceController.ClaimUserCredit(paymentRecord.CreatedByID, paymentRecord.CurrencyCode,
                                                                                         paymentRecord.OrderID, paymentRecord.PaymentAmount, sqlCommand);
                                            }
                                            else if (_paymentMethod == "ac")
                                            {
                                                PaymentServiceController.updateAgentCreditRedeem(item.SuperPNRID, paymentRecord.OrderID, paymentRecord.CreatedByID, paymentRecord.CurrencyCode,
                                                                                                 paymentRecord.PaymentMethodCode, paymentRecord.PaymentAmount, item.MainProductType.ToDescription(), sqlCommand);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            paymentRecord.RequeryStatusCode = "ERR";
                                            string objSerialize = null;

                                            try
                                            {
                                                objSerialize = JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                           new JsonSerializerSettings {
                                                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                                });
                                            }
                                            catch (Exception innerEX)
                                            {
                                                logger.Error(innerEX, "Error while serialize database object.");
                                            }

                                            logger.Error(ex, "Fail to redeem credit while requery payment." + Environment.NewLine + Environment.NewLine
                                                         + objSerialize);
                                            _status.Add(false);
                                        }

                                        if (sqlCommand?.Transaction != null)
                                        {
                                            paymentRecord.PaymentStatusCode = "PAID";
                                            sqlCommand.Transaction.Commit();
                                            logger.Info(string.Format("SuperPNR {0} - {1} success claim credit.", item.SuperPNRID, item.SuperPNRNo));
                                            _status.Add(true);
                                        }
                                        else
                                        {
                                            paymentRecord.RequeryStatusCode = "ERR";
                                            logger.Error("Cannot claim user used travel credit.", JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                                                              new JsonSerializerSettings {
                                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                            }));
                                            _status.Add(false);
                                        }
                                    }
                                    else if (paymentRecord.PaymentStatusCode == "PAID")
                                    {
                                        logger.Info(string.Format("SuperPNR {0} - {1} claimed credit before.", item.SuperPNRID, item.SuperPNRNo));
                                        _status.Add(true);
                                    }
                                }
                                else if (_paymentMethod == "tw")
                                {
                                    if (paymentRecord.PaymentStatusCode != "PAID")
                                    {
                                        SqlCommand sqlCommand = new SqlCommand();

                                        try
                                        {
                                            var productType = paymentRecord.SuperPNROrder.SuperPNR.MainProductType.ToDescription();

                                            // Redeem travel wallet used
                                            PaymentServiceController.UpdateCashCreditRedeem(paymentRecord.CreatedByID, paymentRecord.CurrencyCode,
                                                                                            paymentRecord.OrderID, paymentRecord.PaymentAmount, productType, sqlCommand);

                                            // Remove holded travel wallet
                                            new PaymentServiceController().TempCashCreditRedeemDelete(paymentRecord.OrderID, paymentRecord.CreatedByID,
                                                                                                      paymentRecord.CurrencyCode, paymentRecord.PaymentAmount, sqlCommand);
                                        }
                                        catch (Exception ex)
                                        {
                                            paymentRecord.RequeryStatusCode = "ERR";
                                            string objSerialize = null;

                                            try
                                            {
                                                objSerialize = JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                           new JsonSerializerSettings {
                                                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                                });
                                            }
                                            catch (Exception innerEX)
                                            {
                                                logger.Error(innerEX, "Error while serialize database object.");
                                            }

                                            logger.Error(ex, "Fail to redeem travel wallet while requery payment." + Environment.NewLine + Environment.NewLine
                                                         + objSerialize);
                                            _status.Add(false);
                                        }

                                        if (sqlCommand?.Transaction != null)
                                        {
                                            paymentRecord.PaymentStatusCode = "PAID";
                                            sqlCommand.Transaction.Commit();
                                            logger.Info(string.Format("SuperPNR {0} - {1} success claim travel wallet.", item.SuperPNRID, item.SuperPNRNo));
                                            _status.Add(true);
                                        }
                                        else
                                        {
                                            paymentRecord.RequeryStatusCode = "ERR";
                                            logger.Error("Cannot claim user used travel wallet.", JsonConvert.SerializeObject(paymentRecord, Formatting.Indented,
                                                                                                                              new JsonSerializerSettings {
                                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                            }));
                                            _status.Add(false);
                                        }
                                    }
                                    else if (paymentRecord.PaymentStatusCode == "PAID")
                                    {
                                        logger.Info(string.Format("SuperPNR {0} - {1} claimed travel wallet before.", item.SuperPNRID, item.SuperPNRNo));
                                        _status.Add(true);
                                    }
                                }
                            }

                            try
                            {
                                if (paymentRecordCount == _status.Count && _status.All(x => x == true))
                                {
                                    string oriStatus = order.BookingStatusCode;
                                    order.BookingStatusCode = "CON";
                                    order.PaymentOrders     = UpdatePaymentRequeryStatus(order.PaymentOrders, "SUC");
                                    successProcessed        = successProcessed ?? new List <string>();

                                    successProcessed.Add(string.Format("SuperPNR {0} - {1}: Processed. [{2} --> {3}]",
                                                                       order.SuperPNRID, order.SuperPNR.SuperPNRNo, oriStatus, order.BookingStatusCode));
                                }

                                dbContext.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex, "Error while attempting to save changes on payment scheduler.");
                            }
                        }
                    }
                }

                if (successProcessed != null && successProcessed.Count > 0)
                {
                    string msg = "Payment Scheduler Information" + Environment.NewLine + Environment.NewLine +
                                 string.Join(Environment.NewLine, successProcessed);
                    logger.Info(msg);
                    eventLog1.WriteEntry(msg, EventLogEntryType.SuccessAudit, 200);
                }

                if (bookedList.InformationCaution != null && bookedList.InformationCaution.Count > 0)
                {
                    string msg = "Payment Scheduler Information" + Environment.NewLine + Environment.NewLine +
                                 string.Join(Environment.NewLine, bookedList.InformationCaution);
                    logger.Warn(msg);
                    eventLog1.WriteEntry(msg, EventLogEntryType.Warning);
                }
            }
            catch (Exception ex)
            {
                string msg = "Error Occured when running async action. " + Environment.NewLine + Environment.NewLine + ex.ToString();
                eventLog1.WriteEntry(msg, EventLogEntryType.Warning);
                logger.Warn(msg);
            }
            finally
            {
                try
                {
                    dbContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    var changedInfo = dbContext.ChangeTracker.Entries()
                                      .Where(t => t.State == System.Data.Entity.EntityState.Modified)
                                      .Select(t => new
                    {
                        Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => t.OriginalValues[pn]),
                        Current  = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]),
                    });

                    logger.Error(ex, "Error while attemp to save db change on finally action." +
                                 Environment.NewLine + Environment.NewLine +
                                 JsonConvert.SerializeObject(changedInfo, Formatting.Indented,
                                                             new JsonSerializerSettings {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                }

                semaphoreSlim.Release();
            }
        }
Beispiel #3
0
 public static void ClassInit(TestContext context)
 {
     controller = new PaymentServiceController();
     Today      = DateTime.Now;
 }
        public async Task <ActionResult> Checkout(PaymentCheckout payment, string paymentID = null)
        {
            string _pMethod = payment.PaymentMethod?.ToLower();

            if (_pMethod != null && _pMethod.Contains("adyen"))
            {
                // Reflection get credit card property to remove model validation
                var ccModel = typeof(Alphareds.Module.Model.CreditCard);

                foreach (var item in ccModel.GetProperties())
                {
                    // Remove model validtion
                    ModelState[item.Name]?.Errors.Clear();
                }
            }

            // If member not verify email, block place booking.
            if (User.Identity.IsAuthenticated && !CustomPrincipal.IsProfileActive && !CustomPrincipal.IsAgent)
            {
                ModelState.AddModelError("Error", "Please verify your account first, before place order.");
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Account inactive."));
            }

            string _paymentInfo = null;

            Cryptography.AES.TryDecrypt(paymentID, out _paymentInfo);

            var _superPNR = db.SuperPNRs.FirstOrDefault(x => x.SuperPNRID.ToString() == _paymentInfo);

            // Check model error before postback
            if (!ModelState.IsValid)
            {
                if (_superPNR.MainProductType == ProductTypes.Flight)
                {
                    return(RedirectToAction("OrderHistory", "Flight", new { tripid, bookingID = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else if (_superPNR.MainProductType == ProductTypes.Hotel)
                {
                    return(RedirectToAction("OrderHistory", "Hotel", new { tripid, confirmid = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Product Undefined."));
                }
            }

            var    _paymentList    = _superPNR.GetAllPaymentRecords();
            string paymentCurrency = "MYR";

            _superPNR.LoadPaymentDetailList(true, paymentCurrency);
            var paymentDtlList = _superPNR.PaymentDetailsList.FirstOrDefault(); // take converted rate, only one result

            SqlCommand command = new SqlCommand();

            // Can pass in user preferred currency code into ChkCreditAmtRemin, with optional parameter
            // Use this method to handle multi currency code in different order issues.
            decimal            creditUserAvail     = MemberServiceController.ChkCreditAmtRemain.ByUserId(CustomPrincipal.UserId, CustomPrincipal.UserTypeCode, command, paymentCurrency);
            decimal            cashWalletUserAvail = MemberServiceController.GetUserCashCredit(CustomPrincipal.UserId, command);
            CheckoutController checkoutCtl         = new CheckoutController(ControllerContext);

            decimal thisBookUsableAmt = checkoutCtl.CalcTravelCreditUsable(paymentDtlList.TotalPendingAmount, creditUserAvail, cashWalletUserAvail, DiscountType.TC);

            if (creditUserAvail >= thisBookUsableAmt && payment.UseCredit && (paymentDtlList.TotalPendingAmount <= thisBookUsableAmt))
            {
                payment.PaymentMethod = CustomPrincipal.IsAgent ? "AC" : "SC";
            }

            payment = new PaymentCheckout
            {
                AvailableCredit      = creditUserAvail,
                CreditUsed           = payment.UseCredit ? thisBookUsableAmt : 0m,
                PaymentMethod        = string.IsNullOrWhiteSpace(payment.PaymentMethod) ? CustomPrincipal.IsAgent ? "AC" : "SC" : payment.PaymentMethod,
                Policy               = payment.Policy,
                TnC                  = payment.TnC,
                UseCredit            = payment.UseCredit,
                CreditCard           = payment.CreditCard,
                CreditTerm           = CustomPrincipal.CreditTerm,
                PaymentCurrencyCode  = paymentDtlList.CurrencyCode,
                GrandTotalForPayment = paymentDtlList.TotalPendingAmount
            };

            PromoCodeFunctions  promoCodeFunctions          = new PromoCodeFunctions(_superPNR._MainPromoID, db);
            decimal             ttlOrderUsedTCAmountUseable = payment.CreditUsed;
            decimal             ttlTCAmtUsed         = 0m;
            List <PaymentOrder> paymentOrderToInsert = new List <PaymentOrder>();

            foreach (var _orderId in paymentDtlList.OrdersPendingPayment)
            {
                var _orders = _superPNR.SuperPNROrders.FirstOrDefault(x => x.OrderID == _orderId);

                #region Insert/Update Processing Fee
                var           feeChargeOrder = _orders.FeeChargeOrders.FirstOrDefault();
                ProcessingFee pf             = new ProcessingFee(payment.PaymentMethod, _orders.PendingPaymentAmt, _superPNR.MainProductType, promoCodeFunctions, paymentCurrency);

                var latestFeeCharge = new FeeChargeOrder
                {
                    OrderID         = _orders.OrderID,
                    CreatedByID     = _superPNR.CreatedByID,
                    CurrencyCode    = _orders.CurrencyCode,
                    FeeChargeAmount = pf.Amt,
                    FeeCode         = string.IsNullOrWhiteSpace(pf.FeeCode) ? payment.PaymentMethod : pf.FeeCode,
                    TaxCode         = string.IsNullOrWhiteSpace(pf.TaxCode) ? "ES" : pf.TaxCode,
                    TaxAmount       = pf.GST,
                    ModifiedByID    = CurrentUserID,
                    SuperPNROrder   = _orders,
                };

                if (feeChargeOrder == null)
                {
                    _orders.FeeChargeOrders.Add(latestFeeCharge); // for model calculation
                    PaymentServiceController.InsertFeeChargeOrder(latestFeeCharge, command);
                }
                else
                {
                    // For model calculation only
                    feeChargeOrder.CurrencyCode    = _orders.CurrencyCode;
                    feeChargeOrder.FeeChargeAmount = pf.Amt;
                    feeChargeOrder.FeeCode         = string.IsNullOrWhiteSpace(pf.FeeCode) ? payment.PaymentMethod : pf.FeeCode;
                    feeChargeOrder.TaxCode         = string.IsNullOrWhiteSpace(pf.TaxCode) ? "ES" : pf.TaxCode;
                    feeChargeOrder.TaxAmount       = pf.GST;

                    PaymentServiceController.UpdateFeeChargeOrder(latestFeeCharge, command);
                }
                #endregion

                if (payment != null && payment.UseCredit && payment.CreditUsed > 0 && (payment.PaymentMethod != "SC" && payment.PaymentMethod != "AC"))
                {
                    decimal _thisTransAmt      = _orders.PendingPaymentAmt;
                    decimal _thisTransUseTCAmt = ttlOrderUsedTCAmountUseable;
                    bool    usedAllTC          = ttlTCAmtUsed == payment.CreditUsed;

                    if (ttlOrderUsedTCAmountUseable > _thisTransAmt && !usedAllTC)
                    {
                        _thisTransUseTCAmt = _thisTransAmt;
                    }

                    if (ttlOrderUsedTCAmountUseable > 0 && !usedAllTC)
                    {
                        ttlOrderUsedTCAmountUseable -= _thisTransUseTCAmt;
                        ttlTCAmtUsed += _thisTransUseTCAmt;

                        PaymentOrder tcPaymentOrder = new PaymentOrder
                        {
                            OrderID             = _orders.OrderID,
                            PaymentDate         = DateTime.Now,
                            PaymentMethodCode   = CustomPrincipal.IsAgent ? "AC" : "SC",
                            PaymentStatusCode   = "PEND",
                            CurrencyCode        = _orders.CurrencyCode,
                            PaymentAmount       = _thisTransUseTCAmt,
                            ImagePath           = string.Empty,
                            Ipay88RefNo         = string.Empty,
                            Ipay88TransactionID = string.Empty,
                            CreatedByID         = CurrentUserID,
                            ModifiedByID        = CurrentUserID
                        };

                        paymentOrderToInsert.Add(tcPaymentOrder);

                        // Update SuperPNR Order indicated is Credit Used.
                        _orders.CreditAmount += _thisTransUseTCAmt;
                        _orders.IsCreditUsed  = _orders.CreditAmount > 0;
                        HotelServiceController.UpdateSuperPNROrder(_orders, command);
                    }
                }
                else
                {
                    // Update SuperPNR Order indicated is Credit Used.
                    _orders.CreditAmount = _orders.PaymentOrders.Where(x => (x.PaymentMethodCode == "AC" || x.PaymentMethodCode == "SC") && x.PaymentStatusCode == "PAID").Sum(s => s.PaymentAmount);
                    _orders.IsCreditUsed = _orders.CreditAmount > 0;
                    HotelServiceController.UpdateSuperPNROrder(_orders, command);
                }

                decimal paymentPrepareToInsert = paymentOrderToInsert.Where(x => x.OrderID == _orders.OrderID).Sum(s => s.PaymentAmount);

                if (paymentPrepareToInsert < _orders.PendingPaymentAmt)
                {
                    PaymentOrder normalPayment = new PaymentOrder
                    {
                        OrderID             = _orders.OrderID,
                        PaymentDate         = DateTime.Now,
                        PaymentMethodCode   = payment.PaymentMethod,
                        PaymentStatusCode   = "PEND",
                        CurrencyCode        = _orders.CurrencyCode,
                        PaymentAmount       = _orders.PendingPaymentAmt - paymentPrepareToInsert,
                        ImagePath           = string.Empty,
                        Ipay88RefNo         = string.Empty,
                        Ipay88TransactionID = string.Empty,
                        CreatedByID         = CurrentUserID,
                        ModifiedByID        = CurrentUserID
                    };

                    paymentOrderToInsert.Add(normalPayment);
                }
            }

            decimal    ttlAmtPOSTGateway    = paymentOrderToInsert.Where(x => x.PaymentMethodCode != "SC" && x.PaymentMethodCode != "AC").Sum(s => s.PaymentAmount);
            List <int> paymentOrderInserted = new List <int>();

            #region Insert SupperPNROrders records into DB
            try
            {
                foreach (var paymentRecord in paymentOrderToInsert)
                {
                    paymentOrderInserted.Add(PaymentServiceController.InsertPaymentOrder(paymentRecord, command));
                }

                #region Payment Gateway Redirect
                _superPNR.GetContactPerson();
                var contactPerson             = _superPNR.ContactPerson;
                PaymentSubmitModels iPayModel = PaymentController.PopulatePaymentSubmitModel(DateTime.Now, _superPNR.SuperPNRID, _superPNR.SuperPNRNo, paymentCurrency, ttlAmtPOSTGateway, payment.PaymentMethod, contactPerson.Phone1, contactPerson.Email, contactPerson.FullName);

                // Save transaction before redirect
                command.Transaction.Commit();

                string clientIP              = HttpContext.Request.UserHostAddress;
                string paymentMethod         = payment.PaymentMethod.ToUpper();
                string token                 = _superPNR.SuperPNRID.ToString() + "," + _superPNR.SuperPNRNo;
                string encToken              = General.CustomizeBaseEncoding.CodeBase64(token);
                string encPaymentOrderIDList = Cryptography.AES.Encrypt(paymentOrderInserted.JoinToString(","));

                FormCollection             form = new FormCollection();
                adyenCaptureResponseModels captureResponseModels2 = new adyenCaptureResponseModels();
                iPayCaptureResponseModels  captureResponseModels  = new iPayCaptureResponseModels
                {
                    Status = "1", Amount = iPayModel.PaymentAmount, TransId = ""
                };

                switch (payment.PaymentMethod.ToLower())
                {
                case "sc":
                    form.Add("Status", captureResponseModels.Status);
                    form.Add("Amount", captureResponseModels.Amount.ToString("n2"));

                    return(await checkoutCtl.PaymentCheckOut(form, captureResponseModels, captureResponseModels2, encToken, tripid, encPaymentOrderIDList, true));

                case "ac":
                    form.Add("Status", captureResponseModels.Status);
                    form.Add("Amount", captureResponseModels.Amount.ToString("n2"));

                    return(await checkoutCtl.PaymentCheckOut(form, captureResponseModels, captureResponseModels2, encToken, tripid, encPaymentOrderIDList, true));

                case "ipacc":
                    return(iPay88CheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), iPayModel, true));

                case "ipafpx":
                    return(iPay88CheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), iPayModel));

                case "adyenc":
                    AdyenCardPaymentModels adyenModel = PaymentController.PopulateAdyenPaymentSubmitModel(_superPNR.SuperPNRID, Request.Url.Scheme, _superPNR.SuperPNRNo, paymentCurrency, ttlAmtPOSTGateway, contactPerson.Email, payment.CreditCard);
                    return(AdyenCheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), adyenModel, Request.Form));

                default:
                    ModelState.AddModelError("Error", "Payment Method Not Found.");
                    break;
                }

                #endregion
            }
            catch (Exception ex)
            {
                // Insert payment record failed.
                command?.Transaction?.Rollback();

                // Handle redirect back to OrderHistory Page
                ViewBag.PaymentDetails = payment;
                ModelState.AddModelError("Error", "Unexpected error occured, please try again later.");

                string errorMsg = $"Insert Payment Order record failed on OrderHistory repayment.";
                logger.Fatal(ex, errorMsg);

                if (_superPNR.MainProductType == ProductTypes.Flight)
                {
                    return(RedirectToAction("OrderHistory", "Flight", new { tripid, bookingID = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else if (_superPNR.MainProductType == ProductTypes.Hotel)
                {
                    return(RedirectToAction("OrderHistory", "Hotel", new { tripid, confirmid = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Product Undefined."));
                }
            }
            #endregion

            return(null);
        }