public ActionResult Create(InvoiceDetail invoicedetail)
        {
            if (ModelState.IsValid)
            {
                db.InvoiceDetails.Add(invoicedetail);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(invoicedetail);
        }
        //
        // GET: //GenerateInvoice
        public ActionResult GenerateInvoice(int id = 0)
        {
            int nInvoiceNo = 0;
            int nTrackingNo = 0;
            int nPos = -1;
            double dTax = 0;
            string szMsg = "";
            string[] szHlp = null;
            InitialInfo initialinfo = null;
            Invoice invoice = null;
            InvoiceDetail invoicedetail = null;

            TimelyDepotContext db01 = new TimelyDepotContext();

            IQueryable<SalesOrderDetail> qrySODetails = null;

            SalesOrder salesorder = db.SalesOrders.Find(id);
            if (salesorder != null)
            {
                //Get the next payment No
                initialinfo = db.InitialInfoes.FirstOrDefault<InitialInfo>();
                if (initialinfo == null)
                {
                    initialinfo = new InitialInfo();
                    initialinfo.InvoiceNo = 1;
                    initialinfo.PaymentNo = 0;
                    initialinfo.PurchaseOrderNo = 0;
                    initialinfo.SalesOrderNo = 0;
                    initialinfo.TaxRate = 0;
                    initialinfo.TrackingNo = 1;
                    db.InitialInfoes.Add(initialinfo);
                }
                else
                {
                    nInvoiceNo = initialinfo.InvoiceNo;
                    nInvoiceNo++;
                    initialinfo.InvoiceNo = nInvoiceNo;
                    nTrackingNo = Convert.ToInt32(initialinfo.TrackingNo);
                    nTrackingNo++;
                    initialinfo.TrackingNo = nTrackingNo;
                    dTax = initialinfo.TaxRate;
                    db.Entry(initialinfo).State = EntityState.Modified;
                }

                //Use the sales order tax information
                if (salesorder.Tax_rate != null)
                {
                    if (Convert.ToDecimal(salesorder.Tax_rate) >= 0)
                    {
                        dTax = Convert.ToDouble(salesorder.Tax_rate);
                    }
                }

                //Create the Invoice
                invoice = new Invoice();
                invoice.InvoiceNo = nInvoiceNo.ToString();
                invoice.CustomerId = salesorder.CustomerId;
                invoice.BussinesType = salesorder.BussinesType;
                invoice.CreaditCardNo = salesorder.CreaditCardNo;
                invoice.CustomerShipLocation = salesorder.CustomerShipLocation;
                invoice.CustomerShiptoId = salesorder.CustomerShiptoId;
                //invoice.InvoiceDate = DateTime.Now;
                invoice.InvoiceDate = Convert.ToDateTime(salesorder.SODate);
                invoice.IsBlindShip = salesorder.IsBlindShip;
                invoice.Note = salesorder.Note;
                invoice.PaymentAmount = salesorder.PaymentAmount;
                invoice.PaymentDate = salesorder.PaymentDate;
                invoice.PaymentTerms = salesorder.PaymentTerms;
                invoice.PurchaseOrderNo = salesorder.PurchaseOrderNo;
                invoice.SalesOrderId = salesorder.SalesOrderId;
                invoice.SalesOrderNo = salesorder.SalesOrderNo;
                invoice.SalesRep = salesorder.SalesRep;
                invoice.ShipDate = salesorder.ShipDate;
                invoice.ShippingHandling = salesorder.ShippingHandling;
                invoice.ShipVia = salesorder.ShipVia;
                invoice.TrackingNo = nTrackingNo.ToString();
                invoice.TradeId = salesorder.TradeId;
                invoice.VendorAddress = salesorder.VendorAddress;
                invoice.VendorId = salesorder.VendorId;
                invoice.Tax_rate = Convert.ToDecimal(dTax);
                invoice.Invs_Tax = Convert.ToDecimal(dTax);

                //Set the shipment information
                invoice.FromAddress1 = salesorder.FromAddress1;
                invoice.FromAddress2 = salesorder.FromAddress2;
                invoice.FromCity = salesorder.FromCity;
                invoice.FromCompany = salesorder.FromCompany;
                invoice.FromCountry = salesorder.FromCountry;
                invoice.FromEmail = salesorder.FromEmail;
                invoice.FromFax = salesorder.FromFax;
                invoice.FromName = salesorder.FromName;
                invoice.FromState = salesorder.FromState;
                invoice.FromTel = salesorder.FromTel;
                invoice.FromTitle = salesorder.FromTitle;
                invoice.FromZip = salesorder.FromZip;

                invoice.ToAddress1 = salesorder.ToAddress1;
                invoice.ToAddress2 = salesorder.ToAddress2;
                invoice.ToCity = salesorder.ToCity;
                invoice.ToCompany = salesorder.ToCompany;
                invoice.ToCountry = salesorder.ToCountry;
                invoice.ToEmail = salesorder.ToEmail;
                invoice.ToFax = salesorder.ToFax;
                invoice.ToName = salesorder.ToName;
                invoice.ToState = salesorder.ToState;
                invoice.ToTel = salesorder.ToTel;
                invoice.ToTitle = salesorder.ToTitle;
                invoice.ToZip = salesorder.ToZip;

                db.Invoices.Add(invoice);
                db.SaveChanges();

                //Create the details
                qrySODetails = db.SalesOrderDetails.Where(sodt => sodt.SalesOrderId == salesorder.SalesOrderId);
                if (qrySODetails.Count() > 0)
                {
                    foreach (var item in qrySODetails)
                    {
                        invoicedetail = new InvoiceDetail();
                        invoicedetail.BackOrderQuantity = 0;
                        invoicedetail.Description = item.Description;

                        nPos = -1;
                        nPos = item.Description.IndexOf("Set up Charge");
                        if (nPos != -1)
                        {
                            szHlp = item.Description.Split(' ');
                            szHlp[3] = invoice.InvoiceId.ToString();
                            szMsg = string.Format("{0} {1} {2} {3} {4}", szHlp[0], szHlp[1], szHlp[2], szHlp[3], szHlp[4]);
                            invoicedetail.Description = szMsg;
                        }

                        nPos = -1;
                        nPos = item.Description.IndexOf("Run Charge");
                        if (nPos != -1)
                        {
                            szHlp = item.Description.Split(' ');
                            szHlp[2] = invoice.InvoiceId.ToString();
                            szMsg = string.Format("{0} {1} {2} {3}", szHlp[0], szHlp[1], szHlp[2], szHlp[3]);
                            invoicedetail.Description = szMsg;
                        }

                        invoicedetail.InvoiceId = invoice.InvoiceId;
                        invoicedetail.ItemID = item.ItemID;
                        invoicedetail.ItemOrder = item.ItemOrder;
                        invoicedetail.ItemPosition = item.ItemPosition;
                        invoicedetail.Quantity = item.Quantity;
                        invoicedetail.ShipQuantity = item.Quantity;
                        invoicedetail.Sub_ItemID = item.Sub_ItemID;
                        invoicedetail.Tax = item.Tax;
                        invoicedetail.UnitPrice = item.UnitPrice;
                        invoicedetail.Tax = item.Tax;
                        db.InvoiceDetails.Add(invoicedetail);

                    }

                    db.SaveChanges();
                }

            }

            return RedirectToAction("Edit", new { id = invoice.InvoiceId });
        }
        //
        // 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, string shipment)
        {
            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 = "";

            InvoiceDetail sodetail = db.InvoiceDetails.Find(id);
            InvoiceDetail setupcharge = null;
            InvoiceDetail 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.InvoiceId.ToString(), sodetail.ItemID);
                    setupcharge = db.InvoiceDetails.Where(spch => spch.InvoiceId == sodetail.InvoiceId && spch.Description == szSalesOredidHlp).FirstOrDefault<InvoiceDetail>();
                    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 InvoiceDetail();
                        setupcharge.InvoiceId = nSalesOrderId;
                        setupcharge.ItemID = string.Empty;
                        setupcharge.Sub_ItemID = string.Empty;
                        setupcharge.Description = string.Format("Set up Charge {0} {1}", sodetail.InvoiceId.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.InvoiceDetails.Add(setupcharge);
                        db.SaveChanges();
                    }
                }

                //Update Run Charge
                if (!string.IsNullOrEmpty(pricesc) && !string.IsNullOrEmpty(qtysc))
                {
                    szSalesOredidHlp = string.Format("Run Charge {0} {1}", sodetail.InvoiceId.ToString(), sodetail.ItemID);
                    runcharge = db.InvoiceDetails.Where(spch => spch.InvoiceId == sodetail.InvoiceId && spch.Description == szSalesOredidHlp).FirstOrDefault<InvoiceDetail>();
                    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 InvoiceDetail();
                        runcharge.InvoiceId = nSalesOrderId;
                        runcharge.ItemID = string.Empty;
                        runcharge.Sub_ItemID = string.Empty;
                        runcharge.Description = string.Format("Run Charge {0} {1}", sodetail.InvoiceId.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.InvoiceDetails.Add(runcharge);
                        db.SaveChanges();
                    }
                }
            }

            if (!string.IsNullOrEmpty(shipment))
            {
                return RedirectToAction("Index", "Shipment", new { id = nSalesOrderId });
            }

            return RedirectToAction("Edit", new { id = nSalesOrderId });
        }
        public ActionResult AddSalesOrderDetails(string itemOrder, string shipment, int id = 0, int salesorderId = 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 = "";
            InvoiceDetail salesdetail = null;
            InvoiceDetail salesdetailcurrent = null;
            InvoiceDetail 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 invoicedetail
                salesdetailcurrent = db.InvoiceDetails.Where(sldt => sldt.InvoiceId == salesorderId && sldt.ItemPosition == itemPos && sldt.ItemOrder == nItemOrder).FirstOrDefault<InvoiceDetail>();
                if (salesdetailcurrent != null)
                {
                    nCurrentItemPos = Convert.ToInt32(salesdetailcurrent.ItemPosition);
                    dCurrentItemOrder = Convert.ToDouble(salesdetailcurrent.ItemOrder);
                    szCurentItemId = salesdetailcurrent.ItemID;
                }

                //Get the next salesorderdetail
                salesdetailnext = db.InvoiceDetails.Where(sldt => sldt.InvoiceId == salesorderId && sldt.ItemPosition == nCurrentItemPos && sldt.ItemOrder > dCurrentItemOrder).OrderBy(sldt => sldt.ItemOrder).FirstOrDefault<InvoiceDetail>();
                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 InvoiceDetail();
                salesdetail.InvoiceId = salesorderId;
                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.InvoiceDetails.Add(salesdetail);
                db.SaveChanges();
            }

            if (!string.IsNullOrEmpty(shipment))
            {
                return RedirectToAction("Index", "Shipment", new { id = salesorderId });
            }

            return RedirectToAction("Edit", new { id = salesorderId });
        }
        //
        // GET: /Invoice/InsertItem
        public ActionResult InsertItem(string salesorderid, 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 = "";
            InvoiceDetail salesdetailcurrent = null;
            InvoiceDetail salesdetailnext = null;

            int nSalesOrderId = Convert.ToInt32(salesorderid);

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

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

            //Get the next salesorderdetail
            salesdetailnext = db.InvoiceDetails.Where(sldt => sldt.InvoiceId == nSalesOrderId && sldt.ItemPosition == nCurrentItemPos && sldt.ItemOrder > dCurrentItemOrder).OrderBy(sldt => sldt.ItemOrder).FirstOrDefault<InvoiceDetail>();
            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;
            }

            InvoiceDetail salesdetail = null;

            salesdetail = new InvoiceDetail();
            salesdetail.InvoiceId = 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.InvoiceDetails.Add(salesdetail);
            db.SaveChanges();

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