コード例 #1
0
        public ActionResult OrderCencel(int OrderId)
        {
            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    #region Update Order Status
                    var order = db.tbl_orders.FirstOrDefault(x => x.OrderID == OrderId);

                    if (order != null)
                    {
                        var orderLine = db.tbl_order_Line_item.Where(x => x.OrderID == order.OrderID).ToList();
                        orderLine.ForEach(x =>
                        {
                            tbl_purchase tblpur = new tbl_purchase();
                            tblpur.OrderID      = OrderId;
                            tblpur.ProductID    = x.ProductID;
                            tblpur.ProductName  = x.ProductName;
                            //tblpur.ProductTypeID = "";
                            //tblpur.ProductTypeName = "";
                            tblpur.MRP      = x.MRP;
                            tblpur.MemberID = order.MemberID;
                            tblpur.BP       = x.BP;
                            tblpur.RB       = x.RB;
                            //tblpur.DealerID
                            tblpur.PaymentAddress  = order.PaymentAddress;
                            tblpur.ShipmentAddress = order.ShipmentAddress;
                            tblpur.OrderStatus     = KDMOrderStatus.Cancled;
                            // tblpur.OrderDateTime = order.OrderDateTime;
                            tblpur.OrderBy = order.OrderBy;
                            //tblpur.OrderApprovedBy = "";
                            tblpur.OrderCanceledBy  = User.Identity.Name;
                            tblpur.Quantity         = x.Quantity;
                            tblpur.PaymentType      = order.PaymentType;
                            tblpur.TotalAmount      = x.Quantity * x.DP;
                            tblpur.TotalPV          = 0;
                            tblpur.TotalBV          = 0;
                            tblpur.StatusUpdateDate = DateTime.Now;
                            db.tbl_purchase.Add(tblpur);
                        });

                        db.tbl_orders.Remove(order);
                        db.tbl_order_Line_item.RemoveRange(orderLine);
                    }
                    #endregion

                    db.SaveChanges();
                    tr.Commit();
                    TempData["SMsg"] = "Order# " + OrderId + " cancled";
                }
                catch (Exception ex)
                {
                    tr.Rollback();
                    Log.Error(ex, "[M_0000013] [ERROR]");
                    TempData["EMsg"] = "Can't cancel the order# " + OrderId;
                }
            }

            return(RedirectToAction("OrderList"));
        }
コード例 #2
0
 public ActionResult Details(tbl_purchase p)
 {
     if (ModelState.IsValid)
     {
         using (dbeadmeenEntities5 db = new dbeadmeenEntities5())
         {
             db.tbl_purchase.Add(p);
             db.SaveChanges();
             ModelState.Clear();
             p = null;
             //ViewBag.message = "sucess fully order";
             TempData["message"] = "sucess fully order";
         }
     }
     //return View(p);
     return(RedirectToAction("Details"));
 }
