public ActionResult Create(PurchasOrderDetail purchasorderdetail)
        {
            if (ModelState.IsValid)
            {
                db.PurchasOrderDetails.Add(purchasorderdetail);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(purchasorderdetail);
        }
        public ActionResult Create(PurchaseOrders purchaseorders, string PODateHlp)
        {
            int nYear = 0;
            int nMonth = 0;
            int nDay = 0;
            int nCustomerId = 0;
            int nSalesOrderId = 0;
            int nTradeId = 0;
            int nPurchaseOrderId = 0;
            int nItemPosition = 0;
            decimal dSetupCharge = 0;
            decimal dRunCharge = 0;
            string szVendorNo = "";
            string szPaymentType = "";
            string szSalesOrderNo = "";
            string szCardType = "";
            string szItemId = "";
            string[] szDateHlp = null;
            string[] szSetUpRunHlp = null;

            int nHas = 0;
            int nPos = -1;
            string szError = "";
            string szDecriptedData = "";
            string szDecriptedCode = "";
            string szMsg = "";

            DateTime dDate = DateTime.Now;
            DateTime dShipDate = DateTime.Now;

            PurchasOrderDetail purchaseorderdetail = null;
            SalesOrder salesorder = null;
            SalesOrderDetail salesorderdetail = null;
            CustomersContactAddress customeraddress = null;
            CustomersShipAddress customershipto = null;
            CustomersCreditCardShipping cardshipping = null;
            Trade trade = null;
            SalesOrderBlindShip blindship = null;
            VendorItem vendoritem = null;
            SUB_ITEM subitem = null;
            Payments payment = null;

            TimelyDepotContext db02 = new TimelyDepotContext();

            List<KeyValuePair<string, string>> listSelector = new List<KeyValuePair<string, string>>();
            IQueryable<Trade> qryTrade = null;
            IQueryable<SalesOrderDetail> qrysalesdetail = null;

            if (!string.IsNullOrEmpty(PODateHlp))
            {
                szDateHlp = PODateHlp.Split('/');
                if (szDateHlp != null)
                {
                    nMonth = Convert.ToInt32(szDateHlp[0]);
                    nDay = Convert.ToInt32(szDateHlp[1]);
                    nYear = Convert.ToInt32(szDateHlp[2]);
                    dDate = new DateTime(nYear, nMonth, nDay);
                }
                else
                {
                    dDate = Convert.ToDateTime(purchaseorders.PODate);
                }
            }
            else
            {
                dDate = Convert.ToDateTime(purchaseorders.PODate);
            }

            if (ModelState.IsValid)
            {
                if (purchaseorders.PODate != dDate)
                {
                    purchaseorders.PODate = dDate;
                }

                //Get the Sales Order Data
                salesorder = db.SalesOrders.Where(slor => slor.SalesOrderNo == purchaseorders.SalesOrderNo).FirstOrDefault<SalesOrder>();
                if (salesorder != null)
                {
                    nSalesOrderId = salesorder.SalesOrderId;
                    nCustomerId = Convert.ToInt32(salesorder.CustomerId);
                    nTradeId = Convert.ToInt32(salesorder.TradeId);
                    szVendorNo = purchaseorders.VendorId;
                    szSalesOrderNo = purchaseorders.SalesOrderNo;

                    purchaseorders.PurchaseOrderReference = string.Format("{0}-{1}", salesorder.SalesOrderNo, nCustomerId.ToString());

                    if (salesorder.ShipDate != null)
                    {
                        dShipDate = Convert.ToDateTime(salesorder.ShipDate);
                        purchaseorders.ShipDate = dShipDate;
                    }

                    purchaseorders.IsBlindShip = salesorder.IsBlindShip;

                    if (purchaseorders.IsBlindShip)
                    {
                        //Get blind ship address
                        blindship = db02.SalesOrderBlindShips.Where(blsh => blsh.SalesOrderId == nSalesOrderId).FirstOrDefault<SalesOrderBlindShip>();
                        if (blindship != null)
                        {
                            purchaseorders.ToAddress1 = blindship.Address1;
                            purchaseorders.ToAddress2 = blindship.Address2;
                            purchaseorders.ToCity = blindship.City;
                            purchaseorders.ToCompany = blindship.Title;
                            purchaseorders.ToCountry = blindship.Country;
                            //purchaseorders.FromEmail = blindship.Email;
                            //purchaseorders.FromFax = blindship.Fax;
                            purchaseorders.ToName = string.Format("{0} {1}", blindship.FirstName, blindship.LastName);
                            purchaseorders.ToState = blindship.State;
                            purchaseorders.ToTel = blindship.Tel;
                            purchaseorders.ToTitle = blindship.Title;
                            purchaseorders.ToZip = blindship.Zip;
                        }
                        db02.Dispose();
                        db02 = new TimelyDepotContext();

                        customershipto = db02.CustomersShipAddresses.Where(ctsh => ctsh.CustomerId == nCustomerId).FirstOrDefault<CustomersShipAddress>();
                        if (customershipto != null)
                        {
                            purchaseorders.FromAddress1 = customershipto.Address1;
                            purchaseorders.FromAddress2 = customershipto.Address2;
                            purchaseorders.FromCity = customershipto.City;
                            purchaseorders.FromCompany = customershipto.Title;
                            purchaseorders.FromCountry = customershipto.Country;
                            purchaseorders.FromEmail = customershipto.Email;
                            purchaseorders.FromFax = customershipto.Fax;
                            purchaseorders.FromName = string.Format("{0} {1}", customershipto.FirstName, customershipto.LastName);
                            purchaseorders.FromState = customershipto.State;
                            purchaseorders.FromTel = customershipto.Tel;
                            //purchaseorders.ToTitle = trade.Title;
                            purchaseorders.FromZip = customershipto.Zip;

                            //Get the blind drop data
                            purchaseorders.BlindDrop = string.Format("{0} a/c: {1}", customershipto.ShippingPreference, customershipto.ShipperAccount);

                        }
                        db02.Dispose();
                        db02 = new TimelyDepotContext();
                    }
                    else
                    {
                        //Get customer address
                        customeraddress = db02.CustomersContactAddresses.Where(ctad => ctad.CustomerId == nCustomerId).FirstOrDefault<CustomersContactAddress>();
                        if (customeraddress != null)
                        {
                            purchaseorders.FromAddress1 = customeraddress.Address;
                            purchaseorders.FromAddress2 = customeraddress.Note;
                            purchaseorders.FromCity = customeraddress.City;
                            purchaseorders.FromCompany = customeraddress.CompanyName;
                            purchaseorders.FromCountry = customeraddress.Country;
                            purchaseorders.FromEmail = customeraddress.Email;
                            purchaseorders.FromFax = customeraddress.Fax;
                            purchaseorders.FromName = string.Format("{0} {1}", customeraddress.FirstName, customeraddress.LastName);
                            purchaseorders.FromState = customeraddress.State;
                            purchaseorders.FromTel = customeraddress.Tel;
                            purchaseorders.FromTitle = customeraddress.Title;
                            purchaseorders.FromZip = customeraddress.Zip;
                        }
                        db02.Dispose();
                        db02 = new TimelyDepotContext();

                        //Get the trade data
                        //trade = db02.Trades.Where(trd => trd.TradeId == nTradeId).FirstOrDefault<Trade>();
                        //if (trade != null)
                        //{
                        //    purchaseorders.ToAddress1 = trade.Address;
                        //    //purchaseorders.ToAddress2 = trade.WebSite;
                        //    purchaseorders.ToCity = trade.City;
                        //    purchaseorders.ToCompany = trade.TradeName;
                        //    purchaseorders.ToCountry = trade.Country;
                        //    purchaseorders.ToEmail = trade.Email;
                        //    purchaseorders.ToFax = trade.Fax;
                        //    //purchaseorders.ToName = string.Format("{0} {1}", trade., trade.LastName);
                        //    purchaseorders.ToState = trade.State;
                        //    purchaseorders.ToTel = customeraddress.Tel;
                        //    //purchaseorders.ToTitle = trade.Title;
                        //    purchaseorders.ToZip = trade.PostCode;
                        //}
                        //db02.Dispose();
                        //db02 = new TimelyDepotContext();

                        //Get the ship to address for the sales order
                        customershipto = db02.CustomersShipAddresses.Where(ctsh => ctsh.Id == salesorder.CustomerShiptoId).FirstOrDefault<CustomersShipAddress>();
                        if (customershipto != null)
                        {
                            purchaseorders.ToAddress1 = customershipto.Address1;
                            purchaseorders.ToAddress2 = customershipto.Address2;
                            purchaseorders.ToCity = customershipto.City;
                            purchaseorders.ToCompany = customershipto.Title;
                            purchaseorders.ToCountry = customershipto.Country;
                            purchaseorders.ToEmail = customershipto.Email;
                            purchaseorders.ToFax = customershipto.Fax;
                            purchaseorders.ToName = string.Format("{0} {1}", customershipto.FirstName, customershipto.LastName);
                            purchaseorders.ToState = customershipto.State;
                            purchaseorders.ToTel = customershipto.Tel;
                            //purchaseorders.ToTitle = trade.Title;
                            purchaseorders.ToZip = customershipto.Zip;

                            //Get the blind drop data
                            purchaseorders.BlindDrop = string.Format("{0} a/c: {1}", customershipto.ShippingPreference, customershipto.ShipperAccount);

                        }
                        db02.Dispose();
                        db02 = new TimelyDepotContext();

                        customershipto = db02.CustomersShipAddresses.Where(ctsh => ctsh.CustomerId == nCustomerId).FirstOrDefault<CustomersShipAddress>();
                        if (customershipto != null)
                        {

                            //Get the blind drop data
                            purchaseorders.BlindDrop = string.Format("{0} a/c: {1}", customershipto.ShippingPreference, customershipto.ShipperAccount);

                        }
                        db02.Dispose();
                        db02 = new TimelyDepotContext();

                    }

                }

                //Get the pay by data
                payment = db.Payments.Where(pmt => pmt.SalesOrderNo == szSalesOrderNo).FirstOrDefault<Payments>();
                if (payment != null)
                {
                    szPaymentType = payment.PaymentType;
                    if (!string.IsNullOrEmpty(szPaymentType))
                    {
                        cardshipping = db.CustomersCreditCardShippings.Where(cdsp => cdsp.CreditNumber == szPaymentType && cdsp.CustomerId == nCustomerId).FirstOrDefault<CustomersCreditCardShipping>();
                        if (cardshipping != null)
                        {
                            szCardType = cardshipping.CardType;
                            if (!string.IsNullOrEmpty(szCardType))
                            {
                                szError = "";
                                szDecriptedData = TimelyDepotMVC.Controllers.PaymentController.DecodeInfo02(szPaymentType, 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("******");
                                    }
                                }

                                purchaseorders.PaidBy = string.Format("{0} {1}", szCardType, szDecriptedData);
                            }
                        }
                    }
                }

                db.Entry(purchaseorders).State = EntityState.Modified;
                db.SaveChanges();

                //Get the detail
                nPurchaseOrderId = purchaseorders.PurchaseOrderId;

                qrysalesdetail = db.SalesOrderDetails.Where(sldt => sldt.SalesOrderId == nSalesOrderId).OrderBy(sldt => sldt.ItemPosition).ThenBy(sldt => sldt.ItemOrder);
                if (qrysalesdetail.Count() > 0)
                {
                    foreach (var item in qrysalesdetail)
                    {

                        //Get the vendors data
                        if (item.ItemID != null)
                        {
                            if (string.IsNullOrEmpty(szItemId))
                            {
                                szItemId = item.ItemID;
                            }
                            purchaseorderdetail = new PurchasOrderDetail();
                            purchaseorderdetail.PurchaseOrderId = nPurchaseOrderId;
                            purchaseorderdetail.ItemID = item.ItemID;
                            purchaseorderdetail.Sub_ItemID = item.Sub_ItemID;
                            purchaseorderdetail.Description = item.Description;

                            nPos = -1;
                            nPos = item.Description.IndexOf("Set up");
                            if (nPos != -1)
                            {
                                szSetUpRunHlp = item.Description.Split(' ');
                                if (szSetUpRunHlp.Length > 0)
                                {
                                    purchaseorderdetail.Description = string.Format("Set up Charge {0} {1}", nPurchaseOrderId.ToString(), szSetUpRunHlp[4]);
                                }
                            }
                            nPos = -1;
                            szSetUpRunHlp = null;
                            nPos = item.Description.IndexOf("Run Charge");
                            if (nPos != -1)
                            {
                                szSetUpRunHlp = item.Description.Split(' ');
                                if (szSetUpRunHlp.Length > 0)
                                {
                                    purchaseorderdetail.Description = string.Format("Run Charge {0} {1}", nPurchaseOrderId.ToString(), szSetUpRunHlp[3]);
                                }
                            }

                            purchaseorderdetail.Quantity = item.Quantity;
                            purchaseorderdetail.UnitPrice = item.UnitPrice;
                            purchaseorderdetail.Tax = item.Tax;

                            purchaseorderdetail.ItemPosition = item.ItemPosition;
                            purchaseorderdetail.ItemOrder = item.ItemOrder;
                            nItemPosition = Convert.ToInt32(item.ItemPosition);

                            vendoritem = db02.VendorItems.Where(vdit => vdit.VendorNo == szVendorNo && vdit.ItemId == item.ItemID).FirstOrDefault<VendorItem>();
                            if (vendoritem != null)
                            {
                                if (purchaseorders.IsBlindShip)
                                {
                                    purchaseorderdetail.UnitPrice = vendoritem.CostBlind;
                                }
                                else
                                {
                                    if (vendoritem.Cost != null)
                                    {
                                        purchaseorderdetail.UnitPrice = vendoritem.Cost;

                                    }
                                }

                                purchaseorderdetail.VendorReference = vendoritem.VendorPartNo;
                            }
                            else
                            {
                                //purchaseorderdetail.UnitPrice = 0;
                            }

                            if (vendoritem != null)
                            {
                                dSetupCharge = Convert.ToDecimal(vendoritem.SetupCharge);
                                dRunCharge = Convert.ToDecimal(vendoritem.RunCharge);
                            }
                            else
                            {
                                dSetupCharge = 0;
                                dRunCharge = 0;
                            }
                            db02.Dispose();
                            db02 = new TimelyDepotContext();

                            //Get the vendor part no from the subitem table
                            subitem = db02.SUB_ITEM.Where(sbit => sbit.Sub_ItemID == item.Sub_ItemID).FirstOrDefault<SUB_ITEM>();
                            if (subitem != null)
                            {
                                purchaseorderdetail.VendorReference = subitem.PartNo;
                            }
                            db02.Dispose();
                            db02 = new TimelyDepotContext();

                            db.PurchasOrderDetails.Add(purchaseorderdetail);
                        }

                    }

                    ////Add setup and run charges
                    //purchaseorderdetail = new PurchasOrderDetail();
                    //purchaseorderdetail.PurchaseOrderId = nPurchaseOrderId;
                    //purchaseorderdetail.ItemID = szItemId;
                    //purchaseorderdetail.Description = "Setup charge";
                    //purchaseorderdetail.Quantity = 0;
                    //purchaseorderdetail.UnitPrice = dSetupCharge;
                    //purchaseorderdetail.Tax = 0;

                    //nItemPosition++;
                    //purchaseorderdetail.ItemPosition = nItemPosition;
                    //purchaseorderdetail.ItemOrder = 0;

                    //db.PurchasOrderDetails.Add(purchaseorderdetail);

                    //purchaseorderdetail = new PurchasOrderDetail();
                    //purchaseorderdetail.PurchaseOrderId = nPurchaseOrderId;
                    //purchaseorderdetail.ItemID = szItemId;
                    //purchaseorderdetail.Description = "Run charge";
                    //purchaseorderdetail.Quantity = 0;
                    //purchaseorderdetail.UnitPrice = dRunCharge;
                    //purchaseorderdetail.Tax = 0;

                    //nItemPosition++;
                    //purchaseorderdetail.ItemPosition = nItemPosition;
                    //purchaseorderdetail.ItemOrder = 0;

                    //db.PurchasOrderDetails.Add(purchaseorderdetail);

                    db.SaveChanges();
                }

                //Get the dropdown data

                qryTrade = db.Trades.OrderBy(trd => trd.TradeName);
                if (qryTrade.Count() > 0)
                {
                    foreach (var item in qryTrade)
                    {
                        listSelector.Add(new KeyValuePair<string, string>(item.TradeId.ToString(), item.TradeName));
                    }
                }
                SelectList tradeselectorlist = new SelectList(listSelector, "Key", "Value");
                ViewBag.TradeList = tradeselectorlist;

                return RedirectToAction("Edit", new { id = purchaseorders.PurchaseOrderId });
                //return RedirectToAction("Index");
            }

            return View(purchaseorders);
        }
        //
        // GET: /Invoice/UpdateDetail
        public ActionResult UpdateDetail(int? id, string salesorderid, string qty, string shipqty, string boqty, string desc, string price, string tax,
            string logo, string imprt, string qtysc, string qtyrc, string pricesc, string pricerc)
        {
            double dHlp = 0;
            decimal dcHlp = 0;
            decimal dcHlp1 = 0;
            double dTaxRate = 0;
            int nSalesOrderId = Convert.ToInt32(salesorderid);
            int nPriceId = 0;
            string szSalesOrder = "";
            string szSalesOredidHlp = "";
            string szSalesOrderIdHlp = "";
            string szItemIdHlp = "";

            PurchasOrderDetail sodetail = db.PurchasOrderDetails.Find(id);
            PurchasOrderDetail setupcharge = null;
            PurchasOrderDetail runcharge = null;

            PRICE price01 = null;
            IQueryable<PRICE> qryPrice = null;

            List<KeyValuePair<double, int>> qtyprcList = new List<KeyValuePair<double, int>>();

            if (sodetail != null)
            {
                //
                // Get the price and qty list for this item
                qryPrice = db.PRICEs.Where(prc => prc.Item == sodetail.ItemID).OrderBy(prc => prc.Qty);
                if (qryPrice.Count() > 0)
                {
                    foreach (var item in qryPrice)
                    {
                        qtyprcList.Add(new KeyValuePair<double, int>(item.Qty, item.Id));
                    }
                }

                sodetail.Description = desc;
                sodetail.Logo = logo;
                sodetail.ImprintMethod = imprt;

                if (!string.IsNullOrEmpty(qty))
                {
                    dHlp = Convert.ToDouble(qty);
                    sodetail.Quantity = dHlp;
                }
                //if (!string.IsNullOrEmpty(shipqty))
                //{
                //    dHlp = Convert.ToDouble(shipqty);
                //    sodetail.ShipQuantity = dHlp;
                //}
                //if (!string.IsNullOrEmpty(boqty))
                //{
                //    dHlp = Convert.ToDouble(boqty);
                //    sodetail.BackOrderQuantity = dHlp;
                //}
                if (!string.IsNullOrEmpty(tax))
                {
                    dHlp = Convert.ToDouble(tax);
                    sodetail.Tax = dHlp;
                }
                if (!string.IsNullOrEmpty(price))
                {
                    price = price.Replace("$", "");
                    price = price.Replace(",", "");
                    dcHlp = Convert.ToDecimal(price);
                    sodetail.UnitPrice = dcHlp;

                    //Set the price according with the Quantity
                    for (int i = 0; i < qtyprcList.Count; i++)
                    {
                        if (i == 0)
                        {
                            if (sodetail.Quantity <= qtyprcList[i].Key)
                            {
                                nPriceId = qtyprcList[i].Value;
                            }
                            else
                            {
                                if (sodetail.Quantity >= qtyprcList[i].Key && sodetail.Quantity < qtyprcList[i + 1].Key)
                                {
                                    nPriceId = qtyprcList[i + 1].Value;
                                }
                            }
                        }
                        else
                        {
                            if (i == qtyprcList.Count - 1)
                            {
                                if (sodetail.Quantity > qtyprcList[i].Key)
                                {
                                    nPriceId = qtyprcList[i].Value;

                                }
                            }
                            else
                            {
                                if (sodetail.Quantity >= qtyprcList[i].Key && sodetail.Quantity < qtyprcList[i + 1].Key)
                                {
                                    nPriceId = qtyprcList[i + 1].Value;
                                }
                            }
                        }
                    }
                    if (nPriceId > 0)
                    {
                        price01 = db.PRICEs.Find(nPriceId);
                        if (price01 != null)
                        {
                            double dDiscountPrc = TimelyDepotMVC.Controllers.InventoryController.GetDiscount(db, price01.Discount_Code);
                            sodetail.UnitPrice = price01.thePrice * (1 - Convert.ToDecimal(dDiscountPrc));
                        }
                    }

                }

                db.Entry(sodetail).State = EntityState.Modified;
                db.SaveChanges();

                //Update Set up Charge
                if (!string.IsNullOrEmpty(pricesc) && !string.IsNullOrEmpty(qtysc))
                {
                    szSalesOredidHlp = string.Format("Set up Charge {0} {1}", sodetail.PurchaseOrderId.ToString(), sodetail.ItemID);
                    setupcharge = db.PurchasOrderDetails.Where(spch => spch.PurchaseOrderId == sodetail.PurchaseOrderId && spch.Description == szSalesOredidHlp).FirstOrDefault<PurchasOrderDetail>();
                    if (setupcharge != null)
                    {
                        pricesc = pricesc.Replace("$", "");
                        pricesc = pricesc.Replace(",", "");
                        dcHlp = Convert.ToDecimal(pricesc);
                        setupcharge.UnitPrice = dcHlp;

                        qtysc = qtysc.Replace("$", "");
                        qtysc = qtysc.Replace(",", "");
                        dcHlp1 = Convert.ToDecimal(qtysc);
                        setupcharge.Quantity = Convert.ToDouble(dcHlp1);
                        db.Entry(setupcharge).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        pricesc = pricesc.Replace("$", "");
                        pricesc = pricesc.Replace(",", "");
                        dcHlp = Convert.ToDecimal(pricesc);
                        //setupcharge.UnitPrice = dcHlp;

                        qtysc = qtysc.Replace("$", "");
                        qtysc = qtysc.Replace(",", "");
                        dcHlp1 = Convert.ToDecimal(qtysc);

                        setupcharge = new PurchasOrderDetail();
                        setupcharge.PurchaseOrderId = nSalesOrderId;
                        setupcharge.ItemID = string.Empty;
                        setupcharge.Sub_ItemID = string.Empty;
                        setupcharge.Description = string.Format("Set up Charge {0} {1}", sodetail.PurchaseOrderId.ToString(), sodetail.ItemID);
                        setupcharge.Quantity = Convert.ToDouble(dcHlp1);
                        //setupcharge.ShipQuantity = 0;
                        //setupcharge.BackOrderQuantity = 0;
                        setupcharge.Tax = 0;
                        setupcharge.UnitPrice = dcHlp;
                        setupcharge.ItemPosition = 0;
                        setupcharge.ItemOrder = 0;
                        setupcharge.Tax = Convert.ToDouble(dTaxRate);
                        db.PurchasOrderDetails.Add(setupcharge);
                        db.SaveChanges();
                    }
                }

                //Update Run Charge
                if (!string.IsNullOrEmpty(pricesc) && !string.IsNullOrEmpty(qtysc))
                {
                    szSalesOredidHlp = string.Format("Run Charge {0} {1}", sodetail.PurchaseOrderId.ToString(), sodetail.ItemID);
                    runcharge = db.PurchasOrderDetails.Where(spch => spch.PurchaseOrderId == sodetail.PurchaseOrderId && spch.Description == szSalesOredidHlp).FirstOrDefault<PurchasOrderDetail>();
                    if (runcharge != null)
                    {
                        pricerc = pricerc.Replace("$", "");
                        pricerc = pricerc.Replace(",", "");
                        dcHlp = Convert.ToDecimal(pricerc);
                        runcharge.UnitPrice = dcHlp;

                        qtyrc = qtyrc.Replace("$", "");
                        qtyrc = qtyrc.Replace(",", "");
                        dcHlp1 = Convert.ToDecimal(qtyrc);
                        runcharge.Quantity = Convert.ToDouble(dcHlp1);
                        db.Entry(runcharge).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        pricerc = pricerc.Replace("$", "");
                        pricerc = pricerc.Replace(",", "");
                        dcHlp = Convert.ToDecimal(pricerc);
                        //runcharge.UnitPrice = dcHlp;

                        qtyrc = qtyrc.Replace("$", "");
                        qtyrc = qtyrc.Replace(",", "");
                        dcHlp1 = Convert.ToDecimal(qtyrc);

                        runcharge = new PurchasOrderDetail();
                        runcharge.PurchaseOrderId = nSalesOrderId;
                        runcharge.ItemID = string.Empty;
                        runcharge.Sub_ItemID = string.Empty;
                        runcharge.Description = string.Format("Run Charge {0} {1}", sodetail.PurchaseOrderId.ToString(), sodetail.ItemID);
                        runcharge.Quantity = Convert.ToDouble(dcHlp1);
                        //runcharge.ShipQuantity = 0;
                        //runcharge.BackOrderQuantity = 0;
                        runcharge.Tax = 0;
                        runcharge.UnitPrice = dcHlp;
                        runcharge.ItemPosition = 0;
                        runcharge.ItemOrder = 0;
                        runcharge.Tax = Convert.ToDouble(dTaxRate);
                        db.PurchasOrderDetails.Add(runcharge);
                        db.SaveChanges();
                    }
                }
            }

            return RedirectToAction("Edit", new { id = nSalesOrderId });
        }
        public ActionResult AddPurchaseOrderDetails(string itemOrder, int id = 0, int purchaseorderid = 0, int itemPos = 0)
        {
            double nItemOrder = 0;
            int nitemPosNext = 0;
            int nItemPos = 0;
            int nCurrentItemPos = 0;
            int nNextItemPos = 0;
            double dItemOrder = 0;
            double dCurrentItemOrder = 0;
            double dNextItemOrder = 0;
            double dQty = 0;
            decimal dPrice = 0;
            string szCurentItemId = "";
            string szNextItemId = "";
            PurchasOrderDetail salesdetail = null;
            PurchasOrderDetail salesdetailcurrent = null;
            PurchasOrderDetail salesdetailnext = null;

            IQueryable<PRICE> qryPrice = null;

            TimelyDepotContext db01 = new TimelyDepotContext();

            SUB_ITEM subitem = db.SUB_ITEM.Find(id);
            if (subitem != null)
            {
                if (!string.IsNullOrEmpty(itemOrder))
                {
                    //itemOrder = itemOrder.Replace(".", ",");
                    nItemOrder = Convert.ToDouble(itemOrder);
                }

                //Get the current salesorderdetail
                salesdetailcurrent = db.PurchasOrderDetails.Where(sldt => sldt.PurchaseOrderId == purchaseorderid && sldt.ItemPosition == itemPos && sldt.ItemOrder == nItemOrder).FirstOrDefault<PurchasOrderDetail>();
                if (salesdetailcurrent != null)
                {
                    nCurrentItemPos = Convert.ToInt32(salesdetailcurrent.ItemPosition);
                    dCurrentItemOrder = Convert.ToDouble(salesdetailcurrent.ItemOrder);
                    szCurentItemId = salesdetailcurrent.ItemID;
                }

                //Get the next salesorderdetail
                salesdetailnext = db.PurchasOrderDetails.Where(sldt => sldt.PurchaseOrderId == purchaseorderid && sldt.ItemPosition == nCurrentItemPos && sldt.ItemOrder > dCurrentItemOrder).OrderBy(sldt => sldt.ItemOrder).FirstOrDefault<PurchasOrderDetail>();
                if (salesdetailnext != null)
                {
                    nNextItemPos = Convert.ToInt32(salesdetailnext.ItemPosition);
                    szNextItemId = salesdetailnext.ItemID;
                    dNextItemOrder = Convert.ToDouble(salesdetailnext.ItemOrder);
                }

                if (subitem.ItemID == szNextItemId)
                {
                    nItemPos = nCurrentItemPos;
                    dItemOrder = (dCurrentItemOrder + dNextItemOrder) / 2;
                }
                else
                {
                    nItemPos = nCurrentItemPos;
                    dItemOrder = dCurrentItemOrder + 1;
                }

                //
                // Set the price and qty search to the lowest price for this item
                double dDiscountPrc = 0;
                qryPrice = db.PRICEs.Where(prc => prc.Item == subitem.ItemID).OrderBy(prc => prc.Qty);
                if (qryPrice.Count() > 0)
                {
                    foreach (var item in qryPrice)
                    {
                        dQty = item.Qty;
                        dPrice = item.thePrice;
                        dDiscountPrc = TimelyDepotMVC.Controllers.InventoryController.GetDiscount(db01, item.Discount_Code);
                        break;
                    }
                }

                salesdetail = new PurchasOrderDetail();
                salesdetail.PurchaseOrderId = purchaseorderid;
                salesdetail.ItemID = subitem.ItemID;
                salesdetail.Sub_ItemID = subitem.Sub_ItemID;
                //salesdetail.BackOrderQuantity = 0;
                salesdetail.Description = subitem.Description;
                salesdetail.Quantity = dQty;
                //salesdetail.ShipQuantity = 0;
                salesdetail.Tax = 0;
                salesdetail.UnitPrice = dPrice * (1 - Convert.ToDecimal(dDiscountPrc));
                salesdetail.ItemPosition = nItemPos;
                salesdetail.ItemOrder = dItemOrder;
                db.PurchasOrderDetails.Add(salesdetail);
                db.SaveChanges();
            }

            return RedirectToAction("Edit", new { id = purchaseorderid });
        }
        //
        // GET: /PurchaseOrder/InsertItem
        public ActionResult InsertItem(string purchaseorderid, string itemOrder, int itemPos = 0)
        {
            double nItemOrder = 0;
            int nitemPosNext = 0;
            int nItemPos = 0;
            int nCurrentItemPos = 0;
            int nNextItemPos = 0;
            double dItemOrder = 0;
            double dCurrentItemOrder = 0;
            double dNextItemOrder = 0;
            string szCurentItemId = "";
            string szNextItemId = "";
            PurchasOrderDetail salesdetailcurrent = null;
            PurchasOrderDetail salesdetailnext = null;

            int nSalesOrderId = Convert.ToInt32(purchaseorderid);

            if (!string.IsNullOrEmpty(itemOrder))
            {
                //itemOrder = itemOrder.Replace(".", ",");
                nItemOrder = Convert.ToDouble(itemOrder);
            }

            //Get the current salesorderdetail
            salesdetailcurrent = db.PurchasOrderDetails.Where(sldt => sldt.PurchaseOrderId == nSalesOrderId && sldt.ItemPosition == itemPos && sldt.ItemOrder == nItemOrder).FirstOrDefault<PurchasOrderDetail>();
            if (salesdetailcurrent != null)
            {
                nCurrentItemPos = Convert.ToInt32(salesdetailcurrent.ItemPosition);
                dCurrentItemOrder = Convert.ToDouble(salesdetailcurrent.ItemOrder);
                szCurentItemId = salesdetailcurrent.ItemID;
            }

            //Get the next salesorderdetail
            salesdetailnext = db.PurchasOrderDetails.Where(sldt => sldt.PurchaseOrderId == nSalesOrderId && sldt.ItemPosition == nCurrentItemPos && sldt.ItemOrder > dCurrentItemOrder).OrderBy(sldt => sldt.ItemOrder).FirstOrDefault<PurchasOrderDetail>();
            if (salesdetailnext != null)
            {
                nNextItemPos = Convert.ToInt32(salesdetailnext.ItemPosition);
                szNextItemId = salesdetailnext.ItemID;
                dNextItemOrder = Convert.ToDouble(salesdetailnext.ItemOrder);

                nItemPos = nCurrentItemPos;
                dItemOrder = (dCurrentItemOrder + dNextItemOrder) / 2;
            }
            else
            {
                nItemPos = nCurrentItemPos;
                dItemOrder = dCurrentItemOrder + 1;
            }

            //if (subitem.ItemID == szNextItemId)
            //{
            //    nItemPos = nCurrentItemPos;
            //    dItemOrder = (dCurrentItemOrder + dNextItemOrder) / 2;
            //}
            //else
            //{
            //    nItemPos = nCurrentItemPos;
            //    dItemOrder = dCurrentItemOrder + 1;
            //}

            PurchasOrderDetail salesdetail = null;

            salesdetail = new PurchasOrderDetail();
            salesdetail.PurchaseOrderId = nSalesOrderId;
            salesdetail.ItemID = string.Empty;
            salesdetail.Sub_ItemID = string.Empty;
            //salesdetail.BackOrderQuantity = 0;
            salesdetail.Description = string.Empty;
            salesdetail.Quantity = 0;
            //salesdetail.ShipQuantity = 0;
            salesdetail.Tax = 0;
            salesdetail.UnitPrice = 0;
            salesdetail.ItemPosition = nItemPos;
            salesdetail.ItemOrder = dItemOrder;
            db.PurchasOrderDetails.Add(salesdetail);
            db.SaveChanges();

            return RedirectToAction("Edit", new { id = nSalesOrderId });
        }
 public ActionResult Edit(PurchasOrderDetail purchasorderdetail)
 {
     if (ModelState.IsValid)
     {
         db.Entry(purchasorderdetail).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(purchasorderdetail);
 }