protected void loadDetail(string id, int deptId)
        {
            #region default header
            lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
            var usr = db.Users.Where(x => x.userID == lvm.userID).ToList();
            if(deptId == 0)
                deptId = usr[0].deptID;

            if (lvm.isAdmin == false)
                //ViewBag.Dept = new SelectList(db.departments.Where(x=>x.deptID==deptId).Select(x => new { x.deptID, x.deptName }).ToList(), "deptID", "deptName");
                ViewBag.Dept = new SelectList(db.divisis.Where(x => x.divisiID == deptId).Select(x => new { deptID = x.divisiID, deptName = x.divisiName }).ToList(), "deptID", "deptName");
            else
                //ViewBag.Dept = new SelectList(db.departments.Select(x => new { x.deptID, x.deptName }).ToList(), "deptID", "deptName");
                ViewBag.Dept = new SelectList(db.divisis.Select(x => new { deptID = x.divisiID, deptName = x.divisiName }).ToList(), "deptID", "deptName");
            #endregion

            var popUp = db.products.ToList();
            var modelProd = new product();
            if (popUp != null)
            {
                for (int i = 0; i < popUp.Count; i++ )
                {
                    var editor = new product.listProduct()
                    {
                        productID = popUp[i].productID,
                        productCode = popUp[i].productCode,
                        productName = popUp[i].productName,
                        unit = popUp[i].unit
                    };
                    modelProd.productList.Add(editor);
                }
                ViewBag.ProductPopUp = modelProd.productList.ToList();
            }
            ViewBag.totalRows = popUp.Count;

            ViewBag.VendorPopUp = db.vendors.ToList();
            ViewBag.totalRowsVendor = db.vendors.Count();
            
            var prod = new product();
            foreach (var g in db.products.ToList() as IEnumerable<Models.product>)
            {
                var editor = new product.listProduct()
                {
                    productID = g.productID,
                    productCode = g.productCode,
                    productName = g.productName,
                    unit = g.unit,
                    createdUser = g.createdUser,
                    createdDate = g.createdDate,
                    modifiedUser = g.modifiedUser,
                    modifiedDate = g.modifiedDate
                };
                prod.productList.Add(editor);
            }

            if(id != string.Empty)
            {
                var model = new purchaseRequestHeader();
                var tempDetail = db.purchaseRequestDetails.Where(x => x.prId == id).ToList();
                foreach (var a in tempDetail)
                {
                    int t_productID = a.productId;
                    string t_description = a.description.ToString();
                    int t_qty = a.qty.ToString() != "" ? Convert.ToInt32(a.qty.ToString().Replace('.', ',')) : 0;
                    string t_unit = a.unit.ToString();
                    int? t_vendorid = a.vendorId;

                    var editor = new purchaseRequestHeader.purchaseRequestDetail()
                    {
                        productId = t_productID,
                        description = t_description,
                        qty = t_qty,
                        unit = t_unit,
                        vendorId = t_vendorid
                    };
                    model.detailPurchaseRequest.Add(editor);
                }
                ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();

                var g = db.products
                    .Join(db.purchaseRequestDetails.Where(x => x.prId == id), y => y.productID, z => z.productId, (y, z) => new { y })
                    .Select(c => new { c.y.productID, c.y.productCode, c.y.productName, c.y.unit, c.y.createdUser, c.y.createdDate, c.y.modifiedUser, c.y.modifiedDate }).ToList();

                prod.productList.Clear();
                for(int i=0; i<g.Count; i++)
                {
                    var editor = new product.listProduct()
                    {                        
                        productID = g[i].productID,
                        productCode = g[i].productCode,
                        productName = g[i].productName,
                        unit = g[i].unit,
                        createdUser = g[i].createdUser,
                        createdDate = g[i].createdDate,
                        modifiedUser = g[i].modifiedUser,
                        modifiedDate = g[i].modifiedDate
                    };
                    prod.productList.Add(editor);
                }
            }
            ViewBag.product = prod.productList.ToList();
        }
        public ActionResult Create(purchaseRequestHeader purchaserequest)
        {
            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() });

            ViewBag.Dept = new SelectList(db.departments.Select(x => new { x.deptID, x.deptName }).ToList(), "deptID", "deptName", purchaserequest.requestDeptId);
            if (ModelState.IsValid)
            {
                bool isProposed = false;
                #region collect detail purchase request
                var countChk = 0;
                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;
                }

                var model = new purchaseRequestHeader();
                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());
                    string t_description = Request.Form["txtDescription_" + i].ToString();
                    int t_qty = Request.Form["txtQty_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQty_" + i].ToString().Replace('.', ',')) : 0;
                    string t_unit = Request.Form["txtUnit_" + i].ToString();
                    int? t_vendorid = int.Parse(Request.Form["txtVendorID_" + i].ToString());

                    var editor = new purchaseRequestHeader.purchaseRequestDetail()
                    {
                        productId = t_productID,
                        description = t_description,
                        qty = t_qty,
                        unit = t_unit,
                        vendorId = t_vendorid
                    };
                    model.detailPurchaseRequest.Add(editor);
                }
                ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();
                #endregion 

                try
                {
                    using(TransactionScope ts = new TransactionScope())
                    {
                        string generateID = prefix + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
                        var prIDCreated = db.purchaseRequestHeaders.Where(x => x.prId.Contains(generateID)).OrderByDescending(x => x.createdDate).Select(x => x.prId).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');
                        }

                        lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
                        purchaserequest.prId = generateID;
                        purchaserequest.proposedBy = lvm.userID;
                        purchaserequest.proposedDate = DateTime.Now;
                        purchaserequest.proposedStatus = isProposed;
                        purchaserequest.createdUser = lvm.userID;
                        purchaserequest.createdDate = DateTime.Now;
                        db.purchaseRequestHeaders.Add(purchaserequest);
                        //db.SaveChanges();

                        #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());
                            string t_description = Request.Form["txtDescription_" + i].ToString();
                            int t_qty = Request.Form["txtQty_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQty_" + i].ToString().Replace('.', ',')) : 0;
                            string t_unit = Request.Form["txtUnit_" + i].ToString();
                            int? t_vendorid = int.Parse(Request.Form["txtVendorID_" + i].ToString());

                            var editor = new purchaseRequestHeader.purchaseRequestDetail()
                            {
                                prId = generateID,
                                productId = t_productID,
                                description = t_description,
                                qty = t_qty,
                                unit = t_unit,
                                vendorId = t_vendorid
                            };
                            db.purchaseRequestDetails.Add(editor);
                        }
                        #endregion

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

            return View(purchaserequest);
        }
        public ActionResult Edit(purchaseRequestHeader purchaserequest)
        {
            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() });

            ViewBag.Dept = new SelectList(db.departments.Select(x => new { x.deptID, x.deptName }).ToList(), "deptID", "deptName", purchaserequest.requestDeptId);
            if (ModelState.IsValid)
            {
                #region collect detail purchase request
                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;
                }

                var model = new purchaseRequestHeader();
                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());
                    string t_description = Request.Form["txtDescription_" + i].ToString();
                    int t_qty = Request.Form["txtQty_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQty_" + i].ToString().Replace('.', ',')) : 0;
                    string t_unit = Request.Form["txtUnit_" + i].ToString();
                    int? t_vendorid = int.Parse(Request.Form["txtVendorID_" + i].ToString());

                    var editor = new purchaseRequestHeader.purchaseRequestDetail()
                    {
                        productId = t_productID,
                        description = t_description,
                        qty = t_qty,
                        unit = t_unit,
                        vendorId = t_vendorid
                    };
                    model.detailPurchaseRequest.Add(editor);
                }
                ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();
                #endregion 

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

                        #region insertDetail
                        bool runFirst = true;
                        for (int i = 1; i <= countChk; i++)
                        {
                            if (runFirst == true)
                            {
                                db.purchaseRequestDetails.RemoveRange(db.purchaseRequestDetails.Where(x => x.prId == purchaserequest.prId));
                                runFirst = false;
                            }

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

                            int t_productID = int.Parse(Request.Form["txtProductID_" + i].ToString());
                            string t_description = Request.Form["txtDescription_" + i].ToString();
                            int t_qty = Request.Form["txtQty_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQty_" + i].ToString().Replace('.', ',')) : 0;
                            string t_unit = Request.Form["txtUnit_" + i].ToString();
                            int? t_vendorid = int.Parse(Request.Form["txtVendorID_" + i].ToString());

                            var editor = new purchaseRequestHeader.purchaseRequestDetail()
                            {
                                prId = purchaserequest.prId,
                                productId = t_productID,
                                description = t_description,
                                qty = t_qty,
                                unit = t_unit,
                                vendorId = t_vendorid
                            };
                            db.purchaseRequestDetails.Add(editor);
                        }
                        #endregion

                        db.SaveChanges();
                        ts.Complete();
                    }
                    return RedirectToAction("Index");
                }
                catch(Exception exc)
                {
                    string a = exc.Message;
                }
            }
            return View(purchaserequest);
        }
        public async Task<ActionResult> LoadDetailPurchaseRequest(string dataDetail, string act)
        {
            string[] data = dataDetail.Split('|');

            var model = new purchaseRequestHeader();
            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());
                string t_description = value[2].ToString();
                int t_qty = value[3].ToString() != "" ? Convert.ToInt32(value[3].ToString()) : 0;
                string t_unit = value[4].ToString();
                int? t_vendorid = int.Parse(value[5].ToString());

                var editor = new purchaseRequestHeader.purchaseRequestDetail()
                {
                    productId = t_productID,
                    description = t_description,
                    qty = t_qty,
                    unit = t_unit,
                    vendorId = t_vendorid
                };
                model.detailPurchaseRequest.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();
            loadDetail(string.Empty, 0);
            return PartialView("_PartialPagePR_Supplier1");
        }
        public void loadPO(string poId)
        {
            var detailPR = db.purchaseRequestHeaders.Where(x => x.proposedStatus == true && x.approvedStatus == true).AsNoTracking()
                               //.Join(db.departments, a => a.requestDeptId, b => b.deptID, (a, b) => new { a, b }) ~old process ~sweeping department kebalik dgn divisi
                               .Join(db.divisis, a => a.requestDeptId, b => b.divisiID, (a, b) => new { a, b })
                               .Join(db.purchaseOrderHeaders.Where(po=>po.poId == poId), e=>e.a.prId, d=>d.prId,(e,d) => new{d,e})
                               .Select(c => new { c.e.a.prId, c.e.a.requestDeptId, deptName = c.e.b.divisiName, c.e.a.typeOrder, c.e.a.proposalInclude, c.e.a.specialInstruction, c.e.a.projectTimeDelivery, c.d.vendorId }).ToList();
            var vendorId = "";
            //var model = new purchaseOrderHeader();
            for (int i = 0; i < detailPR.Count; i++)
            {
                //var editor = new purchaseOrderHeader.prPopUp()
                //{
                ViewBag.From = detailPR[i].deptName;
                ViewBag.poUrgent = detailPR[i].typeOrder;
                ViewBag.Proposal = detailPR[i].proposalInclude;
                ViewBag.Instruction = detailPR[i].specialInstruction;
                ViewBag.Delivery = detailPR[i].projectTimeDelivery;
                vendorId = detailPR[i].vendorId;
                //};
                //model.PopUpPR.Add(editor);
            }
            //ViewBag.PRPopUp = model.PopUpPR.ToList();

            var topMultipleSaved = db.purchaseOrderTOPs.AsNoTracking().Where(x => x.poId == poId).ToList();
            Session["topMultiple"] = topMultipleSaved;

            var poH = db.purchaseOrderHeaders.AsNoTracking().Where(x => x.poId == poId)
                                .Join(db.vendors, a => a.vendorId, b => b.vendorID, (a, b) => new { a, b }).ToList();
            
            string userId = string.Empty;
            string prId = string.Empty;
            for (int i = 0; i < poH.Count; i++)
            {
                ViewBag.vendorName = poH[i].b.vendorName;
                ViewBag.Address = poH[i].b.address1;
                ViewBag.Cp = poH[i].b.contactPerson;
                ViewBag.Telp = poH[i].b.telp;
                ViewData["topTypes"] = poH[i].a.topType;
                ViewBag.Disc = poH[i].a.disc;
                ViewBag.Ppn = poH[i].a.ppn;
                userId = poH[i].a.proposedBy;
                prId = poH[i].a.prId;
            }
            ViewBag.userName = ccm.getUserName(userId);

            #region oldProcess
            //var model = new purchaseRequestHeader();
            //foreach (var a in db.purchaseRequestDetails.Where(x => x.prId == prId).ToList() as IEnumerable<purchaseRequestHeader.purchaseRequestDetail>)
            //{
            //    var editor = new purchaseRequestHeader.purchaseRequestDetail()
            //    {
            //        productId = a.productId,
            //        description = a.description,
            //        qty = a.qty,
            //        unit = a.unit
            //    };
            //    model.detailPurchaseRequest.Add(editor);
            //}
            //ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();
            #endregion
            #region newProcess
            int id_vendor = 0;
            var ven = db.vendors.Where(x => x.vendorID == vendorId).ToList();
            if (ven.Count() > 0)
                id_vendor = ven[0].id;

            var model = new purchaseRequestHeader();
            string sql = "SELECT DISTINCT b.* ";
            sql += "FROM [dbo].[transVendorProducts] a ";
            sql += "INNER JOIN [dbo].[PurchaseRequestDetails] b ON b.productID = a.productID ";
            sql += "INNER JOIN [dbo].[Vendors] c ON c.id = a.id_vendor ";
            sql += "INNER JOIN (SELECT x.*, y.prId ";
            sql += "	FROM [dbo].[PurchaseOrderDetails] x ";
            sql += "	INNER JOIN [dbo].[PurchaseOrderHeaders] y ON y.poId = x.poId) d ON d.prId = b.prId AND d.productID = b.productID ";
            sql += "WHERE d.poId = '" + poId + "'";
            DataTable dtListAuthorize = con.executeReader(sql);
            foreach (DataRow dr in dtListAuthorize.Rows)
            {
                foreach (var b in db.transVendorProducts.Where(x => x.id_vendor == id_vendor).ToList() as IEnumerable<transVendorProduct>)
                {
                    if (b.productID == int.Parse(dr["productID"].ToString()))
                    {
                        var editor = new purchaseRequestHeader.purchaseRequestDetail()
                        {
                            productId = int.Parse(dr["productID"].ToString()),
                            description = dr["description"].ToString(),
                            qty = int.Parse(dr["qty"].ToString()),
                            unit = dr["unit"].ToString()
                        };
                        model.detailPurchaseRequest.Add(editor);
                        break;
                    }
                }
            }
            ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();
            #endregion
            ViewData["dataDetailSaved"] = db.purchaseOrderDetails.Where(x => x.poId == poId).ToList();
        }
        public ActionResult Create(purchaseOrderHeader purchaseorderheader)
        {
            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() });

            //ViewBag.ddlVendor = DDLVendor(string.Empty);
            ViewBag.ddlVendor = DDLVendorByPRId(purchaseorderheader.prId);
            var xz = db.purchaseRequestHeaders.AsNoTracking().Where(x => !db.purchaseOrderHeaders.Any(y => y.prId == x.prId) && x.proposedStatus == true && x.approvedStatus == true)
                                //.Join(db.departments, a => a.requestDeptId, b => b.deptID, (a, b) => new { a, b }) ~old process ~sweeping department kebalik dgn divisi
                                .Join(db.divisis, a => a.requestDeptId, b => b.divisiID, (a, b) => new { a, b })
                                .Select(c => new { c.a.prId, c.a.requestDeptId, deptName = c.b.divisiName, c.a.typeOrder, c.a.proposalInclude, c.a.specialInstruction, c.a.projectTimeDelivery }).ToList();

            ViewData["PRPopUp"] = xz;

            var model = new purchaseOrderHeader();
            var editor = new purchaseOrderHeader.prPopUp()
            {
                prId = xz[0].prId,
                requestDeptId = xz[0].requestDeptId,
                deptName = xz[0].deptName,
                typeOrder = xz[0].typeOrder,
                proposalInclude = xz[0].proposalInclude,
                specialInstruction = xz[0].specialInstruction,
                projectTimeDelivery = xz[0].projectTimeDelivery
            };
            model.PopUpPR.Add(editor);
            ViewBag.PRPopUp = model.PopUpPR.ToList();
            
            var modelx = new purchaseRequestHeader();
            foreach (var a in db.purchaseRequestDetails.Where(x => x.prId == purchaseorderheader.prId).ToList() as IEnumerable<purchaseRequestHeader.purchaseRequestDetail>)
            {
                var editorx = new purchaseRequestHeader.purchaseRequestDetail()
                {
                    productId = a.productId,
                    description = a.description,
                    qty = a.qty,
                    unit = a.unit
                };
                modelx.detailPurchaseRequest.Add(editorx);
            }
            ViewData["dataDetail"] = modelx.detailPurchaseRequest.ToList();

            if (ModelState.IsValid)
            {
                var countChk = 0;
                var countChkMultiple = 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;

                    if (purchaseorderheader.topType == "Multiple")
                        if (Request.Form.AllKeys.ToList()[i].Contains("txtBuyDate_"))
                            countChkMultiple++;
                }

                try
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        string generateID = prefix + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("d2");
                        var prIDCreated = db.purchaseOrderHeaders.Where(x => x.poId.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');
                        }

                        #region ubah vendorID ke vendorCode
                        int idVendor = 0;
                        try{
                            idVendor = int.Parse(purchaseorderheader.vendorId) * 1;
                        }
                        catch
                        {

                        }

                        if(idVendor > 0 )
                        {
                            var ven = db.vendors.AsNoTracking().Where(x => x.id == idVendor).ToList();
                            purchaseorderheader.vendorId = ven[0].vendorID;
                        }
                        #endregion
                        purchaseorderheader.poId = generateID;
                        lvm = Session["sessionUserLogin"] as LoginViewModel.userLogin;
                        purchaseorderheader.createdDate = DateTime.Now;
                        purchaseorderheader.createdUser = lvm.userID;
                        purchaseorderheader.proposedBy = lvm.userID;
                        purchaseorderheader.proposedDate = DateTime.Now;
                        purchaseorderheader.proposedStatus = isProposed;
                        db.purchaseOrderHeaders.Add(purchaseorderheader);

                        #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_qty = Request.Form["txtQty_" + i].ToString() != "" ? Convert.ToInt32(Request.Form["txtQty_" + i].ToString().Replace('.', ',')) : 0;
                            decimal t_price = Request.Form["txtPrice_" + i].ToString() != "" ? Convert.ToDecimal(Convert.ToDouble(Request.Form["txtPrice_" + i].ToString().Replace('.', ','))) : 0;
                            decimal t_disc = Request.Form["txtDisc_" + i].ToString() != "" ? Convert.ToDecimal(Convert.ToDouble(Request.Form["txtDisc_" + i].ToString().Replace('.', ','))) : 0;

                            var editorx = new purchaseOrderHeader.purchaseOrderDetail()
                            {
                                poId = purchaseorderheader.poId,
                                productID = t_productID,
                                qty = t_qty,
                                price = t_price,
                                disc = t_disc
                            };
                            db.purchaseOrderDetails.Add(editorx);
                        }
                        #endregion

                        #region insertTOPMultiple
                        if(purchaseorderheader.topType == "Multiple")
                        { 
                            for (int i = 0; i < countChkMultiple; i++)
                            {
                                var colVal = Request.Form["txtBuyDate_" + i];
                                if (colVal == "")
                                    break;

                                DateTime t_BuyDate = Convert.ToDateTime(Request.Form["txtBuyDate_" + i].ToString());
                                decimal t_BuyPercent = Request.Form["txtBuyPercent_" + i].ToString() != "" ? Convert.ToDecimal(Convert.ToDouble(Request.Form["txtBuyPercent_" + i].ToString().Replace('.', ','))) : 0;

                                var editort = new purchaseOrderHeader.purchaseOrderTop()
                                {
                                    poId = purchaseorderheader.poId,
                                    buyDate = t_BuyDate,
                                    buyPercent = t_BuyPercent
                                };
                                db.purchaseOrderTOPs.Add(editort);
                            }
                        }
                        #endregion

                        db.SaveChanges();
                        ts.Complete();
                    }

                    return RedirectToAction("Index");
                }
                catch (Exception exc)
                {
                    string a = exc.Message;
                }
            }
            return View(purchaseorderheader);
        }
        public async Task<ActionResult> LoadDetailPR_byVendorID(string prId, int vendorID)
        {
            var model = new purchaseRequestHeader();
            #region oldProcess
            //foreach (var a in db.purchaseRequestDetails.Where(x => x.prId == prId).ToList() as IEnumerable<purchaseRequestHeader.purchaseRequestDetail>)
            //{
            //    foreach(var b in db.transVendorProducts.Where(x=>x.id_vendor==vendorID).ToList() as IEnumerable<transVendorProduct>)
            //    { 
            //        if(b.productID == a.productId)
            //        { 
            //            var editor = new purchaseRequestHeader.purchaseRequestDetail()
            //            {
            //                productId = a.productId,                            
            //                description = a.description,
            //                qty = a.qty,
            //                unit = a.unit
            //            };
            //            model.detailPurchaseRequest.Add(editor);
            //            break;
            //        }
            //    }
            //}
            #endregion

            #region new Process
            string sql = "SELECT DISTINCT b.* ";
            sql += "FROM [dbo].[transVendorProducts] a ";
            sql += "INNER JOIN [dbo].[PurchaseRequestDetails] b ON b.productID = a.productID ";
            sql += "INNER JOIN [dbo].[Vendors] c ON c.id = a.id_vendor ";
            sql += "LEFT JOIN (SELECT x.*, y.prId ";
            sql += "	FROM [dbo].[PurchaseOrderDetails] x ";
            sql += "	INNER JOIN [dbo].[PurchaseOrderHeaders] y ON y.poId = x.poId) d ON d.prId = b.prId AND d.productID != b.productID ";
            sql += "WHERE b.prId = '" + prId + "'";
            DataTable dtListAuthorize = con.executeReader(sql);
            foreach (DataRow dr in dtListAuthorize.Rows)
            {
                foreach(var b in db.transVendorProducts.Where(x=>x.id_vendor==vendorID).ToList() as IEnumerable<transVendorProduct>)
                {
                    if (b.productID == int.Parse(dr["productID"].ToString()))
                    {
                        var editor = new purchaseRequestHeader.purchaseRequestDetail()
                        {
                            productId = int.Parse(dr["productID"].ToString()),
                            description = dr["description"].ToString(),
                            qty = int.Parse(dr["qty"].ToString()),
                            unit = dr["unit"].ToString()
                        };
                        model.detailPurchaseRequest.Add(editor);
                        break;
                    }
                }
            }
            #endregion
            ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();

            ViewBag.product = db.products.ToList();
            return PartialView("_PartialPagePR-PO");
        }
        public async Task<ActionResult> LoadDetailPR(string prId)
        {

            var model = new purchaseRequestHeader();
            foreach(var a in db.purchaseRequestDetails.Where(x=>x.prId==prId).ToList() as IEnumerable<purchaseRequestHeader.purchaseRequestDetail>)
            {
                var editor = new purchaseRequestHeader.purchaseRequestDetail()
                {
                    productId = a.productId,
                    description = a.description,
                    qty = a.qty,
                    unit = a.unit
                };
                model.detailPurchaseRequest.Add(editor);
            }
            ViewData["dataDetail"] = model.detailPurchaseRequest.ToList();

            return PartialView("_PartialPagePR-PO");
        }