コード例 #3
0
        //Methods------------------
        protected void Save()
        {
            try
            {
                tbl_purchase purchase = new tbl_purchase();
                purchase.company_id       = companyId;
                purchase.branch_id        = branchId;
                purchase.financialyear_id = financialYearId;
                purchase.InvoiceNumber    = lblInvoice.Text;

                purchase.PaymentMode_id = Convert.ToInt32(ddlPaymentMode.SelectedValue);
                purchase.status         = true;
                purchase.party_id       = Convert.ToInt32(ddlVendor.SelectedValue);
                purchase.Po_Date        = DateTime.Parse(txtdate.Text, new CultureInfo("en-US"));
                purchase.po_no          = txtPONo.Text;

                purchase.created_by   = user_id;
                purchase.created_date = DateTime.Now;

                //insert into Purchase Payment Details
                tbl_PurchasePaymentDetials purchasePaymentDetail = new tbl_PurchasePaymentDetials();
                purchasePaymentDetail.TaxAmount      = Convert.ToDecimal(lblTaxAmount.Text);
                purchasePaymentDetail.DiscountAmount = Convert.ToDecimal(lblDiscountAmt.Text);
                purchasePaymentDetail.SubTotal       = Convert.ToDecimal(lblsubtotal.Text);
                purchasePaymentDetail.GrandTotal     = Convert.ToDecimal(lblGrandTotal.Text);
                purchasePaymentDetail.PaidAmnt       = Convert.ToDecimal(txtPaidAmt.Text);
                purchasePaymentDetail.GivenAmnt      = Convert.ToDecimal(txtPaidAmt.Text);
                purchasePaymentDetail.BalanceAmnt    = Convert.ToDecimal(txtBalanceAmt.Text);
                purchasePaymentDetail.FromTable      = "Purchase";
                purchase.tbl_PurchasePaymentDetials.Add(purchasePaymentDetail);

                for (int i = 0; i <= gvpurchasedetails.Rows.Count - 1; i++)
                {
                    int         productId = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[2].Text);
                    int         batchId   = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[4].Text);
                    tbl_product product   = context.tbl_product.Where(w => w.product_id == productId).FirstOrDefault();

                    //Add into Purchase Details table for each product
                    tbl_purchasedetails purchaseDetails = new tbl_purchasedetails();
                    purchaseDetails.product_id   = productId;
                    purchaseDetails.batch_id     = batchId;
                    purchaseDetails.tax_id       = product.tax_id;
                    purchaseDetails.unit_id      = product.unit_id;
                    purchaseDetails.tax_amt      = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[11].Text);
                    purchaseDetails.dicount_amt  = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[9].Text);
                    purchaseDetails.quantity     = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                    purchaseDetails.amount       = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[12].Text);
                    purchaseDetails.created_by   = Convert.ToString(user_id);
                    purchaseDetails.created_date = DateTime.Now;
                    purchaseDetails.status       = true;

                    //Enter Details In tbl_ActualPurchaseTaxAndPrice : to get the original Values at the time of Purchase Return
                    tbl_ActualPurchaseTaxAndPrice actualPurchase = new tbl_ActualPurchaseTaxAndPrice();
                    actualPurchase.product_id       = productId;
                    actualPurchase.status           = true;
                    actualPurchase.tax_percent      = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[10].Text);
                    actualPurchase.purchase_rate    = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[6].Text);
                    actualPurchase.discount_percent = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[8].Text);
                    actualPurchase.discount_amnt    = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[9].Text);
                    actualPurchase.batch_id         = batchId;
                    actualPurchase.sale_price       = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[7].Text);
                    actualPurchase.created_by       = Convert.ToString(user_id);
                    actualPurchase.created_date     = DateTime.Now;

                    //Add into Actual Purchase Tax And Return Table
                    purchase.tbl_ActualPurchaseTaxAndPrice.Add(actualPurchase);


                    //Add Stock if not exist or update the Stock against the product
                    tbl_stock stock = new tbl_stock();
                    if (!IsProductStockExists(companyId, branchId, productId, batchId))
                    {
                        stock.company_id   = companyId;
                        stock.branch_id    = branchId;
                        stock.product_id   = productId;
                        stock.batch_id     = batchId;
                        stock.qty          = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                        stock.status       = true;
                        stock.created_by   = Convert.ToString(user_id);
                        stock.created_date = DateTime.Now;
                        context.tbl_stock.Add(stock);
                    }
                    else
                    {
                        stock               = context.tbl_stock.Where(w => w.company_id == companyId && w.branch_id == branchId && w.product_id == productId && w.batch_id == batchId).FirstOrDefault();
                        stock.qty           = stock.qty + Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                        stock.modified_by   = Convert.ToString(user_id);
                        stock.modified_date = DateTime.Now;
                    }
                    purchase.tbl_purchasedetails.Add(purchaseDetails);
                }

                context.tbl_purchase.Add(purchase);
                context.SaveChanges();
                string order = purchase.InvoiceNumber;
                Session["p_id"] = purchase.purchase_id;
                ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('Saved successfully, Your order number is " + order + "');", true);
            }
            catch (Exception ex)
            {
                ErrorLog.saveerror(ex);
            }
        }
