public ActionResult Create(Payments payments)
        {
            string szError = "";
            string szEncriptedData = "";

            if (ModelState.IsValid)
            {
                //Encode the credit card info
                if (!string.IsNullOrEmpty(payments.CreditCardNumber))
                {
                    szEncriptedData = TimelyDepotMVC.Controllers.PaymentController.EncriptInfo02(payments.CreditCardNumber, ref szError);
                    payments.CreditCardNumber = szEncriptedData;
                }

                ////Encode the secure code
                //if (!string.IsNullOrEmpty(customerscreditcardshipping.SecureCode))
                //{
                //    szEncriptedData = TimelyDepotMVC.Controllers.PaymentController.EncriptInfo02(customerscreditcardshipping.SecureCode, ref szError);
                //    customerscreditcardshipping.SecureCode = szEncriptedData;
                //}

                db.Payments.Add(payments);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(payments);
        }
        //
        // GET: /PayPalPayment/OrderSimple
        public ActionResult OrderSimple(Payments payment)
        {
            string cancelUrl = "";
            string returnUrl = "";
            string szMsg = "";

            payment = db.Payments.Find(payment.Id);
            if (payment != null)
            {

                string customerEmail = Request["orderEmail"];

                string hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + Request.ApplicationPath;
                //string cancelUrl = hostUrl + "Payment";
                //string returnUrl = hostUrl + "PayPalPayment/PaymentSuccess";

                szMsg = hostUrl.Substring(hostUrl.Length - 1);
                if (szMsg == "/")
                {
                    cancelUrl = string.Format("{0}Payment?id={1}", hostUrl, payment.Id);
                    returnUrl = string.Format("{0}PayPalPayment/PaymentSuccess?paymentid={1}", hostUrl, payment.Id);
                }
                else
                {
                    cancelUrl = string.Format("{0}/Payment?id={1}", hostUrl, payment.Id);
                    returnUrl = string.Format("{0}/PayPalPayment/PaymentSuccess?paymentid={1}", hostUrl, payment.Id);
                }

                // Enter the email of the receiver
                string receiver = "*****@*****.**";

                var amount = Convert.ToDecimal(payment.Amount);
                var sender = customerEmail;
                var response = PayPal.AdaptivePayments.SimplePay.Execute
                    (receiver, amount, sender, "WebMatrix Integration", "127.0.0.1", "Test Device", cancelUrl, returnUrl, returnUrl);
                response.Redirect();
            }

            return RedirectToAction("Index", "Payment");
        }
        public ActionResult Payment(Payments payments)
        {
            int nPos = 0;
            string CreditNumber01 = payments.CreditCardNumber;
            string szEncriptedData = "";
            string szError = "";

            Payments paymentsHlp = null;
            SalesOrder salesorder = null;
            CustomersContactAddress customeraddress = null;
            CustomersShipAddress shipto = null;

            //use the user supplied data
            if (!string.IsNullOrEmpty(CreditNumber01))
            {
                nPos = CreditNumber01.IndexOf("*");
                if (nPos == -1)
                {
                    payments.CreditCardNumber = CreditNumber01;

                    //Encode the credit card info
                    if (!string.IsNullOrEmpty(payments.CreditCardNumber))
                    {
                        szEncriptedData = TimelyDepotMVC.Controllers.PaymentController.EncriptInfo02(payments.CreditCardNumber, ref szError);
                        payments.CreditCardNumber = szEncriptedData;
                    }
                }
                else
                {
                    //Do not replace the credit card number
                }
            }

            //Get the Payment and update paymen type
            paymentsHlp = new Payments();
            if (paymentsHlp != null)
            {
                paymentsHlp.Amount = payments.Amount;
                paymentsHlp.CustomerNo = payments.CustomerNo;
                paymentsHlp.PaymentDate = payments.PaymentDate;
                paymentsHlp.PaymentNo = payments.PaymentNo;
                paymentsHlp.SalesOrderNo = payments.SalesOrderNo;

                paymentsHlp.PaymentType = payments.PaymentType;
                paymentsHlp.CreditCardNumber = payments.CreditCardNumber;

                db.Payments.Add(paymentsHlp);
                db.SaveChanges();

                //Get the sales order
                salesorder = db.SalesOrders.Where(slor => slor.SalesOrderNo == paymentsHlp.SalesOrderNo).FirstOrDefault<SalesOrder>();
                if (salesorder != null)
                {
                    //Get the customer
                    customeraddress = db.CustomersContactAddresses.Where(ctad => ctad.CustomerId == salesorder.CustomerId).FirstOrDefault<CustomersContactAddress>();
                    if (customeraddress != null)
                    {
                        ViewBag.Company = customeraddress.CompanyName;

                    }

                    //Get the ship to address
                    shipto = db.CustomersShipAddresses.Where(ctst => ctst.CustomerId == salesorder.CustomerId).FirstOrDefault<CustomersShipAddress>();
                    if (shipto != null)
                    {
                        ViewBag.FirstName = shipto.FirstName;
                        ViewBag.LastName = shipto.LastName;
                        ViewBag.AddressHlp4 = string.Format("{0}", shipto.Address1);
                        ViewBag.AddressHlp5 = string.Format("{0} {1} {2}", shipto.City, shipto.State, shipto.Zip);

                    }

                    return RedirectToAction("Index", "PayPalPayment", new { id = paymentsHlp.Id });
                }

            }

            return RedirectToAction("Index");
        }
        //
        // GET: //Payment
        public PartialViewResult Payment(int id = 0)
        {
            int nPaymentNo = 0;
            int nCustomerId = 0;
            int nPos = -1;
            int nHas = 0;
            double dSalesAmount = 0;
            double dTax = 0;
            double dTotalTax = 0;
            double dTotalAmount = 0;
            double dBalanceDue = 0;
            string szError = "";
            string szDecriptedData = "";
            string szMsg = "";
            string szCustomerNo = "";

            Payments payment = null;

            InitialInfo initialinfo = null;

            Customers customer = null;
            List<KeyValuePair<string, string>> listSelector = new List<KeyValuePair<string, string>>();

            //Get sales order
            SalesOrder salesorder = db.SalesOrders.Find(id);
            if (salesorder != null)
            {
                //Get the totals
                GetSalesOrderTotals(salesorder.SalesOrderId, ref dSalesAmount, ref dTotalTax, ref dTax, ref dTotalAmount, ref dBalanceDue);

                customer = db.Customers.Where(cst => cst.Id == salesorder.CustomerId).FirstOrDefault<Customers>();
                if (customer != null)
                {
                    //Get the next payment No
                    initialinfo = db.InitialInfoes.FirstOrDefault<InitialInfo>();
                    if (initialinfo == null)
                    {
                        initialinfo = new InitialInfo();
                        initialinfo.InvoiceNo = 0;
                        initialinfo.PaymentNo = 1;
                        initialinfo.PurchaseOrderNo = 0;
                        initialinfo.SalesOrderNo = 0;
                        initialinfo.TaxRate = 0;
                        db.InitialInfoes.Add(initialinfo);
                    }
                    else
                    {
                        nPaymentNo = initialinfo.PaymentNo;
                        nPaymentNo++;
                        initialinfo.PaymentNo = nPaymentNo;
                        db.Entry(initialinfo).State = EntityState.Modified;
                    }
                    db.SaveChanges();

                    //Get Payment Type
                    listSelector = new List<KeyValuePair<string, string>>();
                    var qryPaymentType = db.CustomersCardTypes.OrderBy(cdty => cdty.CardType);
                    if (qryPaymentType.Count() > 0)
                    {
                        foreach (var item in qryPaymentType)
                        {
                            listSelector.Add(new KeyValuePair<string, string>(item.CardType, item.CardType));
                        }
                    }
                    SelectList paymentTypeselectorlist = new SelectList(listSelector, "Key", "Value");

                    //Get the Credit Card Number for each credit card
                    listSelector = new List<KeyValuePair<string, string>>();
                    if (paymentTypeselectorlist.Count() > 0)
                    {
                        foreach (var item in paymentTypeselectorlist)
                        {
                            var qryPayment = db.CustomersCreditCardShippings.Join(db.Customers, ctcc => ctcc.CustomerId, cstm => cstm.Id, (ctcc, cstm)
                                 => new { ctcc, cstm }).OrderBy(Nctad => Nctad.ctcc.CardType).ThenBy(Nctad => Nctad.ctcc.CreditNumber).Where(Nctad => Nctad.ctcc.CustomerId == customer.Id && Nctad.ctcc.CardType == item.Value);
                            if (qryPayment.Count() > 0)
                            {
                                foreach (var itemCard in qryPayment)
                                {
                                    if (nCustomerId == 0)
                                    {
                                        nCustomerId = itemCard.cstm.Id;
                                    }

                                    //Decode card number
                                    szError = "";
                                    szDecriptedData = TimelyDepotMVC.Controllers.PaymentController.DecodeInfo02(itemCard.ctcc.CreditNumber, ref szError);
                                    if (!string.IsNullOrEmpty(szError))
                                    {
                                        nPos = szError.IndexOf("data to decode");
                                        if (nPos != -1)
                                        {
                                            szDecriptedData = string.Empty;
                                        }
                                        else
                                        {
                                            szDecriptedData = string.Format("******");
                                        }
                                    }
                                    else
                                    {
                                        //Mask the card number
                                        nHas = szDecriptedData.Length;
                                        if (nHas > 4)
                                        {
                                            szMsg = szDecriptedData.Substring(nHas - 4, 4);
                                            szDecriptedData = string.Format("******{0}", szMsg);
                                        }
                                        else
                                        {
                                            szDecriptedData = string.Format("******");
                                        }
                                    }

                                    szMsg = string.Format("{0} - {1}", itemCard.ctcc.CardType, szDecriptedData);
                                    listSelector.Add(new KeyValuePair<string, string>(itemCard.ctcc.CreditNumber, szMsg));
                                }
                            }

                        }
                    }

                    SelectList cardsselectorlist = new SelectList(listSelector, "Key", "Value");
                    ViewBag.CardsList = cardsselectorlist;

                    payment = new Payments();
                    payment.PaymentNo = nPaymentNo.ToString();
                    payment.PaymentDate = DateTime.Now;
                    payment.CustomerNo = customer.CustomerNo;
                    payment.SalesOrderNo = salesorder.SalesOrderNo;
                    payment.Amount = Convert.ToDecimal(dBalanceDue);
                    //db.Payments.Add(payment);
                    //db.SaveChanges();

                }
            }

            return PartialView(payment);
        }
        public ActionResult Edit(Payments payments, string CreditNumber01)
        {
            int nPos = -1;
            string szError = "";
            string szEncriptedData = "";

            if (ModelState.IsValid)
            {
                //use the user supplied data
                if (!string.IsNullOrEmpty(CreditNumber01))
                {
                    nPos = CreditNumber01.IndexOf("*");
                    if (nPos == -1)
                    {
                        payments.CreditCardNumber = CreditNumber01;

                        //Encode the credit card info
                        if (!string.IsNullOrEmpty(payments.CreditCardNumber))
                        {
                            szEncriptedData = TimelyDepotMVC.Controllers.PaymentController.EncriptInfo02(payments.CreditCardNumber, ref szError);
                            payments.CreditCardNumber = szEncriptedData;
                        }
                    }
                    else
                    {
                        //Do not replace the credit card number
                    }
                }

                db.Entry(payments).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(payments);
        }
        public ActionResult AddCreditCardPayment(string salesOrderNumber, decimal totalBalance = 0, int invoiceId = -1, string paymentTypeSelected = "")
        {
            var environmentParam = this.db.EnvironmentParameters.SingleOrDefault(x => x.Active);
            IOrderedQueryable<Payments> paymentList = this.db.Payments.OrderByDescending(x => x.Id);
            var latestPayments = new Payments();
            var parsedPaymentNo = 0;
            var actualPaymentNo = string.Empty;
            Invoice anInvoice = null;

            if (paymentList.Any())
            {
                latestPayments = paymentList.First();
                parsedPaymentNo = int.Parse(latestPayments.PaymentNo);
                parsedPaymentNo++;
            }
            else
            {
                parsedPaymentNo = 1;
            }

            actualPaymentNo = parsedPaymentNo.ToString(CultureInfo.InvariantCulture);

            double dBalanceDue = 0;
            double dTotalAmount = 0;
            double dTax = 0;
            double dTotalTax = 0;
            double dSalesAmount = 0;

            var paymentCash = (from salesorders in this.db.SalesOrders
                               where (salesorders.SalesOrderNo == salesOrderNumber)
                               select new CashPayment()
                               {
                                   SalesOrderId = salesorders.SalesOrderId,
                                   CustomerId = salesorders.CustomerId,
                                   SalesOrderNo = salesorders.SalesOrderNo,
                                   SalesAmount = (decimal)dTotalAmount,
                                   PaymentNo = actualPaymentNo,
                                   PaymentType = "CreditCard",
                                   PaymentDate = DateTime.Now,
                                   ActualEnvironment = environmentParam.Description,
                                   PayLog = latestPayments.PayLog
                               }).FirstOrDefault();

            this.GetSalesOrderTotals(
                paymentCash.SalesOrderId,
                ref dSalesAmount,
                ref dTotalTax,
                ref dTax,
                ref dTotalAmount,
                ref dBalanceDue);

            if (invoiceId > 0)
            {
                anInvoice = this.db.Invoices.SingleOrDefault(x => x.InvoiceId == invoiceId);
            }

            if (anInvoice != null)
            {
                paymentCash.InvoiceDate = anInvoice.InvoiceDate;
                paymentCash.InvoiceNo = anInvoice.InvoiceNo;
                paymentCash.InvoiceId = anInvoice.InvoiceId;
                paymentCash.InvoicePayment = true;
            }

            var queryPaymentList = this.GetPaymentList(salesOrderNumber);
            var queryRefundList = this.GetRefundList(salesOrderNumber);
              double balance = dTotalAmount;
            var joinedRefundsAndPayments = JoinedRefundsAndPayments(queryPaymentList, queryRefundList);
            <<<<<<< master

            var paymentTransactionLists = joinedRefundsAndPayments as IList<PaymentTransactionList> ?? joinedRefundsAndPayments.ToList();

            if (paymentTransactionLists.Any())
            {
                var sumPayment = GetSumPayment(paymentTransactionLists);

            =======

            var paymentTransactionLists = joinedRefundsAndPayments as IList<PaymentTransactionList> ?? joinedRefundsAndPayments.ToList();

            if (paymentTransactionLists.Any())
            {
                var sumPayment = GetSumPayment(paymentTransactionLists);

            >>>>>>> local
                var sumRefunds = GetSumRefunds(paymentTransactionLists);

                if ((sumPayment != null) && (sumRefunds != null))
                {
             balance = (dTotalAmount - (double)sumPayment) + (double)sumRefunds;
                    this.ViewBag.DueBalance = balance;
                }
            }

            paymentCash.SalesAmount = (decimal)dSalesAmount;
            paymentCash.BalanceDue = (decimal?)balance;

            var listSelector = new List<KeyValuePair<string, string>>();
            var qryPaymentType = db.CustomersCardTypes.OrderBy(cdty => cdty.CardType);
            if (qryPaymentType.Count() > 0)
            {
                foreach (var item in qryPaymentType)
                {
                    listSelector.Add(new KeyValuePair<string, string>(item.CardType, item.CardType));
                }
            }
            var paymentTypeselectorlist = new SelectList(listSelector, "Key", "Value");
            var aCustomer = this.db.Customers.SingleOrDefault(x => x.Id == paymentCash.CustomerId);
            if (aCustomer != null)
            {
                var listOfCards = this.GetListOfCardSelectItems(aCustomer);
                ViewBag.CreditCardNumber = listOfCards;
            }

            ViewBag.PaymentType = paymentTypeselectorlist;

            return this.View(paymentCash);
            }

            private List<SelectListItem> GetListOfCardSelectItems(Customers aCustomer)
            {
            var emptyListOfCards = new List<SelectListItem>()
                                  {
                                      new SelectListItem() { Text = "", Value = "" }
                                  };

            var listOfCards = this.GetListOfCardsByUsers(aCustomer.CustomerNo) ?? emptyListOfCards;
            return listOfCards;
            }
            public ActionResult AddCreditCardPayment(CashPayment aPayment)
            {
            if (ModelState.IsValid)
            {
                var creditCardNumber = "No credit card";
                var aCreditCardType = "CreditCard";
                var creditcardId = int.Parse(aPayment.CreditCardNumber);
                var creditcardType = this.db.CustomersCreditCardShippings.SingleOrDefault(x => x.Id == creditcardId);
                if (creditcardType != null)
                {
                    aCreditCardType = creditcardType.CardType;
                }
                var customersCreditCardShipping =
                    this.db.CustomersCreditCardShippings.SingleOrDefault(
                        x => x.Id == creditcardId);
                if (customersCreditCardShipping != null)
                {
                    creditCardNumber =
                            customersCreditCardShipping.CreditNumber;
                }

                var customerData = this.db.Customers.SingleOrDefault(x => x.Id == aPayment.CustomerId);
                var aNewPayment = new Payments()
                {
                    PaymentNo = aPayment.PaymentNo,
                    CheckNo = aPayment.CheckNumber,
                    CustomerNo = String.IsNullOrEmpty(customerData.CustomerNo) ? string.Empty : customerData.CustomerNo,
                    SalesOrderNo = aPayment.SalesOrderNo,
                    PaymentType = aCreditCardType,
                    Amount = (decimal?)aPayment.PaymentAmount,
                    PaymentDate = aPayment.PaymentDate,
                    TransactionCode = 2,
                    CreditCardNumber = creditCardNumber
                };

                if (!string.IsNullOrEmpty(aPayment.InvoiceNo) || (aPayment.InvoiceId != -1))
                {
                    aNewPayment.InvoicePayment = "True";
                }

                db.Payments.Add(aNewPayment);
                db.SaveChanges();
                ViewBag.Environment = aPayment.ActualEnvironment;
                return RedirectToAction("FDZPayment", new { id = aNewPayment.Id, invoiceId = aPayment.InvoiceId, invoicepayment = aNewPayment.InvoicePayment, paymentAmount = aNewPayment.Amount });
            }

            var aCustomer = this.db.Customers.SingleOrDefault(x => x.Id == aPayment.CustomerId);
            var listOfCards = this.GetListOfCardSelectItems(aCustomer);
            this.ViewBag.CreditCardNumber = listOfCards;

            return View(aPayment);
            }
        public ActionResult AddCashPayment(string salesOrderNumber, int transactionCode, decimal? totalBalance, int invoiceId)
        {
            IOrderedQueryable<Payments> paymentList = this.db.Payments.OrderByDescending(x => x.Id);
            var latestPayments = new Payments();
            var parsedPaymentNo = 0;
            var actualPaymentNo = string.Empty;
            Invoice anInvoice = null;

            if (paymentList.Any())
            {
                latestPayments = paymentList.First();
                parsedPaymentNo = int.Parse(latestPayments.PaymentNo);
                parsedPaymentNo++;
            }
            else
            {
                parsedPaymentNo = 1;
            }

            actualPaymentNo = parsedPaymentNo.ToString(CultureInfo.InvariantCulture);

            double dBalanceDue = 0;
            double dTotalAmount = 0;
            double dTax = 0;
            double dTotalTax = 0;
            double dSalesAmount = 0;

            var paymentCash = (from salesorders in this.db.SalesOrders
                               where (salesorders.SalesOrderNo == salesOrderNumber)
                               select new CashPayment()
                                          {
                                              TransactionCode = transactionCode,
                                              SalesOrderId = salesorders.SalesOrderId,
                                              CustomerId = salesorders.CustomerId,
                                              SalesOrderNo = salesorders.SalesOrderNo,
                                              SalesAmount = (decimal)dTotalAmount,
                                              PaymentNo = actualPaymentNo,
                                              PaymentDate = DateTime.Now
                                          }).FirstOrDefault();

            if (invoiceId > 0)
            {
                anInvoice = this.db.Invoices.SingleOrDefault(x => x.InvoiceId == invoiceId);
            }

            if (anInvoice != null)
            {
                if (paymentCash != null)
                {
                    paymentCash.InvoiceDate = anInvoice.InvoiceDate;
                    paymentCash.InvoiceNo = anInvoice.InvoiceNo;
                    paymentCash.InvoiceId = anInvoice.InvoiceId;
                }
            }

            if (paymentCash != null)
            {
                this.GetSalesOrderTotals(
                    paymentCash.SalesOrderId,
                    ref dSalesAmount,
                    ref dTotalTax,
                    ref dTax,
                    ref dTotalAmount,
                    ref dBalanceDue);

                paymentCash.SalesAmount = (decimal)dSalesAmount;
                paymentCash.BalanceDue = totalBalance;
                ViewBag.PaymentType = SelectPayTypeListItems();
                return this.View(paymentCash);
            }

            ViewBag.ErrorMessage("Error getting payment data!");
            return this.View();
        }
        public ActionResult AddCashPayment(CashPayment aPayment)
        {
            if (ModelState.IsValid)
            {
                var customerData = this.db.Customers.SingleOrDefault(x => x.Id == aPayment.CustomerId);
                var aCustomerNo = string.Empty;
                if (customerData != null)
                {
                    aCustomerNo = customerData.CustomerNo;
                }

                var aTransactionCode = Convert.ToInt32(aPayment.PaymentType);
                var paymentDescription = string.Empty;
                var transactioncodeQuery = this.db.TransactionCodes.SingleOrDefault(z => z.TransactionCode == aTransactionCode);
                if (transactioncodeQuery != null)
                {
                    paymentDescription = transactioncodeQuery.CodeDescription;
                }

                var aNewPayment = new Payments()
                                           {
                                               CheckNo = aPayment.CheckNumber,
                                               PaymentNo = aPayment.PaymentNo,
                                               CustomerNo = string.IsNullOrEmpty(aCustomerNo) ? string.Empty : aCustomerNo,
                                               SalesOrderNo = aPayment.SalesOrderNo,
                                               PaymentType = string.IsNullOrEmpty(paymentDescription) ? "None" : paymentDescription,
                                               Amount = (decimal?)aPayment.PaymentAmount,
                                               PaymentDate = aPayment.PaymentDate,
                                               TransactionCode = 1,
                                               PayLog = "Transaction succeed!"
                                           };

                if (!string.IsNullOrEmpty(aPayment.InvoiceNo) || (aPayment.InvoiceId != -1))
                {
                    aNewPayment.InvoicePayment = "True";
                }

                db.Payments.Add(aNewPayment);
                db.SaveChanges();

                this.AddPaymentAmountSalesOrder(aNewPayment);
                this.AddPaymentAmountInvoice(aNewPayment);

                return RedirectToAction("PaymentTransactionList", new { salesOrderNo = aPayment.SalesOrderNo, invoiceId = -1 });
            }

            ViewBag.PaymentType = SelectPayTypeListItems();
            return View(aPayment);
        }
        public ActionResult Add()
        {
            int nPaymentNo = 0;
            string CustomerNo = string.Empty;
            string CompanyName = string.Empty;
            InitialInfo initialinfo = null;

            //Get the next payment No
            initialinfo = db.InitialInfoes.FirstOrDefault<InitialInfo>();
            if (initialinfo == null)
            {
                initialinfo = new InitialInfo();
                initialinfo.InvoiceNo = 0;
                initialinfo.PaymentNo = 1;
                initialinfo.PurchaseOrderNo = 0;
                initialinfo.SalesOrderNo = 0;
                initialinfo.TaxRate = 0;
                db.InitialInfoes.Add(initialinfo);
            }
            else
            {
                nPaymentNo = initialinfo.PaymentNo;
                nPaymentNo++;
                initialinfo.PaymentNo = nPaymentNo;
                db.Entry(initialinfo).State = EntityState.Modified;
            }

            Payments payment = new Payments();
            payment.PaymentNo = nPaymentNo.ToString();
            payment.PaymentDate = DateTime.Now;
            db.Payments.Add(payment);
            db.SaveChanges();

            TempData["Status"] = "Add";

            return RedirectToAction("Index", new { id = payment.Id });
        }
            private decimal GetSalesOrderPayments(string SalesOrderNo, Payments payments)
            {
            decimal dPayments = 0;

            TimelyDepotContext db01 = new TimelyDepotContext();

            IQueryable<Payments> qryPayment = db01.Payments.Where(pmt => pmt.SalesOrderNo == SalesOrderNo);
            if (qryPayment.Count() > 0)
            {
                foreach (var item in qryPayment)
                {
                    if (item.Id != payments.Id)
                    {
                        dPayments = dPayments + Convert.ToDecimal(item.Amount);
                    }
                }
            }

            return dPayments;
            }
            public ActionResult EditCashPayments(Payments payments, decimal? oldAmount)
            {
            int nPos = -1;
            decimal dPayments = 0;
            string szSalesOrderNo = string.Empty;
            string szEncriptedData = string.Empty;
            string szError = string.Empty;
            Invoice invoice = null;

            if (ModelState.IsValid)
            {
                //Verify that the payment is less than the balance due
                //dPayments = GetSalesOrderPayments(payments.SalesOrderNo, payments);
                //dPayments = dPayments + Convert.ToDecimal(payments.Amount);
                SalesOrder salesorder = db.SalesOrders.Where(slod => slod.SalesOrderNo == payments.SalesOrderNo).FirstOrDefault<SalesOrder>();
                if (salesorder != null)
                {
                    //Update the Sales order
                    salesorder = db.SalesOrders.Where(slod => slod.SalesOrderNo == payments.SalesOrderNo).FirstOrDefault<SalesOrder>();
                    if (salesorder != null)
                    {
                        dPayments = (decimal)salesorder.PaymentAmount;
                        szSalesOrderNo = salesorder.SalesOrderNo;
                        //salesorder.PaymentAmount = Convert.ToDecimal(salesorder.PaymentAmount) - Convert.ToDecimal(payments.Amount);
                        salesorder.PaymentAmount = (dPayments - oldAmount) + Convert.ToDecimal(payments.Amount);
                        salesorder.PaymentDate = Convert.ToDateTime(payments.PaymentDate);
                        if (Convert.ToDecimal(salesorder.PaymentAmount) < 0)
                        {
                            salesorder.PaymentAmount = 0;
                        }

                        db.Entry(salesorder).State = EntityState.Modified;
                        db.SaveChanges();
                    }

                    //Update the invoice
                    invoice = db.Invoices.Where(invc => invc.SalesOrderNo == szSalesOrderNo).FirstOrDefault<Invoice>();
                    if (invoice != null)
                    {
                        //invoice.PaymentAmount = Convert.ToDecimal(invoice.PaymentAmount) - Convert.ToDecimal(payments.Amount);
                        invoice.PaymentAmount = (dPayments - oldAmount) + Convert.ToDecimal(payments.Amount);
                        invoice.PaymentDate = Convert.ToDateTime(payments.PaymentDate);
                        if (Convert.ToDecimal(invoice.PaymentAmount) < 0)
                        {
                            invoice.PaymentAmount = 0;
                        }

                        db.Entry(invoice).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                payments.PayLog = "Succeed!! Payment data changed.";
                var paymentCode = int.Parse(payments.PaymentType);
                var transactionRequest = this.db.TransactionCodes.FirstOrDefault(x => x.TransactionCode == paymentCode);
                if (transactionRequest != null)
                {
                    var transactionDecription = transactionRequest.CodeDescription;
                    payments.PaymentType = transactionDecription;
                }

                db.Entry(payments).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("PaymentTransactionList", new { salesOrderNo = payments.SalesOrderNo, invoiceId = -1 });
            }
            ViewBag.PaymentType = SelectPayTypeListItems();
            return View(payments);
            }
            public ActionResult Create(Payments payments)
            {
            if (ModelState.IsValid)
            {
                db.Payments.Add(payments);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(payments);
            }
            public ActionResult PaymentComponentUpdate(string id)
            {
            List<KeyValuePair<string, string>> listSelector = new List<KeyValuePair<string, string>>();
            Payments payment = new Payments();
            ViewBag.PaymentId = id;
            payment = db.Payments.Find(id);

            //Get the dropdown data
            var qryCust = db.CustomersContactAddresses.Join(db.Customers, ctad => ctad.CustomerId, cstm => cstm.Id, (ctad, cstm)
                => new { ctad, cstm }).OrderBy(Nctad => Nctad.ctad.CompanyName);
            if (qryCust.Count() > 0)
            {
                foreach (var item in qryCust)
                {
                    listSelector.Add(new KeyValuePair<string, string>(item.cstm.CustomerNo, item.ctad.CompanyName));
                }
            }
            SelectList tradeselectorlist = new SelectList(listSelector, "Key", "Value");
            ViewBag.CustomerList = tradeselectorlist;
            return View();
            }