public async Task<ActionResult> LoadDetailPurchaseReceive(string dataDetail, string act)
        {
            string[] data = dataDetail.Split('|');

            var model = new purchaseReceive();
            for (int i = 0; i < data.Count(); i++)
            {
                string[] value = data[i].Split(';');

                if (value[1].ToString() == "")
                    break;

                int t_productID = int.Parse(value[1].ToString());
                int t_qty = value[2].ToString() != "" ? Convert.ToInt32(value[2].ToString()) : 0;
                string t_remarks = value[3].ToString();

                var editor = new purchaseReceive.purchaseReceiveDetail()
                {
                    receiveNo = "",
                    productId = t_productID,
                    qty = t_qty,
                    remarks= t_remarks
                };
                model.detailPurchaseReceive.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPurchaseReceive.ToList();

            return PartialView("_PartialPageRCV1");
        }
        public void loadRCV(string receiveNo)
        {
            var detailRCV = db.purchaseOrderHeaders.AsNoTracking()
                                .Join(db.vendors, a => a.vendorId, b => b.vendorID, (a, b) => new { a, b })
                                .Join(db.purchaseReceives.Where(x=>x.receiveNo == receiveNo), c => c.a.poId, d => d.poId, (c, d) => new { c, d})
                                .Select(e => new { e.c.a.poId, e.c.a.poDate, e.c.b.vendorID, e.c.b.vendorName, e.c.a.poUrgent, e.d.proposedBy }).ToList();
            var userId = "";
            var poId = "";
            for (int i = 0; i < detailRCV.Count; i++)
            {
                ViewBag.vendorId = detailRCV[i].vendorID;
                ViewBag.vendorName = detailRCV[i].vendorName;
                userId = detailRCV[i].proposedBy;
                poId = detailRCV[i].poId;
            }


            var aa = db.purchaseReceives.Where(x => x.receiveNo == "RCV").ToList();
            ViewBag.dataDetailSaved = db.purchaseReceiveDetails.Where(x => x.receiveNo == receiveNo).ToList();
            ViewBag.dataDetailReturnSaved = db.purchaseReturnDetails.Where(x => x.receiveNo == receiveNo).ToList();
            ViewBag.userName = ccm.getUserName(userId);

            var z = db.purchaseOrderDetails.Where(x => x.poId == poId)
                    .Join(db.purchaseOrderHeaders, a => a.poId, b => b.poId, (a, b) => new { a, b })
                    .Join(db.purchaseRequestDetails, c => c.b.prId, d => d.prId, (c, d) => new { c, d })
                    .Where(e => e.c.a.productID == e.d.productId)
                    .Select(y => new { y.c.a.poId, y.c.a.productID, y.d.description, y.c.a.qty, y.d.unit }).ToList();

            var model = new purchaseReceive();
            for (int i = 0; i < z.Count; i++)
            {
                var editor = new purchaseReceive.poReceive()
                {
                    productId = z[i].productID,
                    productDesc = z[i].description,
                    qtyOrder = z[i].qty,
                    unit = z[i].unit
                };
                model.detailPoReceive.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPoReceive.ToList();
        }
        public ActionResult Create(purchaseReceive purchasereceive)
        {
            if (acm.cekSession() == false)
                return RedirectToAction("Logout", "Account");

            lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
            if (acm.cekValidation(Url.Action().ToString()) == false && lvm.isAdmin == false)
                return RedirectToAction("NotAuthorized", "Account", new { menu = Url.Action().ToString() });

            var z = db.purchaseOrderDetails.Where(x => x.poId == purchasereceive.poId)
                    .Join(db.purchaseOrderHeaders, a => a.poId, b => b.poId, (a, b) => new { a, b })
                    .Join(db.purchaseRequestDetails, c => c.b.prId, d => d.prId, (c, d) => new { c, d })
                    .Where(e => e.c.a.productID == e.d.productId)
                    .Select(y => new { y.c.a.poId, y.c.a.productID, y.d.description, y.c.a.qty, y.d.unit }).ToList();

            var model = new purchaseReceive();
            for (int i = 0; i < z.Count; i++)
            {
                var editor = new purchaseReceive.poReceive()
                {
                    productId = z[i].productID,
                    productDesc = z[i].description,
                    qtyOrder = z[i].qty,
                    unit = z[i].unit
                };
                model.detailPoReceive.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPoReceive.ToList();

            if (ModelState.IsValid)
            {
                var countChk = 0;
                bool isProposed = false;
                for (int i = 0; i < Request.Form.Count; i++)
                {
                    if (Request.Form.AllKeys.ToList()[i].Contains("txtProductID_"))
                        countChk++;
                    else if (Request.Form.AllKeys.ToList()[i].Contains("hdnTypeSubmit"))
                        if (Request.Form["hdnTypeSubmit"].ToString() == "requested")
                            isProposed = true;
                }

                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        string generateID = prefix + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
                        var prIDCreated = db.purchaseReceives.Where(x => x.receiveNo.Contains(generateID)).OrderByDescending(x => x.createdDate).Select(x => x.poId).ToList();
                        if (prIDCreated.Count == 0)
                        {
                            generateID = generateID + "0001";
                        }
                        else
                        {
                            generateID = generateID + (Convert.ToInt32(prIDCreated[0].Substring((prIDCreated[0].Length - 4))) + 1).ToString().PadLeft(4, '0');
                        }

                        purchasereceive.receiveNo = generateID;
                        lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
                        purchasereceive.createdUser = lvm.userID;
                        purchasereceive.createdDate = DateTime.Now;
                        purchasereceive.proposedBy = lvm.userID;
                        purchasereceive.proposedDate = DateTime.Now;
                        purchasereceive.proposedStatus = isProposed;
                        db.purchaseReceives.Add(purchasereceive);

                        List<string> listProductId = new List<string>();
                        List<int> listReceive = new List<int>();
                        #region insertDetail
                        for (int i = 1; i <= countChk; i++)
                        {
                            var colVal = Request.Form["txtProductID_" + i];
                            if (colVal == "")
                                break;

                            int t_productID = int.Parse(Request.Form["txtProductID_" + i].ToString());
                            int t_qtyReceive = Request.Form["txtQtyReceive_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReceive_" + i].ToString().Replace('.', ',')) : 0;
                            int t_qtyReturn = Request.Form["txtQtyReturn_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReturn_" + i].ToString().Replace('.', ',')) : 0;
                            listProductId.Add(t_productID.ToString());
                            listReceive.Add(t_qtyReceive);

                            if (t_qtyReceive > 0)
                            {
                                var editorx = new purchaseReceive.purchaseReceiveDetail()
                                {
                                    receiveNo = purchasereceive.receiveNo,
                                    productId = t_productID,
                                    qty = t_qtyReceive
                                };
                                db.purchaseReceiveDetails.Add(editorx);
                            }

                            if (t_qtyReturn > 0)
                            {
                                var editory = new purchaseReceive.purchaseReturnDetail()
                                {
                                    receiveNo = purchasereceive.receiveNo,
                                    productId = t_productID,
                                    qty = t_qtyReturn
                                };
                                db.purchaseReturnDetails.Add(editory);
                            }
                        }
                        #endregion

                        if(isProposed == true)
                        { 
                            #region createInvoice
                            PurchaseInvoiceController pIv = new PurchaseInvoiceController();
                            string prefixInvoice = pIv.prefix;
                            string generateIDInvoice = prefixInvoice + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
                            string generateIDInvoiceSequence = "";
                            var invIDCreated = db.purchaseInvoices.Where(x => x.purchaseInvoiceNo.Contains(generateIDInvoice)).OrderByDescending(x => x.createdDate).Select(x => x.purchaseInvoiceNo).ToList();
                            if (invIDCreated.Count == 0)
                            {
                                generateIDInvoiceSequence = generateIDInvoice + "0001";
                            }
                            else
                            {
                                generateIDInvoiceSequence = generateIDInvoice + (Convert.ToInt32(invIDCreated[0].Substring((invIDCreated[0].Length - 4))) + 1).ToString().PadLeft(4, '0');
                            }

                            var headerPO = db.purchaseOrderHeaders.Where(x => x.poId == purchasereceive.poId).ToList();
                            var topPOMultiple = db.purchaseOrderTOPs.Where(x => x.poId == purchasereceive.poId).ToList();

                            purchaseInvoice purchaseinvoice = new purchaseInvoice();
                            purchaseinvoice.invoiceDate = purchasereceive.proposedDate;
                            purchaseinvoice.receiveNo = purchasereceive.receiveNo;
                            purchaseinvoice.createdUser = purchasereceive.proposedBy;
                            purchaseinvoice.createdDate = purchasereceive.proposedDate;
                            purchaseinvoice.remarks = purchasereceive.remarks;

                            if (headerPO[0].topType == "Single")
                            {
                                purchaseinvoice.purchaseInvoiceNo = generateIDInvoiceSequence;
                                purchaseinvoice.dueDate = purchasereceive.proposedDate.AddDays(headerPO[0].topAmount);

                                decimal total = 0;
                                for (int i = 1; i <= countChk; i++)
                                {
                                    var colVal = Request.Form["txtProductID_" + i];
                                    if (colVal == "")
                                        break;

                                    int t_productID = int.Parse(Request.Form["txtProductID_" + i].ToString());
                                    int t_qtyReceive = Request.Form["txtQtyReceive_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReceive_" + i].ToString().Replace('.', ',')) : 0;
                                    int t_qtyReturn = Request.Form["txtQtyReturn_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReturn_" + i].ToString().Replace('.', ',')) : 0;
                            
                                    var poInfo = db.purchaseOrderDetails.Where(x => x.poId == purchasereceive.poId && x.productID == t_productID).ToList();
                                    foreach (var ax in poInfo as IEnumerable<purchaseOrderHeader.purchaseOrderDetail>)
                                    {
                                        total += ((t_qtyReceive * ax.price) - (((t_qtyReceive * ax.price) * ax.disc) / 100));
                                    }
                                }

                                var poInfoH = db.purchaseOrderHeaders.Where(x => x.poId == purchasereceive.poId).ToList();
                                foreach (var axH in poInfoH as IEnumerable<purchaseOrderHeader>)
                                {
                                    total = (total - ((total * axH.disc) / 100));
                                    total = (total + ((total * axH.ppn) / 100));
                                }
                                purchaseinvoice.total = total;

                                db.purchaseInvoices.Add(purchaseinvoice);
                            }
                            else if (headerPO[0].topType == "Multiple")
                            {
                                for (int a = 0; a < topPOMultiple.Count; a++)
                                {
                                    purchaseinvoice.purchaseInvoiceNo = generateIDInvoiceSequence;
                                    purchaseinvoice.dueDate = topPOMultiple[a].buyDate;
                                    int prodId = int.Parse(listProductId[0]);
                                    var poInfo = db.purchaseOrderDetails.Where(x => x.poId == purchasereceive.poId && x.productID == prodId).ToList();
                                    decimal total = ((poInfo[0].qty * poInfo[0].price) - ((poInfo[0].qty * poInfo[0].price) / 100));
                                    purchaseinvoice.total = total;
                                    db.purchaseInvoices.Add(purchaseinvoice);

                                    generateIDInvoiceSequence = generateIDInvoice + (Convert.ToInt32(generateIDInvoiceSequence.Substring((generateIDInvoiceSequence.Length - 4))) + 1).ToString().PadLeft(4, '0');
                                }
                                db.purchaseInvoices.Add(purchaseinvoice);
                            }
                            #endregion
                        }

                        db.SaveChanges();
                        ts.Complete();
                    }
                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    string a = exc.Message;
                }
            }

            return View(purchasereceive);
        }
        public ActionResult Edit(purchaseReceive purchasereceive)
        {
            if (acm.cekSession() == false)
                return RedirectToAction("Logout", "Account");

            lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
            if (acm.cekValidation(Url.Action().ToString()) == false && lvm.isAdmin == false)
                return RedirectToAction("NotAuthorized", "Account", new { menu = Url.Action().ToString() });

            if (ModelState.IsValid)
            {
                var countChk = 0;
                bool isProposed = false;
                for (int i = 0; i < Request.Form.Count; i++)
                {
                    if (Request.Form.AllKeys.ToList()[i].Contains("txtProductID_"))
                        countChk++;
                    else if (Request.Form.AllKeys.ToList()[i].Contains("hdnTypeSubmit"))
                        if (Request.Form["hdnTypeSubmit"].ToString() == "requested")
                            isProposed = true;
                }

                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
                        purchasereceive.modifiedUser = lvm.userID;
                        purchasereceive.modifiedDate = DateTime.Now;
                        purchasereceive.proposedStatus = isProposed;
                        db.Entry(purchasereceive).State = EntityState.Modified;

                        List<string> listProductId = new List<string>();
                        #region insertDetail
                        bool runFirst = true;
                        for (int i = 1; i <= countChk; i++)
                        {
                            if (runFirst == true)
                            {
                                db.purchaseReceiveDetails.RemoveRange(db.purchaseReceiveDetails.Where(x => x.receiveNo == purchasereceive.receiveNo));
                                db.purchaseReturnDetails.RemoveRange(db.purchaseReturnDetails.Where(x => x.receiveNo == purchasereceive.receiveNo));
                                runFirst = false;
                            }

                            var colVal = Request.Form["txtProductID_" + i];
                            if (colVal == "")
                                break;

                            int t_productID = int.Parse(Request.Form["txtProductID_" + i].ToString());
                            int t_qtyReceive = Request.Form["txtQtyReceive_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReceive_" + i].ToString().Replace('.', ',')) : 0;
                            int t_qtyReturn = Request.Form["txtQtyReturn_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQtyReturn_" + i].ToString().Replace('.', ',')) : 0; 
                            listProductId.Add(t_productID.ToString());

                            if (t_qtyReceive > 0)
                            {
                                var editorx = new purchaseReceive.purchaseReceiveDetail()
                                {
                                    receiveNo = purchasereceive.receiveNo,
                                    productId = t_productID,
                                    qty = t_qtyReceive
                                };
                                db.purchaseReceiveDetails.Add(editorx);
                            }

                            if (t_qtyReturn > 0)
                            {
                                var editory = new purchaseReceive.purchaseReturnDetail()
                                {
                                    receiveNo = purchasereceive.receiveNo,
                                    productId = t_productID,
                                    qty = t_qtyReturn
                                };
                                db.purchaseReturnDetails.Add(editory);
                            }
                        }
                        #endregion

                        if (isProposed == true)
                        {
                            #region createInvoice
                            PurchaseInvoiceController pIv = new PurchaseInvoiceController();
                            string prefixInvoice = pIv.prefix;
                            string generateIDInvoice = prefixInvoice + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
                            string generateIDInvoiceSequence = "";
                            var invIDCreated = db.purchaseInvoices.Where(x => x.purchaseInvoiceNo.Contains(generateIDInvoice)).OrderByDescending(x => x.createdDate).Select(x => x.purchaseInvoiceNo).ToList();
                            if (invIDCreated.Count == 0)
                            {
                                generateIDInvoiceSequence = generateIDInvoice + "0001";
                            }
                            else
                            {
                                generateIDInvoiceSequence = generateIDInvoice + (Convert.ToInt32(invIDCreated[0].Substring((invIDCreated[0].Length - 4))) + 1).ToString().PadLeft(4, '0');
                            }

                            var headerPO = db.purchaseOrderHeaders.Where(x => x.poId == purchasereceive.poId).ToList();
                            var topPOMultiple = db.purchaseOrderTOPs.Where(x => x.poId == purchasereceive.poId).ToList();

                            purchaseInvoice purchaseinvoice = new purchaseInvoice();
                            purchaseinvoice.invoiceDate = purchasereceive.proposedDate;
                            purchaseinvoice.receiveNo = purchasereceive.receiveNo;
                            purchaseinvoice.createdUser = purchasereceive.proposedBy;
                            purchaseinvoice.createdDate = purchasereceive.proposedDate;

                            if (headerPO[0].topType == "Single")
                            {
                                purchaseinvoice.purchaseInvoiceNo = generateIDInvoiceSequence;
                                purchaseinvoice.dueDate = purchasereceive.proposedDate.AddDays(headerPO[0].topAmount);
                                db.purchaseInvoices.Add(purchaseinvoice);
                            }
                            else if (headerPO[0].topType == "Multiple")
                            {
                                for (int a = 0; a < topPOMultiple.Count; a++)
                                {
                                    purchaseinvoice.purchaseInvoiceNo = generateIDInvoiceSequence;
                                    purchaseinvoice.dueDate = topPOMultiple[a].buyDate;
                                    int prodId = int.Parse(listProductId[0]);
                                    var poInfo = db.purchaseOrderDetails.Where(x => x.poId == purchasereceive.poId && x.productID == prodId).ToList();
                                    decimal total = ((poInfo[0].qty * poInfo[0].price) - ((poInfo[0].qty * poInfo[0].price) / 100));
                                    purchaseinvoice.total = total;
                                    db.purchaseInvoices.Add(purchaseinvoice);

                                    generateIDInvoiceSequence = generateIDInvoice + (Convert.ToInt32(generateIDInvoiceSequence.Substring((generateIDInvoiceSequence.Length - 4))) + 1).ToString().PadLeft(4, '0');
                                }
                                db.purchaseInvoices.Add(purchaseinvoice);
                            }
                            #endregion
                        }

                        db.SaveChanges();
                        ts.Complete();
                    }
                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    string a = exc.Message;
                }
            }
            return View(purchasereceive);
        }
        public async Task<ActionResult> LoadDetailPO(string poId)
        {
            var z = db.purchaseOrderDetails.Where(x => x.poId == poId)
                    .Join(db.purchaseOrderHeaders, a => a.poId, b => b.poId, (a, b) => new { a, b })
                    .Join(db.purchaseRequestDetails, c => c.b.prId, d => d.prId, (c, d) => new { c, d })
                    .Where(e=>e.c.a.productID == e.d.productId)
                    .Select(y => new { y.c.a.poId, y.c.a.productID, y.d.description, y.c.a.qty, y.d.unit }).ToList();
            
            var model = new purchaseReceive();
            for (int i = 0; i < z.Count; i++ )
            {
                var editor = new purchaseReceive.poReceive()
                {
                    productId = z[i].productID,
                    productDesc = z[i].description,
                    qtyOrder = z[i].qty,
                    unit = z[i].unit
                };
                model.detailPoReceive.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPoReceive.ToList();

            return PartialView("_PartialPageRCV-PO1");
        }