コード例 #4
0
        protected void Save()
        {
            try
            {
                int purchaseId = Convert.ToInt32(hdnPurchaseId.Value);
                if (purchaseId == 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('Please Enter Purchase No','False');", true);
                    return;
                }
                //Get Origianl Purchase Details
                tbl_purchase purchase = new tbl_purchase();
                purchase = context.tbl_purchase.Where(pd => pd.purchase_id == purchaseId && pd.company_id == companyId && pd.branch_id == branchId).FirstOrDefault();

                tbl_purchasereturn purchaseReturn = new tbl_purchasereturn();
                purchaseReturn.purchase_id      = purchaseId;
                purchaseReturn.company_id       = companyId;
                purchaseReturn.branch_id        = branchId;
                purchaseReturn.financialyear_id = financialYearId;
                purchaseReturn.InvoiceNumber    = txtPoNo.Text;
                purchaseReturn.paymentmode_id   = Convert.ToInt32(ddlPaymentMode.SelectedValue);
                purchaseReturn.status           = true;
                purchaseReturn.party_id         = Convert.ToInt32(purchase.party_id);
                purchaseReturn.created_by       = user_id;
                purchaseReturn.created_date     = DateTime.Now;

                //Update into Purchase Payment Details
                tbl_PurchasePaymentDetials purchasePaymentDetail = context.tbl_PurchasePaymentDetials.Where(w => w.PurchaseId == purchaseId).FirstOrDefault();
                purchasePaymentDetail.PaidAmnt       = Convert.ToDecimal(txtPaidAmt.Text);
                purchasePaymentDetail.GivenAmnt      = Convert.ToDecimal(lblGivenAmnt.Text) - Convert.ToDecimal(txtPaidAmt.Text);
                purchasePaymentDetail.BalanceAmnt    = Convert.ToDecimal(txtBalanceAmt.Text);
                purchasePaymentDetail.TaxAmount      = Convert.ToDecimal(lblResultTotalTaxAmnt.Text);
                purchasePaymentDetail.DiscountAmount = Convert.ToDecimal(lblResultTotalDiscount.Text);
                purchasePaymentDetail.SubTotal       = Convert.ToDecimal(lblResultSubTotal.Text);
                purchasePaymentDetail.GrandTotal     = Convert.ToDecimal(lblResultGrndTotal.Text);
                purchasePaymentDetail.FromTable      = "Return";
                purchase.tbl_PurchasePaymentDetials.Add(purchasePaymentDetail);

                for (int i = 0; i <= gvpurchasedetails.Rows.Count - 1; i++)
                {
                    int         productId = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[2].Text);
                    int         batchId   = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[4].Text);
                    tbl_product product   = context.tbl_product.Where(w => w.product_id == productId).FirstOrDefault();

                    tbl_purchasereturndetails purchaseReturnDetails = new tbl_purchasereturndetails();
                    purchaseReturnDetails.product_id    = productId;
                    purchaseReturnDetails.batch_id      = batchId;
                    purchaseReturnDetails.tax_id        = product.tax_id;
                    purchaseReturnDetails.unit_id       = product.unit_id;
                    purchaseReturnDetails.discount_amnt = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[7].Text);
                    purchaseReturnDetails.tax_amt       = gvpurchasedetails.Rows[i].Cells[9].Text;
                    purchaseReturnDetails.quantity      = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                    purchaseReturnDetails.amount        = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[10].Text);
                    purchaseReturnDetails.created_by    = Convert.ToString(user_id);
                    purchaseReturnDetails.created_date  = Convert.ToDateTime(DateTime.Now);
                    purchaseReturnDetails.status        = true;

                    tbl_stock stock = new tbl_stock();
                    stock               = context.tbl_stock.Where(w => w.company_id == companyId && w.branch_id == branchId && w.product_id == productId && w.batch_id == batchId).FirstOrDefault();
                    stock.qty           = stock.qty - Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                    stock.modified_by   = Convert.ToString(user_id);
                    stock.modified_date = Convert.ToDateTime(DateTime.Now);

                    purchaseReturn.tbl_purchasereturndetails.Add(purchaseReturnDetails);
                }

                context.tbl_purchasereturn.Add(purchaseReturn);
                context.SaveChanges();
                string invoiceNumber = purchaseReturn.InvoiceNumber;
                ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('saved Successfully, You order number is " + invoiceNumber + "','True');", true);
            }
            catch (Exception ex)
            {
                ErrorLog.saveerror(ex);
            }
        }
コード例 #5
0
        public ActionResult OrderApprove(int OrderId)
        {
            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    int totalPVForTemp = 0;
                    #region Update Order Status
                    var order = db.tbl_orders.FirstOrDefault(x => x.OrderID == OrderId);

                    if (order != null && order.MemberID != "")
                    {
                        var orderLine = db.tbl_order_Line_item.Where(x => x.OrderID == order.OrderID).ToList();


                        orderLine.ForEach(x =>
                        {
                            #region Update Member Tree

                            var memberExist = db.tbl_members.FirstOrDefault(y => y.MemberID == order.MemberID);

                            if (memberExist == null)
                            {
                                throw new Exception("Member not found in members");
                            }
                            var member = db.tbl_member_tree.Where(m => m.PlacementID == memberExist.PlacementID).FirstOrDefault();

                            if (member == null)
                            {
                                throw new Exception("Member not found in member tree");
                            }

                            member.PV = (member.PV ?? 0) + (x.BP * x.Quantity);
                            member.BV = (member.BV ?? 0) + (x.RB * x.Quantity);

                            totalPVForTemp += (int)x.BP * (int)x.Quantity;

                            db.Entry(member).State = EntityState.Modified;

                            #endregion

                            // db.SaveChanges();

                            #region Purchase Entry

                            tbl_purchase tblpur = new tbl_purchase();
                            tblpur.OrderID      = OrderId;
                            tblpur.ProductID    = x.ProductID;
                            tblpur.ProductName  = x.ProductName;
                            tblpur.MRP          = x.MRP;
                            tblpur.DP           = x.DP;
                            tblpur.SP           = x.SP;
                            tblpur.MemberID     = order.MemberID;
                            tblpur.BP           = x.BP;
                            tblpur.RB           = x.RB;
                            //tblpur.DealerID
                            tblpur.PaymentAddress   = order.PaymentAddress;
                            tblpur.ShipmentAddress  = order.ShipmentAddress;
                            tblpur.OrderStatus      = KDMOrderStatus.Approved;
                            tblpur.OrderDate        = order.OrderDateTime;
                            tblpur.OrderBy          = order.OrderBy;
                            tblpur.OrderApprovedBy  = User.Identity.Name;
                            tblpur.OrderCanceledBy  = "";
                            tblpur.Quantity         = x.Quantity;
                            tblpur.PaymentType      = order.PaymentType;
                            tblpur.TotalAmount      = x.DP;
                            tblpur.TotalPV          = 0;
                            tblpur.TotalBV          = 0;
                            tblpur.StatusUpdateDate = DateTime.Now;
                            db.tbl_purchase.Add(tblpur);

                            #endregion

                            #region Vat Entry

                            tbl_vat_account_data vad = new tbl_vat_account_data();

                            var rowCount = db.tbl_vat_account_data.ToList();
                            int lastRow  = 0;
                            if (rowCount.Count > 0)
                            {
                                lastRow        = (int)db.tbl_vat_account_data.Max(y => y.trSerialNo);
                                vad.trSerialNo = lastRow + 1;
                            }
                            else
                            {
                                vad.trSerialNo = 1;
                            }
                            decimal balance  = (decimal)db.tbl_vat_account_data.Where(z => z.trSerialNo == lastRow).Select(s => s.Balance).FirstOrDefault();
                            vad.ForAccount   = order.OrderID.ToString();
                            vad.PurposeCode  = 1;
                            vad.DebitAmount  = 0;
                            vad.CreditAmount = x.Vat;
                            vad.Balance      = db.tbl_vat_account_data.FirstOrDefault(y => y.trSerialNo == lastRow).Balance ?? 0 + vad.CreditAmount;
                            vad.PostingDate  = DateTime.Now.Date;
                            vad.PostingTime  = DateTime.Now.TimeOfDay;
                            vad.PostedBy     = User.Identity.Name;
                            vad.ApprovedBy   = User.Identity.Name;
                            db.tbl_vat_account_data.Add(vad);

                            #endregion
                        });

                        db.tbl_orders.Remove(order);
                        db.tbl_order_Line_item.RemoveRange(orderLine);
                    }
                    #endregion

                    #region Bonus Processing
                    KDMTRHelper trHelper = new KDMTRHelper();

                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Wallet, (double)order.TotalPV);
                    trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Sponsor, (double)totalPVForTemp);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.BinaryMatching, (double)order.TotalPV);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Generation, (double)order.TotalBV);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.MonthlyRoyalty, (double)order.TotalPV);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Performance, (double)order.TotalAmount);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Leadership, (double)order.TotalAmount);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.Rank, (double)order.TotalAmount);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.RoyalClub, (double)order.TotalAmount);
                    //trHelper.UpdateMemberBonusTemp(db, order.MemberID, KDMBonusConstants.ECommerce, (double)order.TotalAmount);

                    //trHelper.GiveWalletBonus(order.MemberID);
                    trHelper.GiveSponsorBonus(db, order.MemberID);
                    //trHelper.UpdateFundMonthlyRoyalityBonusByMemberSource(order.MemberID);
                    //trHelper.UpdateFundPerformanceBonusByMemberSource(order.MemberID);
                    //trHelper.UpdateFundLadershipBonusByMemberSource(order.MemberID);
                    //trHelper.UpdateFundRoyalClubBonusByMemberSource(order.MemberID);
                    //trHelper.UpdateFundECommerceBonusByMemberSource(order.MemberID);


                    #endregion

                    db.SaveChanges();
                    tr.Commit();
                    TempData["SMsg"] = "Order# " + OrderId + " approved";
                }
                catch (Exception ex)
                {
                    tr.Rollback();
                    Log.Error(ex, "[M_0000013] [ERROR]");
                    TempData["EMsg"] = "Can't approve the order# " + OrderId;
                }
            }

            return(RedirectToAction("OrderList"));
        }
コード例 #6
0
ファイル: Purchase.aspx.cs プロジェクト: Khan291/IMS-1.0
        //Methods------------------
        protected void Save()
        {
            try
            {
                //added by ather for file attachment url
                string  path       = "~/Uploads/AttachedFiles/Purchase/"; //path without filename to save file
                bool    fileupMsg  = uploadFile(fuAttacheFile, path, "");
                decimal balanceAmt = 0;                                   // Convert.ToDecimal(txtBalanceAmt.Text);
                decimal paidAmnt   = 0;

                if (!string.IsNullOrEmpty(txtPaidAmt.Text))
                {
                    paidAmnt = Convert.ToDecimal(txtPaidAmt.Text);
                }

                if (!string.IsNullOrEmpty(txtBalanceAmt.Text))
                {
                    balanceAmt = Convert.ToDecimal(txtBalanceAmt.Text);
                }


                tbl_purchase purchase = new tbl_purchase();
                if (fileupMsg)
                {
                    path = path + Path.GetFileName(fuAttacheFile.PostedFile.FileName); //path with filename to save in DB
                    purchase.attachmentUrl = path;
                }
                purchase.company_id       = companyId;
                purchase.branch_id        = branchId;
                purchase.financialyear_id = financialYearId;
                purchase.InvoiceNumber    = lblInvoice.Text;

                purchase.PaymentMode_id = Convert.ToInt32(ddlPaymentMode.SelectedValue);
                purchase.status         = true;
                purchase.party_id       = Convert.ToInt32(ddlVendor.SelectedValue);
                purchase.Po_Date        = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", new CultureInfo("en-US"));
                purchase.po_no          = txtPONo.Text;
                purchase.Note           = txtNotePurchase.Text;
                purchase.OtherExpLabel  = txtOtherExpLabel.Text;
                purchase.other_expenses = Convert.ToDecimal(txtotherexpence.Text);

                purchase.created_by   = user_id;
                purchase.created_date = DateTime.Now;


                //insert into Purchase Payment Details
                tbl_PurchasePaymentDetials purchasePaymentDetail = new tbl_PurchasePaymentDetials();
                purchasePaymentDetail.TaxAmount      = Convert.ToDecimal(lblTaxAmount.Text);
                purchasePaymentDetail.DiscountAmount = Convert.ToDecimal(lblDiscountAmt.Text);
                purchasePaymentDetail.SubTotal       = Convert.ToDecimal(lblsubtotal.Text);
                purchasePaymentDetail.GrandTotal     = Convert.ToDecimal(lblGrandTotal.Text);
                purchasePaymentDetail.PaidAmnt       = paidAmnt;
                purchasePaymentDetail.GivenAmnt      = paidAmnt;
                purchasePaymentDetail.BalanceAmnt    = balanceAmt;
                purchasePaymentDetail.CreatedDate    = DateTime.Now;
                purchasePaymentDetail.CreatedBy      = user_id;
                purchasePaymentDetail.FromTable      = "Purchase";

                purchasePaymentDetail.OtherExpLabel = txtOtherExpLabel.Text;
                purchasePaymentDetail.OtherExp      = Convert.ToDecimal(txtotherexpence.Text);

                //string otherExp = txtotherexpence.Text;
                //if (otherExp.Contains("-"))
                //{
                //    var calculatedDiscount = Convert.ToDecimal(lblDiscountAmt.Text);
                //    var overAllDisc = Convert.ToDecimal(otherExp.Substring(otherExp.LastIndexOf('-') + 0));
                //    var totalDiscount = calculatedDiscount - overAllDisc;

                //    purchasePaymentDetail.DiscountAmount = totalDiscount;
                //}
                //else
                //{
                //    purchasePaymentDetail.DiscountAmount = Convert.ToDecimal(lblDiscountAmt.Text);
                //}


                purchasePaymentDetail.DiscountAmount = Convert.ToDecimal(lblDiscountAmt.Text);
                purchase.tbl_PurchasePaymentDetials.Add(purchasePaymentDetail);


                for (int i = 0; i <= gvpurchasedetails.Rows.Count - 1; i++)
                {
                    int         productId = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[2].Text);
                    int         batchId   = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[4].Text);
                    tbl_product product   = context.tbl_product.Where(w => w.product_id == productId).FirstOrDefault();
                    var         qty       = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                    //Add into Purchase Details table for each product
                    tbl_purchasedetails purchaseDetails = new tbl_purchasedetails();
                    purchaseDetails.product_id = productId;
                    purchaseDetails.batch_id   = batchId;
                    // purchaseDetails.tax_id = product.tax_id;
                    purchaseDetails.unit_id      = product.unit_id;
                    purchaseDetails.tax_amt      = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[13].Text);
                    purchaseDetails.dicount_amt  = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[9].Text);
                    purchaseDetails.quantity     = qty;
                    purchaseDetails.amount       = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[14].Text);
                    purchaseDetails.created_by   = Convert.ToString(user_id);
                    purchaseDetails.created_date = DateTime.Now;
                    purchaseDetails.status       = true;

                    var groupId = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[10].Text);

                    DataTable taxgroupTypes = helper.LINQToDataTable(context.SelectProductTaxGroup(groupId, productId, qty));
                    ViewState["TotalTaxPercent"] = null;
                    for (int j = 0; j <= taxgroupTypes.Rows.Count - 1; j++)
                    {
                        ViewState["TotalTaxPercent"] = taxgroupTypes.Rows[j].Field <decimal>("totalTaxPercetage");
                    }

                    //insert into tax group purchase
                    tbl_purchasetaxgroup purchaseTaxGroup = new tbl_purchasetaxgroup();
                    purchaseTaxGroup.group_id           = groupId;
                    purchaseTaxGroup.product_id         = productId;
                    purchaseTaxGroup.batchId            = batchId;
                    purchaseTaxGroup.totalTaxPercentage = (Decimal)ViewState["TotalTaxPercent"];
                    purchaseTaxGroup.group_name         = gvpurchasedetails.Rows[i].Cells[11].Text;
                    //Get the Tax type saved from db
                    //insert into tax group detailes
                    // var taxGroupTypes = context.tbl_productTaxGroup.Join(context.tbl_taxgroup, t => t.group_id, pt => pt.group_id, (t, pt) => new { t.group_id, pt.group_name, t.product_id }).Where(t => t.product_id == productId).ToList();


                    for (int j = 0; j <= taxgroupTypes.Rows.Count - 1; j++)
                    {
                        tbl_purchasetaxgroupdetails purchaseTaxDetails = new tbl_purchasetaxgroupdetails();
                        purchaseTaxDetails.type_id        = taxgroupTypes.Rows[j].Field <int>("type_id");
                        purchaseTaxDetails.tax_percentage = taxgroupTypes.Rows[j].Field <decimal>("tax_percentage");
                        purchaseTaxGroup.tbl_purchasetaxgroupdetails.Add(purchaseTaxDetails);
                    }

                    purchase.tbl_purchasetaxgroup.Add(purchaseTaxGroup);
                    //Enter Details In tbl_ActualPurchaseTaxAndPrice : to get the original Values at the time of Purchase Return
                    tbl_ActualPurchaseTaxAndPrice actualPurchase = new tbl_ActualPurchaseTaxAndPrice();
                    actualPurchase.product_id = productId;
                    actualPurchase.status     = true;
                    //actualPurchase.tax_percent = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[10].Text);
                    actualPurchase.purchase_rate    = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[6].Text);
                    actualPurchase.discount_percent = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[8].Text);
                    actualPurchase.discount_amnt    = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[9].Text);
                    actualPurchase.batch_id         = batchId;
                    actualPurchase.sale_price       = Convert.ToDecimal(gvpurchasedetails.Rows[i].Cells[7].Text);
                    actualPurchase.created_by       = Convert.ToString(user_id);
                    actualPurchase.created_date     = DateTime.Now;

                    //Add into Actual Purchase Tax And Return Table
                    purchase.tbl_ActualPurchaseTaxAndPrice.Add(actualPurchase);


                    //Add Stock if not exist or update the Stock against the product
                    tbl_stock stock = new tbl_stock();
                    if (!IsProductStockExists(companyId, branchId, productId, batchId))
                    {
                        stock.company_id   = companyId;
                        stock.branch_id    = branchId;
                        stock.product_id   = productId;
                        stock.batch_id     = batchId;
                        stock.qty          = Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                        stock.status       = true;
                        stock.created_by   = Convert.ToString(user_id);
                        stock.created_date = DateTime.Now;
                        context.tbl_stock.Add(stock);
                    }
                    else
                    {
                        stock               = context.tbl_stock.Where(w => w.company_id == companyId && w.branch_id == branchId && w.product_id == productId && w.batch_id == batchId).FirstOrDefault();
                        stock.qty           = stock.qty + Convert.ToInt32(gvpurchasedetails.Rows[i].Cells[5].Text);
                        stock.modified_by   = Convert.ToString(user_id);
                        stock.modified_date = DateTime.Now;
                    }
                    purchase.tbl_purchasedetails.Add(purchaseDetails);
                }


                context.tbl_purchase.Add(purchase);
                context.SaveChanges();
                string order = purchase.InvoiceNumber;
                Session["p_id"] = purchase.purchase_id;
                ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('Saved successfully, Your order number is " + order + "');", true);
            }
            catch (Exception ex)
            {
                ErrorLog.saveerror(ex);
            }
        }