Coding Special

Coding Special

Sunday 13 September 2020

cs

 using DataAccessLayer;

using EntityLayer;

using System;

using System.Collections.Generic;

using System.Data;

using System.Drawing;

using System.IO;

using System.Text.RegularExpressions;

using System.Web;

using System.Web.Services;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace WebDesk_ERP.Trade

{

    public partial class PurchaseQuotationWebForm : System.Web.UI.Page

    {

        public string _pendingStatus

        {

            get

            {

                return ViewState["_pendingStatus"] != null ? ViewState["_pendingStatus"].ToString() : "";

            }

            set

            {

                ViewState["_pendingStatus"] = value;

            }

        }

        public decimal PreviousQty

        {

            get

            {

                return ViewState["PreviousQty"] != null ? Convert.ToDecimal(ViewState["PreviousQty"].ToString()) : 0;

            }

            set

            {

                ViewState["PreviousQty"] = value;

            }

        }

        public decimal PreviousAmt

        {

            get

            {

                return ViewState["PreviousAmt"] != null ? Convert.ToInt32(ViewState["PreviousAmt"].ToString()) : 0;

            }

            set

            {

                ViewState["PreviousAmt"] = value;

            }

        }

        public string _poNo

        {

            get

            {

                return ViewState["_poNo"] != null ? ViewState["_poNo"].ToString() : "";

            }

            set

            {

                ViewState["_poNo"] = value;

            }

        }

        public string DocumentCode { get; set; }

        public string Status { get; set; }

        public int PoId

        {

            get

            {

                return ViewState["PoId"] != null ? Convert.ToInt32(ViewState["PoId"].ToString()) : 0;

            }

            set

            {

                ViewState["PoId"] = value;

            }

        }

        public int ActiveId

        {

            get

            {

                return ViewState["ActiveId"] != null ? Convert.ToInt32(ViewState["ActiveId"].ToString()) : 0;

            }

            set

            {

                ViewState["ActiveId"] = value;

            }

        }

        public string FormName { get; set; }

        public int PIDtlId { get; set; }

        public int PIActiveId

        {

            get

            {

                return ViewState["PIActiveId"] != null ? Convert.ToInt32(ViewState["PIActiveId"].ToString()) : 0;

            }

            set

            {

                ViewState["PIActiveId"] = value;

            }

        }

        public int ProductId { get; set; }

        public int UserId { get; set; }

        public int CompanyId { get; set; }

        public int? PurchaseReqId

        {

            get

            {

                return ViewState["PurchaseReqId"] != null ? Convert.ToInt32(ViewState["PurchaseReqId"].ToString()) : 0;

            }

            set

            {

                ViewState["PurchaseReqId"] = value;

            }

        }

        public int? PickDataID

        {

            get

            {

                return ViewState["PickDataID"] != null ? Convert.ToInt32(ViewState["PickDataID"].ToString()) : 0;

            }

            set

            {

                ViewState["PickDataID"] = value;

            }

        }

        public int rowIndex

        {

            get

            {

                return ViewState["rowIndex"] != null ? Convert.ToInt32(ViewState["rowIndex"].ToString()) : 0;

            }

            set

            {

                ViewState["rowIndex"] = value;

            }

        }

        public bool status

        {

            get

            {

                return ViewState["status"] != null ? Convert.ToBoolean(ViewState["status"].ToString()) : true;

            }

            set

            {

                ViewState["status"] = value;

            }

        }

        //public static bool isPickData { get; set; }

        public bool isPickData

        {

            get

            {

                return ViewState["isPickData"] != null ? Convert.ToBoolean(ViewState["isPickData"].ToString()) : true;

            }

            set

            {

                ViewState["isPickData"] = value;

            }

        }

        public bool IsDeleteByList

        {

            get

            {

                return ViewState["IsDeleteByList"] != null ? Convert.ToBoolean(ViewState["IsDeleteByList"].ToString()) : true;

            }

            set

            {

                ViewState["IsDeleteByList"] = value;

            }

        }

        public decimal TotalQty

        {

            get

            {

                return ViewState["TotalQty"] != null ? Convert.ToDecimal(ViewState["TotalQty"].ToString()) : 0;

            }

            set

            {

                ViewState["TotalQty"] = value;

            }

        }

        public decimal tota111

        {

            get

            {

                return ViewState["tota111"] != null ? Convert.ToInt32(ViewState["tota111"].ToString()) : 0;

            }

            set

            {

                ViewState["tota111"] = value;

            }

        }

        public int WarehouseId

        {

            get

            {

                return ViewState["WarehouseId"] != null ? Convert.ToInt32(ViewState["WarehouseId"].ToString()) : 0;

            }

            set

            {

                ViewState["WarehouseId"] = value;

            }

        }

        public static List<int> GetQty = new List<int>();

        public string PropFinalCode

        {

            get

            {

                return ViewState["PropFinalCode"] != null ? ViewState["PropFinalCode"].ToString() : "";

            }

            set

            {

                ViewState["PropFinalCode"] = value;

            }

        }

        public string StartDateYear

        {

            get

            {

                return ViewState["StartDateYear"] != null ? ViewState["StartDateYear"].ToString() : "";

            }

            set

            {

                ViewState["StartDateYear"] = value;

            }

        }

        ApprovalDAL activeApprovalDAL = new ApprovalDAL();

        public string PropCurrencyFormat

        {

            get

            {

                return ViewState["CurrencyFormat"] != null ? ViewState["CurrencyFormat"].ToString() : string.Empty;

            }

            set

            {

                ViewState["CurrencyFormat"] = value;

            }

        }

        public decimal ApprovalTotal

        {

            get

            {

                return ViewState["ApprovalTotal"] != null ? Convert.ToDecimal(ViewState["ApprovalTotal"].ToString()) : 0;

            }

            set

            {

                ViewState["ApprovalTotal"] = value;

            }

        }

        List<PurchaseQuotationDtl> activeSaleOrderdtllist = new List<PurchaseQuotationDtl>();

        List<PurcahseReturnDtl> activeQuotationDtllist = new List<PurcahseReturnDtl>();

        DiscountTaxMasterDAL activeDiscountTaxMasterDAL = new DiscountTaxMasterDAL();

        DiscountTaxMaster activeDiscountTaxMaster = new DiscountTaxMaster();

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!userauth(AuthType.View) == true)

                Response.Redirect("~/Dashboard.aspx?cmgr=uau1");

            if (!IsPostBack)

            {

                StartDateYear = FinancialYearStartDateGetById();

                PropCurrencyFormat = CurrencyFormat();

                FinancialYearMaster activeFinancialYearMaster = activeFinancialYearMasterDAL.FinancialYearMasterGetById(Convert.ToInt32(Session["FinancialYearID"]));

                if (activeFinancialYearMaster.LockYear)

                {

                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Can not Save Changes. Financial Year Locked. Contact Admin.');", true);

                }

                BindCurrency();

                BindVendor();

                BindWarehoue();

                BindJob();

                BindUser();

                BindUnit();

                BindPurcahseQout();

                BindDiscountTax();

                BindPriceList();

                ddlEmployee.SelectedValue = Session["UserId"].ToString();

                if (Request.QueryString["Id"] != null)

                {

                    ActiveId = Convert.ToInt32(Request.QueryString["Id"]);

                    ViewState["ActiveUpdateId"] = ActiveId;

                    btnSave.Text = "Update";

                    UpdatePurchaseRequistion(ActiveId);

                }

                else if (Request.QueryString["Id"] == null)

                {

                    ActiveId = 0;

                    txtCode.Value = Initilaize();

                    txtRefNo.Text = RefCode();

                    txtDiscountTotal.Text = "0.00";

                    txtTotal.Text = "0.00";

                    txtFcTotal.Text = "0.00";

                    txtPerDiscount.Text = "0.00";

                    txtQty.Text = "0";

                    txtRate.Text = "0.00";

                    //txtDiscountTotal.Enabled = false;

                    // Initilaize();

                    single_cal4.Text = DateTime.Now.ToString("yyyy-MM-dd");

                    ViewState["MyDate"] = new List<PurchaseQuotationDtl>();

                    ViewState["PurchaseQuottion"] = new List<PurchaseQuotationDtl>();

                }

                else

                {

                    // BindPurcahseReq();

                    ActiveId = 0;

                    txtCode.Value = Initilaize();

                    txtRefNo.Text = RefCode();

                    txtDiscountTotal.Text = "0.00";

                    txtTotal.Text = "0.00";

                    txtFcTotal.Text = "0.00";

                    txtPerDiscount.Text = "0.00";

                    txtQty.Text = "0";

                    txtRate.Text = "0.00";

                    single_cal4.Text = DateTime.Now.ToString("yyyy-MM-dd");

                    ViewState["MyDate"] = new List<PurchaseQuotationDtl>();

                    ViewState["PurchaseQuottion"] = new List<PurchaseQuotationDtl>();

                }

            }

            if ((ActiveId == 0 && !userauth(AuthType.Add)))

                Response.Redirect("~/Dashboard.aspx?cmgr=uau1");

            if ((ActiveId > 0 && !userauth(AuthType.Update)))

                btnSave.Enabled = false;

        }

        public bool userauth(AuthType en)

        {

            int uid = Convert.ToInt32(Session["userid"].ToString());

            User_Auth objua = new User_Auth();

            string URL = Request.Url.AbsolutePath.Split('/')[2];

            if (objua.checkaccess(uid, URL, en) == true)

            { return true; }

            else { return false; }

        }

        private void BindPurcahseQout()

        {

            try

            {

                PurchaseQuotationDtLDAL activeDAL = new PurchaseQuotationDtLDAL();

                List<PurchaseQuotationDtl> activeList = activeDAL.PurchaseQuotationDtlGetByPurchaseQuotationId(0);

                if (activeList != null)

                {

                    GridViewPurchaseReq.DataSource = activeList;

                    GridViewPurchaseReq.DataBind();

                }

            }

            catch (Exception)

            {

                throw;

            }

        }

        public string Initilaize()

        {

            string PQNo = "";

            try

            {

                PurchaseQuotationDAl activeDAL = new PurchaseQuotationDAl();

                PurchaseQuotation activeMemberMaxId = activeDAL.PurchaseQuotationGetMaxId(Convert.ToInt32(Session["FinancialYearID"]));

                // string caption = "PQUOT-000001";

                if (activeMemberMaxId != null)

                {

                    string theString = activeMemberMaxId.PurQuoNo;

                    var subString = theString.Substring(theString.LastIndexOf('-') + 1);

                    int add = Convert.ToInt32(subString);

                    int code = add + 1;

                    subString = Regex.Replace(subString, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));

                    string sinq = "PQUOT-"+ StartDateYear;

                    PQNo = sinq + "-" + subString;

                }

                else

                {

                    string sinq = "PQUOT-" + StartDateYear; 

                    string caption = sinq + "-0001";

                    PQNo = caption;

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return PQNo;

        }

        private void BindVendor()

        {

            try

            {

                VendorDAL activeDAL = new VendorDAL();

                List<Vendor> activeList = activeDAL.SupplierSelectWithCodeForPurchase();

                Vendor activeUnit = new Vendor();

                activeUnit.VendorName = "None";

                activeUnit.Id = 0;

                activeList.Insert(0, activeUnit);

                ddlVendor.DataSource = activeList;

                ddlVendor.DataValueField = "Id";

                ddlVendor.DataTextField = "VendorName";

                ddlVendor.DataBind();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        public void BindCurrency()

        {

            try

            {

                ListItem li = new ListItem();

                li.Text = "None";

                li.Value = "0";

                CurrencyMasterDAL masterDal = new CurrencyMasterDAL();

                List<CurrencyMaster> master = masterDal.CurrencyMasterSelect(Convert.ToInt32(Session["companyid"]));

                CurrencyMaster activeUnit = new CurrencyMaster();

                CurrencyMaster ActiveMasterDefaultList = new CurrencyMaster();

                ActiveMasterDefaultList = masterDal.CurrencyMasterGetDefault(Convert.ToInt32(Session["companyid"]));

                if (master != null && master.Count > 0)

                {

                    ddlCurrency.DataSource = master;

                    ddlCurrency.DataValueField = "Id";

                    ddlCurrency.DataTextField = "CurrencyName";

                    ddlCurrency.DataBind();

                }

                else

                {

                    ddlCurrency.Items.Clear();

                }

                ddlCurrency.Items.Insert(0, li);

                // Currency Work Step 2

                if (Request.QueryString["Id"] == null)

                {

                    if (ActiveMasterDefaultList != null)

                    {

                        ddlCurrency.SelectedValue = ActiveMasterDefaultList.Id.ToString();

                    }

                    GetDefaultCurrency();

                }

                else

                {

                    GetDefaultCurrency();

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        public void VendorSearch()

        {

            try

            {

                VendorDAL activeDAL = new VendorDAL();

                ListItem li = new ListItem();

                li.Text = "None";

                li.Value = "0";

                int _natureID = 22;

                ddlVendor.DataSource = activeDAL.VendorSelectByChartOfAccount(_natureID).Tables[0];

                ddlVendor.DataTextField = "AccountName";

                ddlVendor.DataValueField = "code";

                ddlVendor.DataBind();

                ddlVendor.Items.Insert(0, li);

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        private void BindWarehoue()

        {

            try

            {

                WarehouseMasterDAL activeDAL = new WarehouseMasterDAL();

                List<WarehouseMaster> activeList = activeDAL.WarehouseMasterSelect(Convert.ToInt32(Session["companyid"]));

                if (activeList == null)

                    activeList = new List<WarehouseMaster>();

                WarehouseMaster activeUnit = new WarehouseMaster();

                activeUnit.Warehouse = "None";

                activeUnit.Id = 0;

                activeList.Insert(0, activeUnit);

                ddlWarehouse.DataSource = activeList;

                ddlWarehouse.DataValueField = "Id";

                ddlWarehouse.DataTextField = "Warehouse";

                ddlWarehouse.DataBind();

                if (activeList != null)

                {

                    foreach (WarehouseMaster item in activeList)

                    {

                        if (item.DefaultWarehouse == true)

                        {

                            ddlWarehouse.SelectedValue = item.Id.ToString();

                            ddlWarehouse.SelectedItem.Text = item.Warehouse;

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        private void BindJob()

        {

            try

            {

                JobMasterDAL activeDAL = new JobMasterDAL();

                List<JobMaster> activeList = activeDAL.JobMasterSelect();

                if (activeList == null)

                    activeList = new List<JobMaster>();

                JobMaster activeUnit = new JobMaster();

                activeUnit.JobName = "None";

                activeUnit.Id = 0;

                activeList.Insert(0, activeUnit);

                ddlJob.DataSource = activeList;

                ddlJob.DataValueField = "Id";

                ddlJob.DataTextField = "JobName";

                ddlJob.DataBind();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        private void BindUser()

        {

            try

            {

                LoginDAL activeDAL = new LoginDAL();

                List<Login1> activeVendorList = activeDAL.UserGetByCompanyId(Convert.ToInt32(Session["companyid"]));

                Login1 activeVEn = new Login1();

                activeVEn.Id = 0;

                activeVEn.Username = "None";

                activeVendorList.Insert(0, activeVEn);

                ddlEmployee.DataSource = activeVendorList;

                ddlEmployee.DataTextField = "Username";

                ddlEmployee.DataValueField = "Id";

                ddlEmployee.DataBind();

            }

            catch (Exception)

            {

                throw;

            }

        }

        decimal discountsum = 0.00m;

        decimal discountpercentage = 0.00m;

        decimal rate = 0.00m;

        decimal Qty = 0;

        decimal GetVatAmount = 0.00m;

        private bool Post()

        {

            bool isSave = true;

            decimal grosstotal = 0.00m;

            try

            {

                List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                decimal totalprice = 0.00m;

                if (txtPartNo.Text != "")

                {

                    decimal rate = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));

                    decimal Qty = Convert.ToDecimal(txtQty.Text);

                    decimal discountamount = 0.00m;

                    //decimal total = Qty * rate;

                    if (txtDiscountAmount.Text == "")

                    {

                        discountamount = 0;

                    }

                    else

                    {

                        discountamount = Convert.ToDecimal(txtDiscountAmount.Text);

                    }

                    if (checkboxDiscountPercentage.Checked)

                    {

                        grosstotal = (Qty * rate);

                        decimal discountpercentage = (grosstotal * discountamount) / 100;

                        decimal total = grosstotal - discountpercentage;

                        decimal balance = total;// - dis;

                        totalprice = balance;

                    }

                    else

                    {

                        if (checkboxApplyallDiscount.Checked == false)

                        {

                            grosstotal = (Qty * rate);

                            decimal total = (Qty * rate) - discountamount;

                            decimal balance = total;// - dis;

                            totalprice = balance;

                        }

                        else

                        {

                            grosstotal = (Qty * rate);

                            decimal total = (Qty * rate);

                            decimal balance = total;// - dis;

                            totalprice = balance;

                        }

                    }

                }

                else

                {

                    decimal rate = 0.00m;

                    decimal Qty = 0;

                    decimal discountamount = 0.00m;

                    if (!string.IsNullOrEmpty(txtRate.Text))

                    {

                        rate = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));

                    }

                    if (!string.IsNullOrEmpty(txtQty.Text))

                    {

                        Qty = Convert.ToDecimal(txtQty.Text);

                    }

                    if (txtDiscountAmount.Text != "" && txtDiscountAmount.Text != "")

                    {

                        discountamount = Convert.ToDecimal(txtDiscountAmount.Text);

                    }


                    decimal total = Qty * rate;

                    totalprice = total;

                }

                if (isSave)

                {

                    if (ActiveId <= 0 && PIActiveId <= 0)

                    {

                        // GridViewPurchaseReq.DataSource = null;

                    }

                    if (GridViewPurchaseReq.Rows.Count > 0)

                    {

                        if (PIActiveId > 0)

                        {

                            if (ViewState["MyDate"] != null)

                            {

                                activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                            }

                            int index = rowIndex;

                            PurchaseQuotationDtl activePurchase = new PurchaseQuotationDtl();

                            activePurchase.Id = PIActiveId;

                            activePurchase.PurReqId = PurchaseReqId;

                            activePurchase.PickDataID = PickDataID;

                            if (!String.IsNullOrEmpty(lblProductId.Text))

                            {

                                activePurchase.ProductId = Convert.ToInt32(lblProductId.Text);


                            }

                            activePurchase.ProductName = txtProduct.Text;

                            activePurchase.UnitID = Convert.ToInt32(ddlUnit.SelectedValue);

                            activePurchase.UnitName = ddlUnit.SelectedItem.Text;

                            //activePurchase.UnitName 

                            activePurchase.PurQuoNo = PropFinalCode;

                            activePurchase.Qty = string.IsNullOrEmpty(txtQty.Text) ? 0 : Convert.ToDecimal(txtQty.Text);

                            activePurchase.ProGrpName = txtUnit.Text;

                            activePurchase.UnitPrice = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));

                            activePurchase.CurrencyId = Convert.ToInt32(ddlCurrency.SelectedValue);

                            activePurchase.CurrencyRate = Convert.ToDecimal(txtCurrencyRate.Text);

                            activePurchase.ConversionRateofCurrency = CalculateCurrencyRate(activePurchase.CurrencyId, activePurchase.CurrencyRate);

                            activePurchase.PageNumber = txtPageNumber.Text;

                            activePurchase.ItemRef = txtItemRef.Text;

                            activePurchase.SerialNumber = txtSerialNumber.Text;

                            activePurchase.Remarks = txtRemarks.Text;

                            activePurchase.BalanceQty = string.IsNullOrEmpty(txtBalQty.Text) ? 0 : Convert.ToDecimal(txtBalQty.Text);

                            activePurchase.ispickBalId = ispickBalId.Checked;

                            if (txtDiscountAmount.Text == "")

                            {

                                activePurchase.Discount = 0;

                            }

                            else

                            {

                                if (checkboxApplyallDiscount.Checked)

                                {

                                    activePurchase.Discount = 0;

                                }

                                else

                                {

                                    if (checkboxApplytoall.Checked)

                                    {

                                        if (txtDiscountAmount.Text == "")

                                        {

                                            activePurchase.Discount = Convert.ToDecimal(txtDiscountTotal.Text);

                                        }

                                        else

                                        {

                                            activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                                        }

                                    }

                                    else

                                    {

                                        activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                                    }

                                }

                            }

                            if (checkboxDiscountPercentage.Checked)

                            {

                                grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                                discountpercentage = (grosstotal * activePurchase.Discount) / 100;

                                activePurchase.DiscountAmount = discountpercentage;

                                decimal total = grosstotal - discountpercentage;

                                decimal balance = total;// - dis;

                                totalprice = balance;

                                activePurchase.DiscountPercentage = true;

                                if (checkboxApplytoall.Checked)

                                {

                                    checkboxApplytoall.Disabled = true;

                                }

                            }

                            else

                            {

                                if (checkboxApplyallDiscount.Checked == false)

                                {

                                    grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                                    decimal total = (activePurchase.Qty * activePurchase.UnitPrice) - activePurchase.Discount;

                                    activePurchase.DiscountAmount = activePurchase.Discount;

                                    decimal balance = total;// - dis;

                                    totalprice = balance;

                                    activePurchase.DiscountPercentage = false;

                                    //txtDiscountAmount.Enabled = false;

                                    txtDiscountAmount.Enabled = true;

                                }

                                else

                                {

                                    grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                                    decimal total = (activePurchase.Qty * activePurchase.UnitPrice);

                                    decimal balance = total;// - dis;

                                    totalprice = balance;

                                    activePurchase.DiscountPercentage = false;

                                    checkboxApplyallDiscount.Checked = true;

                                    checkboxApplyallDiscount.Enabled = false;

                                }

                            }

                            activePurchase.Remarks = txtRemarks.Text;

                            string partnotext = txtPartNo.Text;

                            var partno = "";

                            //if (partnotext.IndexOf('-') != -1)

                            //{

                            //    partno = partnotext.Substring(0, partnotext.LastIndexOf('-'));

                            //    activePurchase.PartNo = partno;

                            //}

                            //else

                            //{

                            //    activePurchase.PartNo = partnotext;

                            //}

                            activePurchase.PartNo = partnotext;

                            activePurchase.Total = ApplyRuleofDecimalCurrency(totalprice);

                            activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                            //activePurchase.FcAmount = totalprice * activePurchase.CurrencyRate;

                            decimal ecost1 = activePurchase.UnitPrice * activePurchase.ConversionRateofCurrency;

                            ecost1 = ecost1;

                            activePurchase.FcUnitPrice = ecost1;

                            decimal ecost = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                            // ecost = Math.Floor(100 * ecost) / 100;

                            activePurchase.FcAmount = ApplyRuleofDecimalCurrency(ecost);

                            if (txtDiscountAmount.Text == "")

                            {

                                activePurchase.DiscountFc = 0;

                            }

                            else

                            {

                                if (checkboxApplyallDiscount.Checked)

                                {

                                    activePurchase.DiscountFc = 0;

                                }

                                else

                                {

                                    if (checkboxApplytoall.Checked)

                                    {

                                        if (txtDiscountAmount.Text == "")

                                        {

                                            activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountTotal.Text) * activePurchase.ConversionRateofCurrency;

                                        }

                                        else

                                        {

                                            activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountAmount.Text) * activePurchase.ConversionRateofCurrency;

                                        }

                                    }

                                    else

                                    {

                                        activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountAmount.Text) * activePurchase.ConversionRateofCurrency;

                                    }

                                }

                            }

                            if (checkboxDiscountPercentage.Checked)

                            {

                                grosstotal = ApplyRuleofDecimalCurrency(activePurchase.Price * activePurchase.ConversionRateofCurrency);

                                decimal discountpercentage = (grosstotal * (activePurchase.Discount)) / 100;

                                //discountpercentage = TruncateDecimal(discountpercentage, 2);

                                activePurchase.DiscountFcAmount = discountpercentage;

                                activePurchase.DiscountFc = activePurchase.Discount;

                                decimal total = grosstotal - discountpercentage;

                                decimal balance = total;// - dis;

                                activePurchase.AfterDiscountFcAmount = ApplyRuleofDecimalCurrency(activePurchase.Total * activePurchase.ConversionRateofCurrency);

                                // activePurchase.DiscountTotal = grosstotal;

                                activePurchase.DiscountPercentage = true;

                                if (checkboxApplytoall.Checked)

                                {

                                    // checkboxApplytoall.Disabled = true;

                                    //txtDiscountAmount.Enabled = false;

                                }

                            }

                            else

                            {

                                if (checkboxApplyallDiscount.Checked == false)

                                {

                                    grosstotal = (activePurchase.FcAmount);

                                    decimal total = (activePurchase.FcAmount) - activePurchase.DiscountFc;

                                    decimal balance = total;// - dis;

                                    activePurchase.DiscountFcAmount = activePurchase.DiscountFc;

                                    activePurchase.DiscountFc = activePurchase.DiscountFc;

                                    activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

                                    activePurchase.DiscountPercentage = false;

                                }

                                else

                                {

                                }

                            }

                            activePurchase.DiscountTotal = totalprice;

                            activePurchase.Status = status;

                            activePurchase.IsPickData = isPickData;

                            if (ddlVatDiscount.SelectedIndex > 0 && Convert.ToDecimal(txtDiscountVATPercentage.Text) > 0)

                            {

                                GetVatAmount = activePurchase.Total / 100 * Convert.ToDecimal(txtDiscountVATPercentage.Text);

                                activePurchase.VATPercentage = Convert.ToDecimal(txtDiscountVATPercentage.Text);

                                activePurchase.AfterVATTotal = GetVatAmount + activePurchase.Total;

                                activePurchase.AfterVATTotalFC = (GetVatAmount * activePurchase.ConversionRateofCurrency) + activePurchase.AfterDiscountFcAmount;

                                activePurchase.VATId = Convert.ToInt32(ddlVatDiscount.SelectedValue);


                            }

                            else

                            {

                                activePurchase.AfterVATTotal = activePurchase.Total;

                                activePurchase.AfterVATTotalFC = activePurchase.AfterDiscountFcAmount;

                            }

                            activePurchase.VATAmount = GetVatAmount;

                            activePurchaseList.RemoveAt(index);

                            activePurchaseList.Insert(index, activePurchase);

                        }

                        else

                        {

                            if (ActiveId <= 0)

                            {

                                if (ViewState["MyDate"] != null)

                                {

                                    activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                                }

                                GridViewPurchaseReq.DataSource = null;

                            }

                            if (ViewState["CurrentDate"] != null)

                            {

                                activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["CurrentDate"];

                            }

                            bool isDuplicate = CheckForDuplicate(Convert.ToInt32(lblProductId.Text), txtProduct.Text);

                            if (!isDuplicate)

                            {

                                PurchaseQuotationDtl activePurchaseQuotationDtl = PurchaseQuotationDtlPost();

                                activePurchaseList.Add(activePurchaseQuotationDtl);

                            }

                            else

                            {

                                string message = "Already add this (" + txtProduct.Text + ") product please edit";

                                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('" + message + "');", true);

                            }

                        }

                    }

                    else

                    {

                        PurchaseQuotationDtl activePurchase = new PurchaseQuotationDtl();

                        activePurchase.Id = 0;

                        activePurchase.PurReqId = PurchaseReqId;

                        activePurchase.PickDataID = PickDataID;

                        if (!String.IsNullOrEmpty(lblProductId.Text))

                        {

                            activePurchase.ProductId = Convert.ToInt32(lblProductId.Text);

                        }

                        activePurchase.ProductName = txtProduct.Text;

                        activePurchase.UnitID = Convert.ToInt32(ddlUnit.SelectedValue);

                        activePurchase.UnitName = ddlUnit.SelectedItem.Text;

                        activePurchase.PurQuoNo = PropFinalCode;

                        activePurchase.Qty = string.IsNullOrEmpty(txtQty.Text) ? 0 : Convert.ToDecimal(txtQty.Text);

                        activePurchase.ProGrpName = txtUnit.Text;

                        activePurchase.UnitPrice = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));

                        activePurchase.CurrencyId = Convert.ToInt32(ddlCurrency.SelectedValue);

                        activePurchase.CurrencyRate = Convert.ToDecimal(txtCurrencyRate.Text);

                        activePurchase.ConversionRateofCurrency = CalculateCurrencyRate(activePurchase.CurrencyId, activePurchase.CurrencyRate);

                        activePurchase.PageNumber = txtPageNumber.Text;

                        activePurchase.ItemRef = txtItemRef.Text;

                        activePurchase.SerialNumber = txtSerialNumber.Text;

                        activePurchase.Remarks = txtRemarks.Text;

                        activePurchase.BalanceQty = string.IsNullOrEmpty(txtBalQty.Text) ? 0 : Convert.ToDecimal(txtBalQty.Text);

                        activePurchase.ispickBalId = ispickBalId.Checked;

                        if (txtDiscountAmount.Text == "")

                        {

                            activePurchase.Discount = 0;

                        }

                        else

                        {

                            if (checkboxApplyallDiscount.Checked)

                            {

                                activePurchase.Discount = 0;

                            }

                            else

                            {

                                if (checkboxApplytoall.Checked)

                                {

                                    if (txtDiscountAmount.Text == "")

                                    {

                                        activePurchase.Discount = Convert.ToDecimal(txtDiscountTotal.Text);

                                    }

                                    else

                                    {

                                        activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                                    }

                                }

                                else

                                {

                                    activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                                }

                            }

                        }

                        if (checkboxDiscountPercentage.Checked)

                        {

                            grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                            decimal discountpercentage = (grosstotal * activePurchase.Discount) / 100;

                            // discountpercentage = TruncateDecimal(discountpercentage, 2);

                            activePurchase.DiscountAmount = discountpercentage;

                            decimal total = grosstotal - discountpercentage;

                            decimal balance = total;// - dis;

                            totalprice = balance;

                            activePurchase.DiscountPercentage = true;

                            if (checkboxApplytoall.Checked)

                            {

                                checkboxApplytoall.Disabled = true;

                                txtDiscountAmount.Enabled = false;

                            }

                        }

                        else

                        {

                            if (checkboxApplyallDiscount.Checked == false)

                            {

                                grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                                decimal total = (activePurchase.Qty * activePurchase.UnitPrice) - activePurchase.Discount;

                                activePurchase.DiscountAmount = activePurchase.Discount;

                                decimal balance = total;// - dis;

                                totalprice = balance;

                                activePurchase.DiscountPercentage = false;

                            }

                            else

                            {

                                grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                                decimal total = (activePurchase.Qty * activePurchase.UnitPrice);

                                decimal balance = total;// - dis;

                                totalprice = balance;

                                activePurchase.DiscountPercentage = false;

                                checkboxApplyallDiscount.Checked = true;

                                checkboxApplyallDiscount.Enabled = false;

                            }

                        }

                        activePurchase.Remarks = txtRemarks.Text;

                        string partnotext = txtPartNo.Text;

                        var partno = "";

                        //if (partnotext.IndexOf('-') != -1)

                        //{

                        //    partno = partnotext.Substring(0, partnotext.LastIndexOf('-'));

                        //    activePurchase.PartNo = partno;

                        //}

                        //else

                        //{

                        //    activePurchase.PartNo = partnotext;

                        //}

                        activePurchase.PartNo = partnotext;

                        activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                        activePurchase.DiscountTotal = totalprice;

                        activePurchase.Total = ApplyRuleofDecimalCurrency(totalprice);

                        decimal ecost1 = activePurchase.UnitPrice * activePurchase.ConversionRateofCurrency;

                        ecost1 = ecost1;

                        activePurchase.FcUnitPrice = ecost1;

                        decimal ecost = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                        // ecost = Math.Floor(100 * ecost) / 100;

                        activePurchase.FcAmount = ecost;

                        if (txtDiscountAmount.Text == "")

                        {

                            activePurchase.DiscountFc = 0;

                        }

                        else

                        {

                            if (checkboxApplyallDiscount.Checked)

                            {

                                activePurchase.DiscountFc = 0;

                            }

                            else

                            {

                                if (checkboxApplytoall.Checked)

                                {

                                    if (txtDiscountAmount.Text == "")

                                    {

                                        activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountTotal.Text) * activePurchase.ConversionRateofCurrency;

                                    }

                                    else

                                    {

                                        activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountAmount.Text) * activePurchase.ConversionRateofCurrency;

                                    }

                                }

                                else

                                {

                                    activePurchase.DiscountFc = Convert.ToDecimal(txtDiscountAmount.Text) * activePurchase.ConversionRateofCurrency;

                                }

                            }

                        }

                        if (checkboxDiscountPercentage.Checked)

                        {

                            grosstotal = (activePurchase.FcAmount);

                            decimal discountpercentage = (grosstotal * (activePurchase.Discount)) / 100;

                            activePurchase.DiscountFc = activePurchase.Discount;

                            activePurchase.DiscountFcAmount = discountpercentage;

                            decimal total = activePurchase.Total - discountpercentage;

                            decimal balance = total;// - dis;

                            activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

                            activePurchase.DiscountPercentage = true;

                            if (checkboxApplytoall.Checked)

                            {

                            }

                        }

                        else

                        {

                            if (checkboxApplyallDiscount.Checked == false)

                            {

                                grosstotal = (activePurchase.Total * activePurchase.ConversionRateofCurrency);

                                decimal total = (grosstotal) - activePurchase.DiscountFc;

                                decimal balance = total;// - dis;

                                activePurchase.DiscountFcAmount = activePurchase.DiscountFc;

                                activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

                                activePurchase.DiscountPercentage = false;

                            }

                            else

                            {

                            }

                        }

                        activePurchase.Status = status;

                        if (checkboxApplyallDiscount.Checked)

                        {

                            txtDiscountTotal.Text = activePurchase.Discount.ToString();

                            activePurchase.Discount = 0;

                        }

                        if (checkboxApplyallDiscountPercentage.Checked)

                        {

                            txtDiscountTotal.Text = activePurchase.Discount.ToString();

                            activePurchase.Discount = 0;

                        }


                        if (ddlVatDiscount.SelectedIndex > 0 && Convert.ToDecimal(txtDiscountVATPercentage.Text) > 0)

                        {

                            GetVatAmount = activePurchase.Total / 100 * Convert.ToDecimal(txtDiscountVATPercentage.Text);

                            activePurchase.VATPercentage = Convert.ToDecimal(txtDiscountVATPercentage.Text);

                            activePurchase.AfterVATTotal = GetVatAmount + activePurchase.Total;

                            activePurchase.AfterVATTotalFC = (GetVatAmount * activePurchase.ConversionRateofCurrency) + activePurchase.AfterDiscountFcAmount;

                            activePurchase.VATId = Convert.ToInt32(ddlVatDiscount.SelectedValue);


                        }

                        else

                        {

                            activePurchase.AfterVATTotal = activePurchase.Total;

                            activePurchase.AfterVATTotalFC = activePurchase.AfterDiscountFcAmount;

                        }

                        activePurchase.VATAmount = GetVatAmount;


                        activePurchaseList.Add(activePurchase);

                    }

                    GridViewPurchaseReq.DataSource = activePurchaseList;

                    GridViewPurchaseReq.DataBind();

                    ViewState["MyDate"] = activePurchaseList;

                    ViewState["PurchaseQuottion"] = activePurchaseList;

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return isSave;

        }

        public void CalculateFooterArea()

        {

            decimal SubSum = 0;

            decimal subsumFC = 0;

            decimal Discount = 0;

            decimal Discountfc = 0;

            decimal SumTotal = 0;

            decimal TotalFC = 0;

            decimal FcDiscountper = 0;

            decimal FcDiscount = 0;

            List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["PurchaseQuottion"];

            if (activePurchaseList != null)

            {

                foreach (PurchaseQuotationDtl item in activePurchaseList)

                {

                    SubSum += Convert.ToDecimal(item.Price);

                    subsumFC += Convert.ToDecimal(item.FcAmount);


                    if (item.DiscountPercentage == true && item.PickDataID > 0)

                    {

                        Discount += SubSum * Convert.ToDecimal(item.DiscountAmount) / 100;

                    }

                    else

                    {

                        Discount += Convert.ToDecimal(item.DiscountAmount);

                    }

                    Discountfc += Convert.ToDecimal(item.DiscountFcAmount);

                    FcDiscountper += Convert.ToDecimal(item.DiscountFc);

                    //TotalFC += Convert.ToDecimal(item.AfterDiscountFcAmount);

                    //SumTotal += Convert.ToDecimal(item.Total);

                    TotalFC += Convert.ToDecimal(item.AfterVATTotalFC);

                    SumTotal += Convert.ToDecimal(item.AfterVATTotal);

                }

            }

            //+Convert.ToDecimal(item.AfterVATTotalFC)  + Convert.ToDecimal(item.AfterVATTotal)

            txtSubTotal.Text = string.Format("{0:n}", SubSum);

            txtsubtotalFC.Text = string.Format("{0:n}", subsumFC);

            txtDiscountTotal.Text = string.Format("{0:n}", Discount);

            txtdiscountFc.Text = string.Format("{0:n}", Discountfc);

            txtTotal.Text = string.Format("{0:n}", SumTotal);

            txtFcTotal.Text = string.Format("{0:n}", TotalFC);

            if (Discountfc <= 0)

            {

                FcDiscount = subsumFC * FcDiscountper / 100;

                txtdiscountFc.Text = string.Format("{0:n}", FcDiscount);

            }

        }

        private PurchaseQuotationDtl PurchaseQuotationDtlPost()

        {

            decimal grosstotal = 0.00m;

            PurchaseQuotationDtl activePurchase = new PurchaseQuotationDtl();

            activePurchase.Id = 0;

            activePurchase.ProductName = txtProduct.Text;

            activePurchase.UnitID = Convert.ToInt32(ddlUnit.SelectedValue);

            activePurchase.UnitName = ddlUnit.SelectedItem.Text;

            //activePurchase.pr = txtCode.Value;

            string partnotext = txtPartNo.Text;

            var partno = "";

            //if (partnotext.IndexOf('-') != -1)

            //{

            //    partno = partnotext.Substring(0, partnotext.LastIndexOf('-'));

            //    activePurchase.PartNo = partno;

            //}

            //else

            //{

            //    activePurchase.PartNo = partnotext;

            //}

            activePurchase.PartNo = partnotext;

            activePurchase.Qty = Convert.ToDecimal(txtQty.Text);

            activePurchase.ProGrpName = txtUnit.Text;

            activePurchase.UnitPrice = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));

            activePurchase.CurrencyId = Convert.ToInt32(ddlCurrency.SelectedValue);

            activePurchase.CurrencyRate = Convert.ToDecimal(txtCurrencyRate.Text);

            activePurchase.ConversionRateofCurrency = CalculateCurrencyRate(activePurchase.CurrencyId, activePurchase.CurrencyRate);

            activePurchase.PageNumber = txtPageNumber.Text;

            activePurchase.ItemRef = txtItemRef.Text;

            activePurchase.SerialNumber = txtSerialNumber.Text;

            activePurchase.Remarks = txtRemarks.Text;

            activePurchase.BalanceQty = string.IsNullOrEmpty(txtBalQty.Text) ? 0 : Convert.ToDecimal(txtBalQty.Text);

            activePurchase.ispickBalId = ispickBalId.Checked;

            if (checkboxApplytoall.Checked)

            {

                if (txtDiscountAmount.Text == "")

                {

                    activePurchase.Discount = Convert.ToDecimal(txtDiscountTotal.Text);

                }

                else

                {

                    activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                }

            }

            else

            {

                if (checkboxApplyallDiscount.Checked)

                {

                    if (txtDiscountAmount.Text != "")

                    {

                        activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                    }

                    else

                    {

                        activePurchase.Discount = Convert.ToDecimal(txtDiscountTotal.Text);

                    }

                }

                else

                {

                    if (txtDiscountAmount.Text != "")

                    {

                        activePurchase.Discount = Convert.ToDecimal(txtDiscountAmount.Text);

                    }

                    else

                    {

                        activePurchase.Discount = 0;

                    }

                }

            }

            if (checkboxDiscountPercentage.Checked)

            {

                grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                decimal discountpercentage = (grosstotal * activePurchase.Discount) / 100;

                //  discountpercentage = TruncateDecimal(discountpercentage, 2);

                activePurchase.DiscountAmount = discountpercentage;

                decimal total = grosstotal - discountpercentage;

                activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                activePurchase.Total = ApplyRuleofDecimalCurrency(total);

                decimal ecost1 = activePurchase.UnitPrice * activePurchase.ConversionRateofCurrency;

                ecost1 = ecost1;

                activePurchase.FcUnitPrice = ecost1;

                decimal ecost = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                activePurchase.FcAmount = ecost;

                activePurchase.DiscountTotal = total;

                activePurchase.DiscountPercentage = true;

                grosstotal = (activePurchase.Total * activePurchase.ConversionRateofCurrency);

                decimal discountpercentagefc = (grosstotal * (activePurchase.Discount)) / 100;

                activePurchase.DiscountFcAmount = discountpercentagefc;

                activePurchase.DiscountFc = activePurchase.Discount;

                activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

            }

            else

            {

                if (checkboxApplyallDiscount.Checked == false)

                {

                    grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                    decimal total = (activePurchase.Qty * activePurchase.UnitPrice) - activePurchase.Discount;

                    activePurchase.DiscountAmount = activePurchase.Discount;

                    activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                    activePurchase.Total = ApplyRuleofDecimalCurrency(total);

                    decimal ecost1 = activePurchase.UnitPrice * activePurchase.ConversionRateofCurrency;

                    ecost1 = ecost1;

                    activePurchase.FcUnitPrice = ecost1;

                    decimal ecost = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                    activePurchase.FcAmount = ecost;

                    activePurchase.DiscountTotal = total;

                    activePurchase.DiscountPercentage = false;

                    grosstotal = (activePurchase.Price * activePurchase.ConversionRateofCurrency);

                    activePurchase.DiscountFc = (activePurchase.Discount * activePurchase.ConversionRateofCurrency);

                    activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

                    activePurchase.DiscountFcAmount = (activePurchase.Discount * activePurchase.ConversionRateofCurrency);

                }

                else

                {

                    grosstotal = (activePurchase.Qty * activePurchase.UnitPrice);

                    decimal total = (activePurchase.Qty * activePurchase.UnitPrice);

                    activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                    activePurchase.Total = ApplyRuleofDecimalCurrency(grosstotal);

                    decimal ecost1 = activePurchase.UnitPrice * activePurchase.ConversionRateofCurrency;

                    ecost1 = ecost1;

                    activePurchase.FcUnitPrice = ecost1;

                    decimal ecost = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                    activePurchase.FcAmount = ecost;

                    activePurchase.DiscountTotal = total;

                    activePurchase.DiscountPercentage = false;

                    checkboxApplyallDiscount.Checked = true;

                    checkboxApplyallDiscount.Enabled = false;

                }

            }

            if (checkboxApplyallDiscount.Checked)

            {

                activePurchase.Discount = 0;

            }

            if (!String.IsNullOrEmpty(lblProductId.Text))

            {

                activePurchase.ProductId = Convert.ToInt32(lblProductId.Text);

            }

            if (ddlVatDiscount.SelectedIndex > 0 && Convert.ToDecimal(txtDiscountVATPercentage.Text) > 0)

            {

                GetVatAmount = activePurchase.Total / 100 * Convert.ToDecimal(txtDiscountVATPercentage.Text);

                activePurchase.VATPercentage = Convert.ToDecimal(txtDiscountVATPercentage.Text);

                activePurchase.AfterVATTotal = GetVatAmount + activePurchase.Total;

                activePurchase.AfterVATTotalFC = (GetVatAmount * activePurchase.ConversionRateofCurrency) + activePurchase.AfterDiscountFcAmount;

                activePurchase.VATId = Convert.ToInt32(ddlVatDiscount.SelectedValue);


            }

            else

            {

                activePurchase.AfterVATTotal = activePurchase.Total;

                activePurchase.AfterVATTotalFC = activePurchase.AfterDiscountFcAmount;

            }

            activePurchase.VATAmount = GetVatAmount;

            return activePurchase;

        }

        private void DisplayProduct(int ActiveId)

        {

            try

            {

                ProductDAL activeDAL = new ProductDAL();

                Product activeProduct = activeDAL.ProductGetById(ActiveId);

                if (activeProduct != null)

                {

                    ProductId = activeProduct.Id;

                    txtRate.Text = ApplyFormatofCurrency(activeProduct.CostPrice);

                    txtUnit.Text = activeProduct.ProGrpName;

                    lblUnit.Text = activeProduct.UnitName;

                    if (activeProduct.Qty != 0)

                    {

                        lblOverAlLStock.Text = "Over All Stock= " + activeProduct.Qty.ToString();

                    }

                    else

                    {

                        lblOverAlLStock.Text = "Over All Stock=0";

                    }

                    WarehouseQtyDAL activeWQDAL = new WarehouseQtyDAL();

                    WarehouseQty activeWQ = activeWQDAL.WarehouseQtyGetByProductIdWarehouseId(ProductId, WarehouseId);

                    if (activeWQ != null)

                    {

                        locationStock.Text = "Location Stock= " + activeWQ.WarehouseQty1.ToString();

                    }

                    else

                    {

                        locationStock.Text = "Location Stock=0";

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        private void ClearProduct()

        {

            try

            {

                ddlUnit.ClearSelection();

                PIActiveId = 0;

                PIDtlId = 0;

                txtQty.Text = "0";

                txtUnit.Text = string.Empty;

                txtRate.Text = "0.00";

                FixedPrice(false);

                txtRemarks.Text = string.Empty;

                if (checkboxApplytoall.Checked == false)

                {

                    checkboxDiscountPercentage.Checked = false;

                    checkboxApplytoall.Checked = false;

                }

                if (checkboxApplyallDiscount.Checked == false)

                {

                    //txtDiscountAmount.Text = string.Empty;

                }

                else

                {

                    checkboxApplyallDiscount.Enabled = true;

                }

                txtPartNo.Text = string.Empty;

                txtProduct.Text = string.Empty;

                txtPageNumber.Text = string.Empty;

                txtItemRef.Text = string.Empty;

                txtSerialNumber.Text = string.Empty;

                lblproductqty.Text = "0.00";

                txtDiscountAmount.Text = "0.00";

                lbelwarehouseqrty.Text = "0.00";

                txtDiscountVATPercentage.Text = string.Empty;

                ddlVatDiscount.ClearSelection();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        protected void btnPost_Click(object sender, EventArgs e)

        {

            try

            {

                ProductId = Convert.ToInt32(lblProductId.Text);

                decimal GetQty = GetBalanceQty(PurchaseReqId, PickDataID);

                decimal balanceQty = 0;

                bool IspickedData = false;

                if (!string.IsNullOrEmpty(txtBalQty.Text))

                    balanceQty = Convert.ToDecimal(txtBalQty.Text);

                if (ispickBalId.Checked)

                    IspickedData = true;

                if (txtQty.Text == "")

                {

                    txtQty.Text = "0.00";

                }

                if (txtRate.Text == "")

                {

                    txtRate.Text = "0.00";

                }

                if (txtDiscountAmount.Text == "")

                {

                    txtDiscountAmount.Text = "0.00";

                }

                if (PIActiveId > 0)

                {

                    if (txtPartNo.Text == "")

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Please Enter Part No :');", true);

                    }

                    else if (txtProduct.Text == "")

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Please Enter Product :');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtQty.Text) && Convert.ToDecimal(txtQty.Text) <= 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Qty can not be less than or equal to zero [ 0 ]');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtRate.Text) && Convert.ToDecimal(txtRate.Text) <= 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Rate can not be less than or equal to zero [ 0.00 ]');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtDiscountAmount.Text) && Convert.ToDecimal(txtDiscountAmount.Text) < 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Discount can not be less than zero [ 0 ]');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtDiscountAmount.Text) && checkboxDiscountPercentage.Checked && checkboxDiscountPercentage.Checked && Convert.ToDecimal(txtDiscountAmount.Text) > 100)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Discount can not be greater than Hundred Percent [ 100% ]');", true);

                    }

                    else if (Convert.ToDecimal(txtQty.Text) > GetQty && ActiveId > 0 && isPick == true)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Quantity is greater than balance Quantity');", true);

                    }

                    else if (IspickedData == true && Convert.ToDecimal(txtQty.Text) > balanceQty)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Quantity is greater than balance Quantity');", true);

                    }

                    else

                    {

                        if (CheckAllWarehouse(ProductId))

                        {

                            Post();

                            //CalculateFooterArea();

                            ClearProduct();

                            PIActiveId = 0;

                        }

                        else

                        {

                            if (CheckWarehouseID(ProductId) == Convert.ToInt32(ddlWarehouse.SelectedValue))

                            {

                                Post();

                                // CalculateFooterArea();

                                ClearProduct();

                                PIActiveId = 0;

                            }

                            else

                            {

                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('This Product is not available in selected Warehouse')", true);

                            }

                        }

                    }

                }

                else

                {

                    if (txtPartNo.Text == "")

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Please Enter Part No :');", true);

                    }

                    else if (txtProduct.Text == "")

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Please Enter Product :');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtQty.Text) && Convert.ToDecimal(txtQty.Text) <= 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Qty can not be less than or equal to zero [ 0 ]');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtRate.Text) && Convert.ToDecimal(txtRate.Text) <= 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Rate can not be less than or equal to zero [ 0.00 ]');", true);

                    }

                    else if (!string.IsNullOrEmpty(txtDiscountAmount.Text) && Convert.ToDecimal(txtDiscountAmount.Text) < 0)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Discount can not be less than zero [ 0 ]');", true);

                    }

                    else if (checkboxDiscountPercentage.Checked && !string.IsNullOrEmpty(txtDiscountAmount.Text) && Convert.ToDecimal(txtDiscountAmount.Text) > 100)

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Detail Information : Discount can not be greater than Hundred Percent [ 100% ]');", true);

                    }


                    else

                    {

                        if (CheckAllWarehouse(ProductId))

                        {

                            if (Post())

                            {

                                //CalculateFooterArea();

                                //BindProduct();

                                ClearProduct();

                                PIActiveId = 0;

                            }

                        }

                        else

                        {

                            if (CheckWarehouseID(ProductId) == Convert.ToInt32(ddlWarehouse.SelectedValue))

                            {

                                if (Post())

                                {

                                    //CalculateFooterArea();

                                    //BindProduct();

                                    ClearProduct();

                                    PIActiveId = 0;

                                }

                            }

                            else

                            {

                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('This Product is not available in selected Warehouse')", true);

                            }

                        }

                    }


                }

                //txtProduct.Focus();

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        protected void GridViewPurchaseReq_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)

        {

            e.Cancel = true;

        }


        protected void GridViewPurchaseReq_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)

        {

            e.Cancel = true;

        }


        private void UpdateProduct(int id)

        {

            if (GridViewPurchaseReq.Rows.Count > 0)

            {

                List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];


                foreach (PurchaseQuotationDtl item in activePurchaseList)

                {

                    if (activePurchaseList.IndexOf(item) == id)

                    //if (item.Id == id)

                    {

                        WebDeskValidator Obj_VLDTR = new WebDeskValidator();

                        PIActiveId = 1;

                        PIDtlId = item.Id;

                        txtBalQty.Text = item.BalanceQty.ToString();

                        ispickBalId.Checked = item.ispickBalId;

                        txtProduct.Text = item.ProductName.ToString();

                        txtQty.Text = item.Qty.ToString("0.00");

                        txtRate.Text = ApplyFormatofCurrency(item.UnitPrice);

                        ProductDAL objProductDAL = new ProductDAL();

                        Product objProduct = new Product();

                        objProduct = objProductDAL.ProductGetById(item.ProductId);

                        FixedPrice(objProduct.FixedPrice);

                        // txtRateofBase.Text = "0.00";

                        txtRemarks.Text = item.Remarks;

                        txtUnit.Text = item.ProGrpName;

                        //txtDiscount.Text = item.PartNo.ToString();

                        txtPartNo.Text = item.PartNo;

                        PickDataID = item.PickDataID;

                        PurchaseReqId = item.PurReqId;

                        txtDiscountAmount.Text = ApplyFormatofCurrency(item.Discount);

                        lblProductId.Text = item.ProductId.ToString();

                        ddlCurrency.SelectedValue = item.CurrencyId.ToString();

                        txtCurrencyRate.Text = ApplyFormatofCurrency(item.CurrencyRate);

                        txtPageNumber.Text = item.PageNumber;

                        txtItemRef.Text = item.ItemRef;

                        txtSerialNumber.Text = item.SerialNumber;


                        if (item.DiscountPercentage == true)

                        {

                            checkboxDiscountPercentage.Checked = true;

                        }

                        else

                        {

                            checkboxDiscountPercentage.Checked = false;

                        }

                        ddlVatDiscount.SelectedValue = item.VATId.ToString();

                        txtDiscountVATPercentage.Text = item.VATPercentage.ToString();

                        int AllStock = Obj_VLDTR.AvailbeAllStock(Convert.ToInt32(lblProductId.Text));

                        lblproductqty.Text = AllStock.ToString();

                        int AllWarehouseStock = Obj_VLDTR.AvailbeStockWarehouse(ddlWarehouse.SelectedValue, Convert.ToInt32(lblProductId.Text));

                        lbelwarehouseqrty.Text = AllWarehouseStock.ToString();

                        if (ddlUnit.Items.FindByValue(item.UnitID.ToString()) != null)

                            ddlUnit.SelectedValue = item.UnitID.ToString();

                    }

                }

            }

        }

        protected void ddlTaxDiscount_SelectedIndexChanged(object sender, EventArgs e)

        {

            if (CheckVATAccount(Convert.ToInt32(ddlVatDiscount.SelectedValue)))

            {

                discTaxSelectChange(Convert.ToInt32(ddlVatDiscount.SelectedValue));

            }

            else if (ddlVatDiscount.SelectedValue != "0")

            {

                ddlVatDiscount.SelectedValue = "0";

                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Tax Cannnot Apply first select Tax account using discount tax master');", true);

            }

            else

            {

                txtDiscountVATPercentage.Text = "0.00";

            }

        }

        private bool CheckVATAccount(int VATID)

        {

            bool isValidVATAcc = false;

            activeDiscountTaxMaster = activeDiscountTaxMasterDAL.DiscountTaxMasterGetById(VATID);

            if (activeDiscountTaxMaster != null)

            {

                if (activeDiscountTaxMaster.ChartOfAccountID > 0)

                {

                    isValidVATAcc = true;


                }

                else

                {


                }


            }

            return isValidVATAcc;


        }

        private void discTaxSelectChange(int DiscountTaxId)

        {

            activeDiscountTaxMaster = activeDiscountTaxMasterDAL.DiscountTaxMasterGetById(DiscountTaxId);

            if (activeDiscountTaxMaster != null)

            {

                txtDiscountVATPercentage.Text = activeDiscountTaxMaster.Persentage.ToString();

                //dllVATEffect.SelectedItem.Text = dllVATEffect.Items.FindByText(activeDiscountTaxMaster.Effect).Text;

            }

            else

            {

                txtDiscountVATPercentage.Text = "0.00";

            }

        }

        protected void GridViewPurchaseReq_RowCommand(object sender, GridViewCommandEventArgs e)

        {


            //int selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());

            int selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());

            GridViewRow rows = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

            TextBox gridtxtProductName = (TextBox)rows.FindControl("gridtxtProductName");

            TextBox gridtxtQty = (TextBox)rows.FindControl("gridtxtQty");

            TextBox gridtxtUnitPrice = (TextBox)rows.FindControl("gridtxtUnitPrice");

            TextBox gridtxtDiscount = (TextBox)rows.FindControl("gridtxtDiscount");

            TextBox gridtxtUnitName = (TextBox)rows.FindControl("gridtxtUnitName");

            Label gridlbldiscountper = (Label)rows.FindControl("gridlbldiscountper");

            if (e.CommandName.ToString() == "ColumnClick")

            {

                foreach (GridViewRow r in GridViewPurchaseReq.Rows)

                {

                    if (r.RowType == DataControlRowType.DataRow)

                    {

                        for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)

                        {

                            r.Cells[columnIndex].Attributes["style"] += "background-color:White;";


                            // GridViewPurchaseReq.Rows[selectedRowIndex].Cells[selectedColumnIndex].Focus();



                        }

                    }

                }


                //gridtxtProductName.ReadOnly = false;

                gridtxtQty.ReadOnly = false;

                gridtxtUnitPrice.ReadOnly = false;

                if (gridlbldiscountper.Text == "True")

                {

                    checkboxDiscountPercentage.Checked = true;

                    gridtxtDiscount.ReadOnly = false;


                }

                else

                {

                    gridtxtDiscount.ReadOnly = false;

                }


            }




            if (e.CommandName == "Edit")

            {

                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);


                rowIndex = row.RowIndex;

                int id = Convert.ToInt32(e.CommandArgument);

                //bool IsConvertedtoQuotation = GetPurchaseQuotationDtl(rowIndex);

                //if (!IsConvertedtoQuotation)

                //{

                UpdateProduct(rowIndex);

                //}

                //else

                //{

                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Cannot Edit this Item because it is Pick in Purchase Order');", true);

                //}

            }

            else if (e.CommandName == "Delete")

            {

                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                rowIndex = row.RowIndex;

                int id = Convert.ToInt32(e.CommandArgument);

                //bool IsConvertedtoQuotation = GetPurchaseQuotationDtl(rowIndex);

                //if (!IsConvertedtoQuotation)

                //{

                List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                activePurchaseList.RemoveAt(rowIndex);

                GridViewPurchaseReq.DataSource = activePurchaseList;

                GridViewPurchaseReq.DataBind();

                rowIndex = rowIndex - 1;

                ViewState["MyDate"] = activePurchaseList;

                ViewState["PurchaseQuottion"] = activePurchaseList;


                if (GridViewPurchaseReq.Rows.Count == 0)

                    ddlpricelist.Enabled = true;

                //}

                //else

                //{

                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Cannot Delete this Item because it is Pick in Purchase Order');", true);

                //}

            }

        }


        decimal totSubTot = 0;

        decimal FCTotal = 0;

        decimal FCFTotal = 0;

        decimal TotalBeforeDiscount = 0;

        decimal VATTotal = 0;

        decimal VATTotalFC = 0;

        protected void GridViewPurchaseReq_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

                decimal dis = 0.00m;

                ddlpricelist.Enabled = false;


                TextBox lblunitprice = (TextBox)e.Row.FindControl("gridtxtUnitPrice");

                TextBox lblqty = (TextBox)e.Row.FindControl("gridtxtQty");

                Label lbldiscountper = (Label)e.Row.FindControl("gridlbldiscountper");

                TextBox gridtxtDiscount = (TextBox)e.Row.FindControl("gridtxtDiscount");

                TextBox gridtxtPrice = (TextBox)e.Row.FindControl("gridtxtPrice");

                TextBox gridtxtFcAmount = (TextBox)e.Row.FindControl("gridtxtFcAmount");

                TextBox gridtxtTotal = (TextBox)e.Row.FindControl("gridtxtTotal");

                TextBox gridtxtAfterDiscountFcAmount = (TextBox)e.Row.FindControl("gridtxtAfterDiscountFcAmount");

                Label lblVATAmount = (Label)e.Row.FindControl("lblVATAmount");

                Label gridlblAmount = (Label)e.Row.FindControl("gridlblAmount");  //Label For After Vat Total 

                Label gridlblFcAmount = (Label)e.Row.FindControl("gridlblFcAmount");  //Label For After Vat Total FC


                totSubTot += decimal.Parse(gridtxtPrice.Text.ToString());

                FCTotal += decimal.Parse(gridlblAmount.Text.ToString());

                FCFTotal += decimal.Parse(gridlblFcAmount.Text);

                VATTotal += decimal.Parse(lblVATAmount.Text);


                if (lbldiscountper.Text == "True")

                {

                    if (!string.IsNullOrEmpty(lblunitprice.Text))

                    {

                        rate = Convert.ToDecimal(lblunitprice.Text);

                    }

                    if (!string.IsNullOrEmpty(lblqty.Text))

                    {

                        Qty = Convert.ToDecimal(lblqty.Text);

                    }

                    dis = Convert.ToDecimal(gridtxtDiscount.Text);

                    decimal aD = (Qty * rate);

                    decimal bD = (aD * dis) / 100;

                    //  bD = TruncateDecimal(bD, 2);

                    decimal cD = aD - dis;

                    discountsum += bD;

                }

                else

                {

                    if (gridtxtDiscount.Text == "0.00")

                    {

                        if (!String.IsNullOrEmpty(txtDiscountAmount.Text))

                        {

                            discountsum = 0;// Convert.ToDecimal(txtDiscountAmount.Text);

                        }

                    }

                    else

                    {

                        dis = Convert.ToDecimal(gridtxtDiscount.Text);

                        if (e.Row.Cells[8].Text != "True")

                        {

                            discountsum += decimal.Parse(gridtxtDiscount.Text);

                        }

                    }


                }


                if (discountsum == 0)

                {

                    if (!string.IsNullOrEmpty(txtDiscountTotal.Text))

                    {

                        discountsum = Convert.ToDecimal(txtDiscountTotal.Text);

                    }


                }




                txtTotal.Text = ApplyFormatofCurrency(FCTotal);

                txtFcTotal.Text = ApplyFormatofCurrency(FCFTotal);

                txtSubTotal.Text = ApplyFormatofCurrency(totSubTot);

                txtsubtotalFC.Text = ApplyFormatofCurrency(totSubTot);

                //txtdiscountFc.Text = FCFTotal.ToString("0.00");

                decimal netvalue = Math.Abs(discountsum);

                txtDiscountTotal.Text = ApplyFormatofCurrency(netvalue);

                txtdiscountFc.Text = ApplyFormatofCurrency(netvalue);

                decimal ConversionRateofCurrency = CalculateCurrencyRate(Convert.ToInt32(ddlCurrency.SelectedValue), Convert.ToDecimal(txtCurrencyRate.Text != "" ? txtCurrencyRate.Text : 0.ToString()));

                VATTotalFC = (VATTotal * ConversionRateofCurrency);

                txtVATTotalAmount.Text = ApplyFormatofCurrency(VATTotal);

                txtVATFcTotal.Text = ApplyFormatofCurrency(VATTotalFC);

                if (checkboxApplyallDiscount.Checked)

                {

                    if (!String.IsNullOrEmpty(txtDiscountTotal.Text))

                    {

                        txtTotal.Text = ApplyFormatofCurrency((FCTotal - Convert.ToDecimal(txtDiscountTotal.Text)));

                        txtFcTotal.Text = ApplyFormatofCurrency((FCTotal - Convert.ToDecimal(txtDiscountTotal.Text) * decimal.Parse(e.Row.Cells[10].Text.ToString())));


                    }

                }


                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];

                string _jsSingle = ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");

                // Add events to each editable cell

                for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex++)

                {

                    // Add the column index as the event argument parameter

                    string js = _jsSingle.Insert(_jsSingle.Length - 2, columnIndex.ToString());

                    // Add this javascript to the onclick Attribute of the cell

                    e.Row.Cells[columnIndex].Attributes["ondblclick"] = js;

                    // Add a cursor style to the cells

                    e.Row.Cells[columnIndex].Attributes["style"] += "cursor:pointer;cursor:hand;";

                }




            }

        }


        public void UpdatePurchaseRequistion(int? ActiveId)

        {

            try

            {

                PurchaseQuotationDAl activeDAL = new PurchaseQuotationDAl();

                PurchaseQuotation activePurchase = activePurchase = activeDAL.PurchaseQuotationGetById(ActiveId);// PurchaseRequistionGetByIdNew(ActiveId);

                if (activePurchase != null)

                {


                    ActiveId = activePurchase.PurQuoId;//  PurchaseRequistionId;

                    txtCode.Attributes.Add("value", activePurchase.PurQuoNo);

                    PropFinalCode = activePurchase.PurQuoNo;

                    ddlWarehouse.SelectedValue = ddlWarehouse.Items.FindByText(activePurchase.Location).Value;

                    txtNarration.Text = activePurchase.Remarks;

                    //  ddlEmployee.SelectedItem.Text = activePurchase.Employee;

                    if (ddlEmployee.Items.FindByText(activePurchase.Employee) != null)

                    {

                        ddlEmployee.SelectedIndex = ddlEmployee.Items.IndexOf(ddlEmployee.Items.FindByText(activePurchase.Employee));

                    }

                    ddlVendor.SelectedValue = activePurchase.VendorAccountCode;

                    ddlpricelist.SelectedValue = activePurchase.VendorPriceListId.ToString();

                    ddlJob.SelectedValue = activePurchase.JobId.ToString();

                    //ddlCurrency.SelectedValue = activePurchase.CurrencyId.ToString();

                    //txtCurrencyRate.Text = activePurchase.FcRate.ToString();

                    txtFcTotal.Text = ApplyFormatofCurrency(activePurchase.FcTotal);

                    txtClientPO.Text = activePurchase.ClientPoNo.ToString();

                    txtRefNo.Text = activePurchase.RefNo.ToString();

                    txtOurPO.Text = activePurchase.OurPoNo.ToString();


                    //CurrencyMasterDAL activeCurrencyDAL = new CurrencyMasterDAL();

                    //if (Convert.ToInt32(ddlCurrency.SelectedValue) != 0)

                    //{

                    //    CurrencyMaster ActiveMasterList = new CurrencyMaster();

                    //    ActiveMasterList = activeCurrencyDAL.CurrencyMasterGetById(Convert.ToInt32(ddlCurrency.SelectedValue));

                    //    if (ActiveMasterList != null)

                    //    {

                    //        txtCurrencyRate.Text = ActiveMasterList.FcRate.ToString();

                    //    }


                    //}

                    //else

                    //{

                    //    ddlCurrency.SelectedIndex = 0;

                    //    txtCurrencyRate.Text = "1.00";

                    //}

                    single_cal4.Text = activePurchase.Date.ToString("yyyy-MM-dd");

                    PurchaseQuotationDtLDAL avtivePODtlDAL = new PurchaseQuotationDtLDAL();

                    List<PurchaseQuotationDtl> activePODtl = avtivePODtlDAL.PurchaseQuotationDtlSelectByPoNo1(activePurchase.PurQuoNo, Convert.ToInt32(Session["FinancialYearID"]));

                    if (activePODtl != null)

                    {

                        ddlCurrency.Enabled = false;

                        txtCurrencyRate.Enabled = false;

                        decimal sum = 0;


                        foreach (PurchaseQuotationDtl item in activePODtl)

                        {

                            sum += Convert.ToDecimal(item.Total);


                            CurrencyMasterDAL activeCurrencyDAL = new CurrencyMasterDAL();

                            CurrencyMaster ActiveMasterList = new CurrencyMaster();

                            if (Convert.ToInt32(item.CurrencyId) != 0)

                            {

                                ActiveMasterList = activeCurrencyDAL.CurrencyMasterGetById(Convert.ToInt32(item.CurrencyId));

                                if (ActiveMasterList != null)

                                {

                                    lblCurrencyCode.Text = ActiveMasterList.CurrencyShortName;

                                    ddlCurrency.SelectedValue = item.CurrencyId.ToString();

                                    txtCurrencyRate.Text = ApplyFormatofCurrency(item.CurrencyRate);

                                }

                            }

                        }

                        GridViewPurchaseReq.DataSource = activePODtl;

                        GridViewPurchaseReq.DataBind();

                        ViewState["MyDate"] = activePODtl;

                        ViewState["PurchaseQuottion"] = activePODtl;


                        if (checkboxApplyallDiscount.Checked != true)

                        {

                            string totalfinal = String.Format("{0:n}", sum);

                            txtTotal.Text = ApplyFormatofCurrency(sum);

                        }



                        txtTotal.Text = ApplyFormatofCurrency(activePurchase.NetTotal);

                        txtFcTotal.Text = ApplyFormatofCurrency(activePurchase.FcTotal);


                        checkboxApplyallDiscountPercentage.Checked = activePurchase.DiscountAllPer;

                        checkboxApplyallDiscount.Checked = activePurchase.DiscountAllAmount;

                        if (activePurchase.NetDiscount > 0)

                        {

                            if (activePurchase.DiscountAllPer == true)

                            {

                                txtDiscountTotal.Text = ApplyFormatofCurrency(activePurchase.DiscountPer);

                                txtPerDiscount.Text = ApplyFormatofCurrency(activePurchase.NetDiscount);

                            }

                            else

                            {

                                txtDiscountTotal.Text = ApplyFormatofCurrency(activePurchase.NetDiscount);

                                txtPerDiscount.Text = "0.00";

                            }


                        }


                        List<TradeDocument> activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];


                        if (activeTradeDocumentList != null)

                        {

                            foreach (TradeDocument item in activeTradeDocumentList)

                            {

                                item.DocumentType = "Purchase Quotation";

                                item.MasterID = ActiveId;

                                item.UserID = Convert.ToInt32(Session["userid"]);

                                item.CompanyID = Convert.ToInt32(Session["companyid"]);

                                new TradeDocumentDAL().TradeDocumentInsert(item);

                            }

                        }

                    }

                }


                if (activePurchase.IsApproved || activePurchase.IsRejected)

                {

                    btnSave.Enabled = false;

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('Quotation cannot be edited because it is Approved or Rejected');", true);

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            //CalculateFooterArea();

        }


        public bool Save()

        {

            bool isSave = true;

            try

            {


                PurchaseQuotationDAl activeDAL = new PurchaseQuotationDAl();

                PurchaseQuotation activePurchase = new PurchaseQuotation();




                //activePurchase.Id = ActiveId;

                //activePurchase.PurQuoId = ActiveId;

                //activePurchase.PurQuoNo = txtCode.Value;


                if (Request.QueryString["Id"] != null)

                {

                    ActiveId = Convert.ToInt32(Request.QueryString["Id"]);

                    activePurchase.Id = ActiveId;

                    activePurchase.PurQuoId = ActiveId;

                    PropFinalCode = txtCode.Value;

                    activePurchase.PurQuoNo = txtCode.Value;

                }

                else

                {

                    activePurchase.Id = ActiveId = 0;

                    activePurchase.PurQuoId = ActiveId;

                    activePurchase.PurQuoNo = Initilaize();

                    if (!isPickData)

                    {

                        txtRefNo.Text = RefCode();

                    }

                    else

                    {

                        activePurchase.RefNo = txtRefNo.Text;

                    }

                    PropFinalCode = activePurchase.PurQuoNo;

                }


                if (ddlVendor.SelectedIndex > 0)

                {

                    activePurchase.VendorId = Convert.ToInt32(ddlVendor.SelectedValue);

                }


                activePurchase.VendorPriceListId = Convert.ToInt32(ddlpricelist.SelectedValue);


                if (!string.IsNullOrEmpty(ddlWarehouse.SelectedItem.Text))

                {

                    activePurchase.Location = ddlWarehouse.SelectedItem.Text;

                }


                activePurchase.VendorAccountCode = ddlVendor.SelectedValue;

                if (ddlEmployee.SelectedIndex > 0)

                {

                    activePurchase.Employee = ddlEmployee.SelectedItem.Text;

                }

                else

                {

                    activePurchase.Employee = null;

                }


                activePurchase.Remarks = txtNarration.Text;

                //activePurchase.CurrencyId = Convert.ToInt32(ddlCurrency.SelectedValue);

                //activePurchase.FcRate = Convert.ToDecimal(txtCurrencyRate.Text);

                activePurchase.ClientPoNo = txtClientPO.Text;

                activePurchase.RefNo = txtRefNo.Text;

                activePurchase.OurPoNo = txtOurPO.Text;

                activePurchase.DiscountAllAmount = checkboxApplyallDiscount.Checked;

                activePurchase.DiscountAllPer = checkboxApplyallDiscountPercentage.Checked;

                activePurchase.IsApproved = false;

                activePurchase.IsRejected = false;

                if (checkboxApplyallDiscount.Checked)

                {

                    activePurchase.DiscountAmount = Convert.ToDecimal(txtDiscountTotal.Text);

                }

                else

                {

                    activePurchase.DiscountAmount = 0.00m;

                }

                if (checkboxApplyallDiscountPercentage.Checked)

                {

                    activePurchase.DiscountPer = Convert.ToDecimal(txtDiscountTotal.Text);

                }

                else

                {

                    activePurchase.DiscountPer = 0.00m;

                }



                if (!string.IsNullOrEmpty(txtDiscountTotal.Text))

                {

                    if (checkboxApplyallDiscountPercentage.Checked)

                    {

                        decimal subtotal = Convert.ToDecimal(txtSubTotal.Text);

                        decimal discountper = Convert.ToDecimal(txtDiscountTotal.Text);

                        decimal amount = ((subtotal * discountper) / 100);

                        activePurchase.NetDiscount = Convert.ToDecimal(amount);

                    }

                    else

                    {

                        activePurchase.NetDiscount = Convert.ToDecimal(txtDiscountTotal.Text);

                    }


                }

                else

                {

                    activePurchase.NetDiscount = 0.00m;

                }



                if (!string.IsNullOrEmpty(txtTotal.Text))

                {


                    activePurchase.NetTotal = Convert.ToDecimal(txtTotal.Text);

                }

                else

                {

                    activePurchase.NetTotal = 0.00m;

                }


                if (!string.IsNullOrEmpty(txtFcTotal.Text))

                {


                    activePurchase.FcTotal = Convert.ToDecimal(txtFcTotal.Text);

                }

                else

                {

                    activePurchase.FcTotal = 0.00m;

                }


                if (!string.IsNullOrEmpty(single_cal4.Text))

                {

                    activePurchase.Date = Convert.ToDateTime(single_cal4.Text);

                }

                activePurchase.Status = "";

                activePurchase.JobId = Convert.ToInt32(ddlJob.SelectedValue);

                activePurchase.CompanyId = Convert.ToInt32(Session["companyid"]);

                activePurchase.UserId = Convert.ToInt32(Session["userid"]);


                if (!string.IsNullOrEmpty(single_cal4.Text))

                {

                    DateTime startdate = Convert.ToDateTime(single_cal4.Text);

                    string starttime = DateTime.Now.ToString("HH:mm");

                    DateTime newDateTime = startdate.Add(TimeSpan.Parse(starttime));

                    if (ActiveId == 0)

                    {

                        activePurchase.Date = newDateTime;

                        activePurchase.CreatedOn = newDateTime;

                        activePurchase.CreatedBy = Convert.ToInt32(Session["userid"]);

                    }

                }


                if (ActiveId > 0)

                {

                    DateTime startdate = Convert.ToDateTime(single_cal4.Text);

                    string starttime = DateTime.Now.ToString("HH:mm");

                    DateTime newDateTime = startdate.Add(TimeSpan.Parse(starttime));

                    activePurchase.Date = newDateTime;

                    //DateTime newDateTime = startdate.Add(TimeSpan.Parse(DocumentCreatedTime));

                    activePurchase.ModifiedOn = DateTime.Now;

                    activePurchase.ModifiedBy = Convert.ToInt32(Session["userid"]);


                }



                if (isSave)

                {

                    int id;

                    if (ViewState["ActiveUpdateId"] != null)

                    {

                        id = (int)ViewState["ActiveUpdateId"];

                    }

                    else { id = 0; }


                    bool IsApprove = ApprovalDAL.IsApproval("Purchase Quotation", Convert.ToInt32(Session["companyid"]));

                    if (IsApprove)

                    {

                        activePurchase.ApprovalStatus = "Pending";

                    }

                    else

                    {

                        activePurchase.ApprovalStatus = "Approved";

                    }

                    activePurchase.FinancialYearID = Convert.ToInt32(Session["FinancialYearID"]);

                    if (id == 0)

                    //if (ActiveId == 0) comment by ashraf

                    {

                        bool isAccount = true;// ValidateAccount(ref isSave);

                        if (isAccount)

                        {

                            bool CheckQty = true;// isValidateQty(ref isSave);

                            if (CheckQty)

                            {


                                PoId = activeDAL.PurchaseInsert(activePurchase);

                                InsertLog("Inserted", "");

                                ActiveId = PoId;

                                if (IsApprove)

                                {

                                    ApprovalDocumentUnictableDAL activeADUDAL = new ApprovalDocumentUnictableDAL();

                                    ApprovalDocumentUnictable activeADU = new ApprovalDocumentUnictable();


                                    activeADU.Id = 0;

                                    activeADU.UserId = Convert.ToInt32(Session["userid"]);

                                    activeADU.DocumentCode = PropFinalCode;

                                    activeADU.DocumentDate = Convert.ToDateTime(single_cal4.Text);

                                    activeADU.DocumentId = PoId;

                                    activeADU.CompanyId = Convert.ToInt32(Session["companyid"]);

                                    activeADUDAL.ApprovalDocumentUnictableInsert(activeADU);

                                }

                                if (PoId > 0)

                                {

                                    PurchaseQuotationDtLDAL avtivePODtlDAL = new PurchaseQuotationDtLDAL();

                                    PurchaseQuotationDtl activePODtl = new PurchaseQuotationDtl();

                                    List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];


                                    foreach (PurchaseQuotationDtl item in activePurchaseList)

                                    {

                                        activePODtl.Id = 0;

                                        activePODtl.PurReqId = item.PurReqId;//it is to be used PoId;

                                        activePODtl.PickDataID = item.PickDataID;

                                        activePODtl.PurchaseQuotationId = PoId;

                                        activePODtl.ProductId = item.ProductId;

                                        activePODtl.ProductName = item.ProductName;

                                        activePODtl.UnitPrice = item.UnitPrice;

                                        activePODtl.CurrencyId = item.CurrencyId;

                                        activePODtl.CurrencyRate = item.CurrencyRate;

                                        activePODtl.FcUnitPrice = item.FcUnitPrice;

                                        activePODtl.FcAmount = item.FcAmount;


                                        if (item.ProGrpName != null)

                                        {

                                            activePODtl.ProGrpName = item.ProGrpName;

                                        }

                                        //activePODtl.UnitName = lblUnit.Text;

                                        activePODtl.Discount = Convert.ToDecimal(item.Discount);

                                        activePODtl.DiscountPercentage = item.DiscountPercentage;

                                        //activePODtl.Discount = 0.00m;

                                        activePODtl.PartNo = item.PartNo;

                                        activePODtl.Qty = item.Qty;

                                        activePODtl.Total = item.Total;

                                        ApprovalTotal = activePODtl.Total;

                                        activePODtl.Remarks = string.IsNullOrEmpty(item.Remarks) ? "" : item.Remarks;

                                        activePODtl.PurQuoNo = PropFinalCode;

                                        activePODtl.Status = true;

                                        activePODtl.DiscountQty = item.Qty;

                                        activePODtl.DiscountTotal = item.DiscountTotal;

                                        activePODtl.DiscountPercentage = item.DiscountPercentage;

                                        activePODtl.DiscountAmount = item.DiscountAmount;

                                        activePODtl.DiscountFc = item.DiscountFc;

                                        activePODtl.DiscountFcAmount = item.DiscountFcAmount;

                                        activePODtl.AfterDiscountFcAmount = item.AfterDiscountFcAmount;

                                        activePODtl.ConversionRateofCurrency = item.ConversionRateofCurrency;

                                        activePODtl.VATId = item.VATId;

                                        activePODtl.VATAmount = item.VATAmount;

                                        activePODtl.VATPercentage = item.VATPercentage;

                                        activePODtl.AfterVATTotal = item.AfterVATTotal;

                                        activePODtl.UnitID = item.UnitID;

                                        activePODtl.UnitName = item.UnitName;

                                        activePODtl.NoOfStockInUnit = StockingUnitGetByProductID(Convert.ToInt32(activePODtl.ProductId), Convert.ToInt32(activePODtl.UnitID));

                                        if (activePODtl.NoOfStockInUnit != 0)

                                        {

                                            activePODtl.NoOfStockInUnit = activePODtl.NoOfStockInUnit * activePODtl.Qty;

                                        }

                                        else

                                        {

                                            activePODtl.NoOfStockInUnit = activePODtl.Qty;

                                        }

                                        avtivePODtlDAL.PurchaseQuotationDtlInsert(activePODtl);


                                        bool Status = Convert.ToBoolean(item.Status.ToString());

                                        //Purchase Requisition affect

                                    }

                                }

                            }

                            else

                            {

                                Messages.InformationMessage("Please add accounts for the particular product.");

                            }

                        }

                        else

                        {

                            // bool isAccount = true;// ValidateAccount(ref isSave);


                        }

                    }

                    else

                    {

                        bool isAccount = true;

                        if (isAccount)

                        {

                            bool CheckQty = CheckQty = true;// isValidateQty(ref isSave);

                            if (CheckQty)

                            {

                                PoId = ActiveId;

                                //ApprovalDocumentUnictableDAL activeADUDAL = new ApprovalDocumentUnictableDAL();

                                //ApprovalDocumentUnictable activeADU = new ApprovalDocumentUnictable();

                                //activeADUDAL.ApprovalDocumentUnictableDelete(PoId);


                                ////activeDAL.PurchaseQuotationDelete(txtCode.Value); //PurchaseRequistionDelete



                                ////

                                //activeADU.Id = 0;

                                //activeADU.UserId = Convert.ToInt32(Session["userid"]);

                                //activeADU.DocumentCode = txtCode.Value;

                                //activeADU.DocumentDate = Convert.ToDateTime(single_cal4.Text);

                                //activeADU.DocumentId = ActiveId;

                                //activeADUDAL.ApprovalDocumentUnictableInsert(activeADU);

                                //


                                activeDAL.PurchaseQuotationUpdate(activePurchase);

                                InsertLog("Update", "");

                                PurchaseQuotationDtLDAL avtivePODtlDAL = new PurchaseQuotationDtLDAL();


                                //avtivePODtlDAL.PurchaseQuotationDtlDeleteByPINO(txtCode.Value);

                                PurchaseQuotationDtl activePODtl = new PurchaseQuotationDtl();

                                List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["PurchaseQuottion"];


                                avtivePODtlDAL.PurchaseQuotationDtlDeleteByPINO(activePurchase.PurQuoNo, Convert.ToInt32(Session["FinancialYearID"]));

                                //for (int i = 0; i < GetQty.Count; i++)

                                //{

                                //    int purId = GetQty[i];

                                //    avtivePODtlDAL.PurchaseQuotationDtlDeleteById(purId);

                                //    //PurchaseQuotationDtl activeQuoDtlList = avtivePODtlDAL.PurchaseQuotationDtlGetById(purId);

                                //    //if (activeQuoDtlList != null)

                                //    //{

                                //    //    if (purId == activeQuoDtlList.Id)

                                //    //    {

                                //    //        PurchaseRequistionDtLDAL avtivePODtlDAL2 = new PurchaseRequistionDtLDAL();

                                //    //        PurchaseRequistionDtl actReq = avtivePODtlDAL2.PurchaseRequistionDtlSelectByProductNamePONO(activeQuoDtlList.PartNo, activeQuoDtlList.PurReqId);

                                //    //        if (actReq != null)

                                //    //        {

                                //    //            int subQty = actReq.DsicountQty + activeQuoDtlList.DiscountQty;

                                //    //            decimal disQty = actReq.Total + activeQuoDtlList.Total;

                                //    //            actReq.DsicountQty = Math.Abs(subQty);

                                //    //            actReq.Status = true;

                                //    //            actReq.DiscountTotal = Math.Abs(disQty);

                                //    //            avtivePODtlDAL2.PurchaseRequistionDtlUpdate(actReq);

                                //    //            avtivePODtlDAL.PurchaseQuotationDtlDeleteById(purId);

                                //    //        }

                                //    //    }

                                //    //}

                                //}


                                foreach (PurchaseQuotationDtl item in activePurchaseList)

                                {

                                    activePODtl.Id = 0;

                                    activePODtl.PurchaseQuotationId = PoId;

                                    activePODtl.PurReqId = item.PurReqId;

                                    activePODtl.PickDataID = item.PickDataID;

                                    activePODtl.ProductId = item.ProductId;

                                    activePODtl.ProductName = item.ProductName;

                                    activePODtl.UnitPrice = item.UnitPrice;

                                    //activePODtl.UnitName = lblUnit.Text;

                                    activePODtl.ProGrpName = item.ProGrpName;

                                    activePODtl.Discount = Convert.ToDecimal(item.Discount);

                                    activePODtl.DiscountPercentage = item.DiscountPercentage;

                                    //activePODtl.Discount = 0.00m;

                                    activePODtl.PartNo = item.PartNo;

                                    activePODtl.Qty = item.Qty;

                                    activePODtl.Total = item.Total;

                                    ApprovalTotal = activePODtl.Total;

                                    activePODtl.Remarks = item.Remarks;

                                    activePODtl.PurQuoNo = PropFinalCode;

                                    activePODtl.Status = true;

                                    activePODtl.DiscountQty = item.Qty;

                                    activePODtl.DiscountTotal = item.DiscountTotal;

                                    activePODtl.DiscountPercentage = item.DiscountPercentage;

                                    activePODtl.CurrencyId = item.CurrencyId;

                                    activePODtl.CurrencyRate = item.CurrencyRate;

                                    activePODtl.FcAmount = item.FcAmount;

                                    activePODtl.FcUnitPrice = item.FcUnitPrice;

                                    activePODtl.DiscountAmount = item.DiscountAmount;

                                    activePODtl.DiscountFc = item.DiscountFc;

                                    activePODtl.DiscountFcAmount = item.DiscountFcAmount;

                                    activePODtl.AfterDiscountFcAmount = item.AfterDiscountFcAmount;

                                    activePODtl.ConversionRateofCurrency = item.ConversionRateofCurrency;

                                    activePODtl.VATId = item.VATId;

                                    activePODtl.VATAmount = item.VATAmount;

                                    activePODtl.VATPercentage = item.VATPercentage;

                                    activePODtl.AfterVATTotal = item.AfterVATTotal;

                                    //bool Status = true;

                                    //if (item.IsPickData)

                                    //{

                                    //    Status = Convert.ToBoolean(item.Status.ToString());

                                    //}

                                    //else

                                    //{

                                    //    Status = false;

                                    //}

                                    //PurchaseRequistionDtLDAL avtivePODtlDAL1 = new PurchaseRequistionDtLDAL();

                                    //PurchaseRequistionDtl activePODtl1 = activePODtl1 = avtivePODtlDAL1.PurchaseRequistionDtlSelectByProductNamePONO(activePODtl.PartNo, activePODtl.PurReqId);

                                    //if (Status)

                                    //{


                                    //    if (activePODtl1 != null)

                                    //    {

                                    //        if (activePODtl1.DsicountQty == activePODtl.DiscountQty)

                                    //        {

                                    //            activePODtl1.Status = false;

                                    //            int subQty = activePODtl1.DsicountQty - activePODtl.Qty;

                                    //            // int getQty = subQty - activeQuoDtl.DiscountQty;

                                    //            decimal disQty = activePODtl1.Total - activePODtl.Total;

                                    //            activePODtl1.DsicountQty = Math.Abs(subQty);

                                    //            activePODtl1.DiscountTotal = Math.Abs(disQty);

                                    //            activePODtl1.PurchaseRequistionId = activePODtl.PurReqId;

                                    //        }

                                    //        else

                                    //        {

                                    //            PurchaseQuotationDtl activeQuoDtl = avtivePODtlDAL.PurchaseQuotationDtlSelectByProductNameQuoId(activePODtl.PartNo, activePODtl.PurchaseQuotationId);

                                    //            if (activeQuoDtl != null)

                                    //            {

                                    //                if (activePODtl.Qty > activeQuoDtl.DiscountQty)

                                    //                {

                                    //                    int subQty = activePODtl1.DsicountQty - activePODtl.Qty;

                                    //                    int getQty = subQty + activeQuoDtl.DiscountQty;

                                    //                    decimal disQty = activePODtl1.Total - activePODtl.Total;

                                    //                    activePODtl1.DsicountQty = Math.Abs(getQty);

                                    //                    activePODtl1.Status = true;

                                    //                    activePODtl1.DiscountTotal = Math.Abs(disQty);

                                    //                    activePODtl1.PurchaseRequistionId = activePODtl.PurReqId;

                                    //                }

                                    //                else if (activePODtl.Qty < activeQuoDtl.DiscountQty)

                                    //                {

                                    //                    int subQty = activePODtl1.DsicountQty - activePODtl.Qty;

                                    //                    int getQty = subQty + activeQuoDtl.DiscountQty;

                                    //                    decimal disQty = activePODtl1.Total - activePODtl.Total;

                                    //                    activePODtl1.DsicountQty = Math.Abs(getQty);

                                    //                    activePODtl1.Status = true;

                                    //                    activePODtl1.DiscountTotal = Math.Abs(disQty);

                                    //                    activePODtl1.PurchaseRequistionId = activePODtl.PurReqId;

                                    //                }

                                    //                else if (activePODtl.Qty == activeQuoDtl.DiscountQty)

                                    //                {

                                    //                    //return true;

                                    //                }

                                    //            }

                                    //            else

                                    //            {

                                    //                int subQty = activePODtl1.DsicountQty - activePODtl.Qty;

                                    //                // int getQty = subQty - activeQuoDtl.DiscountQty;

                                    //                decimal disQty = activePODtl1.Total - activePODtl.Total;

                                    //                activePODtl1.DsicountQty = Math.Abs(subQty);

                                    //                activePODtl1.Status = true;

                                    //                activePODtl1.DiscountTotal = Math.Abs(disQty);

                                    //            }

                                    //            activePODtl1.PurchaseRequistionId = activePODtl.PurReqId;

                                    //        }

                                    //        avtivePODtlDAL1.PurchaseRequistionDtlUpdate(activePODtl1);

                                    //    }

                                    //}


                                    //  avtivePODtlDAL.PurchaseQuotationDtlDeleteById(item.Id);

                                    activePODtl.UnitID = item.UnitID;

                                    activePODtl.UnitName = item.UnitName;

                                    activePODtl.NoOfStockInUnit = StockingUnitGetByProductID(Convert.ToInt32(activePODtl.ProductId), Convert.ToInt32(activePODtl.UnitID));

                                    if (activePODtl.NoOfStockInUnit != 0)

                                    {

                                        activePODtl.NoOfStockInUnit = activePODtl.NoOfStockInUnit * activePODtl.Qty;

                                    }

                                    else

                                    {

                                        activePODtl.NoOfStockInUnit = activePODtl.Qty;

                                    }

                                    avtivePODtlDAL.PurchaseQuotationDtlInsert(activePODtl);

                                }



                            }

                            List<TradeDocument> activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];


                            new TradeDocumentDAL().TradeDocumentDeleteByMasterIDType("Purchase Quotation", ActiveId);

                            if (activeTradeDocumentList != null)

                            {

                                foreach (TradeDocument item in activeTradeDocumentList)

                                {

                                    item.DocumentType = "Purchase Quotation";

                                    item.MasterID = ActiveId;

                                    item.UserID = Convert.ToInt32(Session["userid"]);

                                    item.CompanyID = Convert.ToInt32(Session["companyid"]);

                                    new TradeDocumentDAL().TradeDocumentInsert(item);

                                }

                            }

                        }

                        else

                        {

                            Messages.InformationMessage("Please add accounts for the particular product.");

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return isSave;

        }

        private void InsertLog(string Action, string Descreption)

        {

            ERP_Log ActiveERP_log = new ERP_Log();

            ERP_LogDAL ActiveERP_logDAL = new ERP_LogDAL();

            ActiveERP_log.Action = Action;

            ActiveERP_log.FormName = "Purchase Quotation WebForm";

            ActiveERP_log.Descreption = "{ID : " + PoId + " }{Requisition No  : " + txtCode.Value + "}{Vendor : " + ddlVendor.SelectedItem.Text + "}{Date : " + single_cal4.Text + "}{Employee : " + ddlEmployee.SelectedItem.Text + "}{WareHouse : " + ddlWarehouse.SelectedItem.Text + "}";

            ActiveERP_log.UserId = Convert.ToInt32(Session["userid"]);

            ActiveERP_log.CompanyId = Convert.ToInt32(Session["CompanyId"]);

            ActiveERP_logDAL.InsertUserLog(ActiveERP_log);


        }

        private bool isValidateQty(ref bool isSave)

        {

            List<PurchaseRequistionDtl> activePurchaseList = (List<PurchaseRequistionDtl>)ViewState["MyDate"];


            foreach (PurchaseRequistionDtl item in activePurchaseList)

            {

                ProductDAL activeDAL = new ProductDAL();

                Product activeProduct = activeDAL.ProductGetByDescription(item.ProductName);

                WarehouseQtyDAL avtivePODtlDAL1 = new WarehouseQtyDAL();

                WarehouseQty activePODtl1 = avtivePODtlDAL1.WarehouseQtyGetByProductIdWarehouseId(activeProduct.Id, Convert.ToInt32(ddlWarehouse.SelectedValue));

                if (activePODtl1 != null)

                {

                    if (Convert.ToDecimal(item.Qty) == activePODtl1.WarehouseQty1)

                    {

                        isSave = true;

                    }

                    else

                    {

                        if (Convert.ToDecimal(item.Qty) > activePODtl1.WarehouseQty1)

                        {

                            Messages.InformationMessage("Please Enter Less Than Qty, " + activeProduct.ProductName + " Product Available Qty Is: " + activePODtl1.WarehouseQty1);

                            isSave = false;

                            return isSave;

                        }

                        else

                        {

                            isSave = true;

                        }

                    }

                }

                else

                {

                    Messages.InformationMessage("There is no Qty Avaliable in " + ddlWarehouse.SelectedItem.Text + " Warehouse");

                    isSave = false;

                    return isSave;

                }

            }

            return isSave;

        }


        private bool ValidateAccount(ref bool isSave)

        {

            ProductAccountSetupDAL activeProductAccSetupDAL = new ProductAccountSetupDAL();

            ProductAccountSetup activeProductAccSetup = new ProductAccountSetup();

            ProductDAL activeProDAL = new ProductDAL();

            bool isAccount = true;

            List<PurchaseRequistionDtl> activePurchaseList = (List<PurchaseRequistionDtl>)ViewState["MyDate"];


            foreach (PurchaseRequistionDtl item in activePurchaseList)

            {

                Product activeProduct = activeProDAL.ProductGetByDescription(item.ProductName);

                if (activeProduct != null)

                {

                    activeProductAccSetup = activeProductAccSetupDAL.ProductAccountSetupGetByProductId(activeProduct.ProductId);

                    if (activeProductAccSetup != null)

                    {

                        if (activeProductAccSetup.LocalPurchase != string.Empty)

                        {

                            isAccount = true;

                        }

                        else

                        {

                            isAccount = false;

                            isSave = false;

                        }

                    }

                    else

                    {

                        isAccount = false;

                        isSave = false;

                    }

                }

            }

            return isAccount;

        }

        FinancialYearMasterDAL activeFinancialYearMasterDAL = new FinancialYearMasterDAL();

        protected void btnSave_Click(object sender, EventArgs e)

        {

            try

            {

                if ((ActiveId == 0 && !userauth(AuthType.Add)) || (ActiveId > 0 && !userauth(AuthType.Update)))

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "alert('You do not have the right for this action');", true);

                else

                {


                    FinancialYearMaster activeFinancialYearMaster = activeFinancialYearMasterDAL.FinancialYearMasterGetById(Convert.ToInt32(Session["FinancialYearID"]));

                    if (activeFinancialYearMaster.LockYear)

                    {

                        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Can not Save Changes. Financial Year Locked. Contact Admin.');", true);

                    }

                    else

                    {

                        if (ddlVendor.SelectedIndex == 0)

                        {

                            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Header Information : Please Select Vendor');", true);

                        }

                        else if (ddlWarehouse.SelectedIndex == 0)

                        {

                            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Header Information : Please Select Warehouse');", true);

                        }

                        else if (GridViewPurchaseReq.Rows.Count == 0)

                        {

                            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Detail Information : Please Add Purchase Requisition Details.');", true);

                        }

                        else

                        {

                            bool IsConvertedtoOrder = CheckPQConvertinPO(txtCode.Value);

                            if (!IsConvertedtoOrder)

                            {

                                if (Save())

                                {


                                    bool IsApprove = ApprovalDAL.IsApproval("Purchase Quotation", Convert.ToInt32(Session["companyid"]));

                                    if (IsApprove)

                                    {

                                        PurchaseSave();

                                    }

                                    ActiveId = 0;

                                    Response.Redirect("~/Trade/LISTPurchaseQuotation.aspx", false);

                                    Context.ApplicationInstance.CompleteRequest();

                                }

                            }

                            else

                            {

                                string PickedCode = string.Empty;

                                PickedCode = GetPurchaseQuotationNo(txtCode.Value);

                                string message = "'Data Cannot be Update. Already used in Doc# " + PickedCode + "'";

                                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert(" + message + ");", true);

                            }

                        }


                    }


                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        protected void btnClear_Click(object sender, EventArgs e)

        {


            checkboxApplyallDiscount.Enabled = true;

            checkboxApplyallDiscountPercentage.Enabled = true;

            txtDiscountAmount.Enabled = true;

            checkboxApplytoall.Checked = false;

            checkboxApplytoall.Disabled = false;

            checkboxApplyallDiscount.Checked = false;

            checkboxApplyallDiscountPercentage.Checked = false;

            Clear();

            ClearProduct();

        }


        private void Clear()

        {

            ActiveId = 0;

            isPickData = false;

            ddlVendor.SelectedIndex = 0;

            ddlWarehouse.SelectedIndex = 0;

            ddlEmployee.SelectedIndex = 0;

            ddlJob.SelectedIndex = 0;

            txtRefNo.Text = RefCode();

            txtNarration.Text = string.Empty;

            GridViewPurchaseReq.DataSource = null;

            GridViewPurchaseReq.DataBind();

            ViewState["PurchaseQuottion"] = new List<PurchaseQuotation>();

            ViewState["MyDate"] = new List<PurchaseQuotationDtl>();

            //BindPurcahseReqDtl();

            txtDiscountTotal.Text = "0.00";

            txtTotal.Text = "0.00";

            txtFcTotal.Text = "0.00";

            txtPerDiscount.Text = "0.00";

            Initilaize();

            txtClientPO.Text = string.Empty;

            //txtRefNo.Text = string.Empty;

            txtOurPO.Text = string.Empty;

            single_cal4.Text = DateTime.Now.ToString("yyyy-MM-dd");

            BindWarehoue();

            isPickData = false;

            //Response.Redirect("PurchaseQuotationWebForm.aspx");

        }


        public void PurchaseSave()

        {

            try

            {

                int PurchaseQuotationID = 0;

                if (Request.QueryString["Id"] != null)

                {

                    PurchaseQuotationID = Convert.ToInt32(Request.QueryString["Id"]);

                }

                ApprovalDocumentDAL activeAppDocDAL = new ApprovalDocumentDAL();


                if (GridViewPurchaseReq.Rows.Count > 0)

                {

                    ApprovalDAL activeApprovalDAL = new ApprovalDAL();

                    List<Approval> activeApprovalList = activeApprovalDAL.ApprovalGetBySubModuleName("Purchase Quotation");


                    //activeAppDocDAL.ApprovalDocumentDeleteByDocumentCode(txtCode.Value);


                    if (activeApprovalList != null)

                    {

                        foreach (Approval item in activeApprovalList)

                        {

                            if (ApprovalTotal >= item.LimitAmount || item.LimitAmount == 0)

                            {

                                if (PurchaseQuotationID > 0)

                                {

                                    ApprovalDocument activeAppDoc = new ApprovalDocument();

                                    ApprovalDocument activeAppDoc1 = activeAppDocDAL.ApprovalDocumentGetByApprovalId(item.ID);

                                    if (PurchaseQuotationID > 0)

                                    {

                                        activeAppDoc1.Id = activeAppDoc1.Id;

                                    }

                                    else

                                    {

                                        activeAppDoc1.Id = 0;

                                    }


                                    activeAppDoc1.DocumentCode = PropFinalCode;

                                    activeAppDoc1.EmployeeId = Convert.ToInt32(ddlEmployee.SelectedValue);

                                    activeAppDoc1.NetTotal = Convert.ToDecimal(txtTotal.Text);

                                    activeAppDoc1.VendorId = Convert.ToInt32(ddlVendor.SelectedValue);



                                    DateTime startdate = Convert.ToDateTime(single_cal4.Text);

                                    string starttime = DateTime.Now.ToString("HH:mm");

                                    DateTime newDateTime = startdate.Add(TimeSpan.Parse(starttime));

                                    activeAppDoc1.DocumentDate = newDateTime;

                                    activeAppDoc1.Narration = txtRemarks.Text;

                                    activeAppDoc1.DocumentId = PurchaseQuotationID;

                                    activeAppDoc1.Status = activeAppDoc1.Status;

                                    activeAppDoc1.UserId = item.UserID;

                                    activeAppDoc1.ApprovalId = item.ID;

                                    activeAppDoc1.Segment = item.Sequence;

                                    activeAppDoc1.SubModuleId = item.SubModuleId; ;

                                    activeAppDoc1.CompanyId = Convert.ToInt32(Session["companyid"]);


                                    activeAppDocDAL.ApprovalDocumentUpdate(activeAppDoc1);



                                }

                                else

                                {

                                    ApprovalDocument activeAppDoc = new ApprovalDocument();

                                    activeAppDoc.Id = 0;

                                    activeAppDoc.DocumentCode = PropFinalCode;

                                    DateTime startdate = Convert.ToDateTime(single_cal4.Text);

                                    string starttime = DateTime.Now.ToString("HH:mm");

                                    DateTime newDateTime = startdate.Add(TimeSpan.Parse(starttime));

                                    activeAppDoc.DocumentDate = newDateTime;



                                    activeAppDoc.NetTotal = Convert.ToDecimal(txtTotal.Text);

                                    activeAppDoc.EmployeeId = Convert.ToInt32(ddlEmployee.SelectedValue);

                                    activeAppDoc.VendorId = Convert.ToInt32(ddlVendor.SelectedValue);

                                    activeAppDoc.Narration = txtRemarks.Text;

                                    activeAppDoc.DocumentId = PoId;

                                    activeAppDoc.Status = "Pending";

                                    activeAppDoc.UserId = item.UserID;

                                    activeAppDoc.ApprovalId = item.ID;

                                    activeAppDoc.Segment = item.Sequence;

                                    activeAppDoc.SubModuleId = item.SubModuleId;

                                    activeAppDoc.CompanyId = Convert.ToInt32(Session["companyid"]);

                                    activeAppDocDAL.ApprovalDocmentInsert(activeAppDoc);

                                }

                            }

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }




        public bool CheckForDuplicate(int ProducId, string productName)

        {

            bool dupi = false;

            List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

            foreach (PurchaseQuotationDtl items in activePurchaseList)

            {

                if (items.ProductId > 0)

                {

                    if (items.ProductId == ProducId)

                    {

                        dupi = true;

                        return dupi;

                    }

                    else

                    {

                        dupi = false;

                    }

                }

                else

                {

                    if (items.ProductName == productName)

                    {

                        dupi = true;

                        return dupi;

                    }

                    else

                    {

                        dupi = false;

                    }

                }


            }

            return dupi;

        }



        protected void btnApprovalStatus_Click(object sender, EventArgs e)

        {

            BindModelApprovalStatus();


        }



        protected void btnRegApproval_Click(object sender, EventArgs e)

        {

            PurchaseSave();

        }


        protected void dataGridViewPending_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            if (e.CommandName == "Edit")

            {


                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);



                //rowIndex = row.RowIndex;

                //int id = Convert.ToInt32(e.CommandArgument);


                ActiveId = Convert.ToInt32(e.CommandArgument);

                // BindModelPopup();

                //UpdateProduct(rowIndex);

            }

        }


        protected void dataGridViewPending_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            e.Cancel = true;

        }


        protected void dataGridViewPending_RowEditing(object sender, GridViewEditEventArgs e)

        {

            e.Cancel = true;

        }


        private void BindModelApprovalStatus()

        {

            DocumentCode = PropFinalCode;

            if (!string.IsNullOrEmpty(DocumentCode))

            {

                ApprovalDocumentDAL activeDAL = new ApprovalDocumentDAL();

                ApprovalDocument activeAppDoc = activeDAL.ApprovalDocumentGetByDocumentCodeObject(DocumentCode);

                if (activeAppDoc != null)

                {

                    ApprovalDAL activeApproDAL = new ApprovalDAL();

                    Approval activeApproval = activeApproDAL.ApprovalGetById(activeAppDoc.ApprovalId);

                    List<ApprovalDocument> activeApprovalDocList = activeDAL.ApprovalDocumentGetByDocumentCodeAndSubId(DocumentCode, activeApproval.SubModuleId);

                    if (activeApprovalDocList != null)

                    {

                        //dataGridViewApprovalStatus.AutoGenerateColumns = false;

                        dataGridViewApprovalStatus.DataSource = activeApprovalDocList;

                        dataGridViewApprovalStatus.DataBind();

                    }


                }

            }


            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalApprovalStatus();", true);



        }



        protected void dataGridViewPending_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            //if (e.Row.RowType == DataControlRowType.DataRow)

            //{

            //    CheckBox checkBox = e.Row.Cells[0].Controls[0] as CheckBox;

            //    checkBox.Enabled = true;

            //}

        }


        protected void txtProduct_DataBound(object sender, EventArgs e)

        {

            ProductDAL activeDAL = new ProductDAL();

            List<Product> activeProdcut = activeDAL.ProductSelectbycompany(Convert.ToInt32(Session["companyid"]));

            ViewState["SelectionGroup"] = activeProdcut;


            foreach (ListItem item in ((DropDownList)sender).Items)

            {

                string val = item.Text;

                string tail = val.Substring(val.LastIndexOf('-') + 1);

                foreach (Product item1 in activeProdcut)

                {

                    if (item1.ProductDescription == tail)

                        if (item1.RefPartNo == tail)

                        {

                            item.Attributes.Add("classification", "LessThanFifty");

                        }

                        else

                        {

                            item.Attributes.Add("classification", "GreaterThanFifty");

                        }

                    else

                        item.Attributes.Add("classification", "GreaterThanFifty");

                }

            }

            //foreach (ListItem item in ((DropDownList)sender).Items)

            //{

            //    if (!string.IsNullOrEmpty(item.Text))

            //        item.Attributes.Add("classification", "LessThanFifty");

            //    else

            //        item.Attributes.Add("classification", "GreaterThanFifty");

            //}

        }

        //protected void txtPartNo_SelectedIndexChanged(object sender, EventArgs e)

        //{

        //    try

        //    {

        //        if (txtPartNo.SelectedIndex > 0)

        //        {

        //            DisplayProduct(Convert.ToInt32(txtPartNo.SelectedValue));

        //        }

        //    }


        //    catch (Exception ex)

        //    {

        //        throw ex;

        //    }

        //}


        protected void btnBack_Click(object sender, EventArgs e)

        {

            ActiveId = 0;

            Response.Redirect("~/Trade/LISTPurchaseQuotation.aspx", false);

            Context.ApplicationInstance.CompleteRequest();

            ViewState["MyDate"] = null;

        }


        protected void txtPartNo_TextChanged(object sender, EventArgs e)

        {

            try

            {

                if (!string.IsNullOrEmpty(txtPartNo.Text))

                {

                    string partnotext = txtPartNo.Text;

                    string alertMsgForRate = "";

                    //var partno = partnotext.Substring(0, partnotext.LastIndexOf('-'));

                    ProductDAL activeDAL = new ProductDAL();

                    WebDeskValidator Obj_VLDTR = new WebDeskValidator();

                    Product activeProductRate = activeDAL.ProductGetByPartNoObject(partnotext);


                    if (activeProductRate != null)

                    {

                        Product objprice = new Product();

                        objprice = activeDAL.ProductRateGetById(0, activeProductRate.ProductId, Convert.ToInt32(ddlpricelist.SelectedValue));


                        if (objprice != null)

                        {

                            if (objprice.PriceApplicableDate <= Convert.ToDateTime(single_cal4.Text) || objprice.PriceApplicableDate == null) // Comparing Price list Date With Selected Date

                                txtRate.Text = ApplyFormatofCurrency(objprice.CostPrice);

                            else

                            {

                                txtRate.Text = "0.00";

                                alertMsgForRate = "Price list rate is applicable from this document date " + string.Format("{0:MM/dd/yyyy}", objprice.PriceApplicableDate);

                            }

                        }

                        else

                            txtRate.Text = "0.00";


                        FixedPrice(activeProductRate.FixedPrice);

                        txtRate.Text = GetUnitPricebyproductIdandUnitID(activeProductRate.ProductId, Convert.ToInt32(ddlUnit.SelectedValue)).ToString("0.00");

                        txtProduct.Text = activeProductRate.ProductName;

                        if (ddlUnit.Items.FindByValue(activeProductRate.PurchaseUnitID.ToString()) != null)

                            ddlUnit.SelectedValue = activeProductRate.PurchaseUnitID.ToString();

                        txtUnit.Text = activeProductRate.ProGrpName;

                        lblProductId.Text = activeProductRate.ProductId.ToString();

                        txtPageNumber.Text = activeProductRate.PageNumber;

                        txtItemRef.Text = activeProductRate.ItemRef;

                        txtSerialNumber.Text = activeProductRate.SerialNumber;

                        txtRemarks.Text = activeProductRate.ItemDescription;

                        int AllStock = Obj_VLDTR.AvailbeAllStock(Convert.ToInt32(lblProductId.Text));

                        lblproductqty.Text = AllStock.ToString();

                        int AllWarehouseStock = Obj_VLDTR.AvailbeStockWarehouse(ddlWarehouse.SelectedValue, Convert.ToInt32(lblProductId.Text));

                        lbelwarehouseqrty.Text = AllWarehouseStock.ToString();


                        //lblFactoryPrice.Text = activeProductRate.CostPrice.ToString();

                        if (alertMsgForRate != "")

                            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('" + alertMsgForRate + ".');", true);

                    }

                }

            }

            catch (Exception ex)

            { }

        }

        protected void txtProduct_TextChanged(object sender, EventArgs e)

        {

            try

            {

                if (txtProduct.Text != "")

                {

                    ProductDAL activeDAL = new ProductDAL();

                    WebDeskValidator Obj_VLDTR = new WebDeskValidator();

                    //string stock = Obj_VLDTR.AvailbeStock(ddlWarehouse.SelectedValue, txtProduct.Text);

                    //xtavailbestock.Text = stock;

                    Product activeProductRate = activeDAL.ProductGetByProductNameObject(txtProduct.Text);

                    string alertMsgForRate = "";


                    if (activeProductRate != null)

                    {

                        Product objprice = new Product();

                        objprice = activeDAL.ProductRateGetById(0, activeProductRate.ProductId, Convert.ToInt32(ddlpricelist.SelectedValue));


                        if (objprice != null)

                        {

                            if (objprice.PriceApplicableDate <= Convert.ToDateTime(single_cal4.Text) || objprice.PriceApplicableDate == null) // Comparing Price list Date With Selected Date

                                txtRate.Text = ApplyFormatofCurrency(objprice.CostPrice);

                            else

                            {

                                txtRate.Text = "0.00";

                                alertMsgForRate = "Price list rate is applicable from this document date " + string.Format("{0:MM/dd/yyyy}", objprice.PriceApplicableDate);

                            }

                        }

                        else

                            txtRate.Text = "0.00";


                        FixedPrice(activeProductRate.FixedPrice);

                        txtRate.Text = Convert.ToString(GetUnitPricebyproductIdandUnitID(activeProductRate.ProductId, Convert.ToInt32(ddlUnit.SelectedValue)));

                        if (ddlUnit.Items.FindByValue(activeProductRate.PurchaseUnitID.ToString()) != null)

                            ddlUnit.SelectedValue = activeProductRate.PurchaseUnitID.ToString();

                        txtPartNo.Text = activeProductRate.RefPartNo;

                        txtUnit.Text = activeProductRate.ProGrpName;

                        lblProductId.Text = activeProductRate.ProductId.ToString();

                        txtPageNumber.Text = activeProductRate.PageNumber;

                        txtItemRef.Text = activeProductRate.ItemRef;

                        txtSerialNumber.Text = activeProductRate.SerialNumber;

                        txtRemarks.Text = activeProductRate.ItemDescription;

                        //lblFactoryPrice.Text = activeProductRate.CostPrice.ToString();

                        int AllStock = Obj_VLDTR.AvailbeAllStock(Convert.ToInt32(lblProductId.Text));

                        lblproductqty.Text = AllStock.ToString();

                        int AllWarehouseStock = Obj_VLDTR.AvailbeStockWarehouse(ddlWarehouse.SelectedValue, Convert.ToInt32(lblProductId.Text));

                        lbelwarehouseqrty.Text = AllWarehouseStock.ToString();


                        if (alertMsgForRate != "")

                            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('" + alertMsgForRate + ".');", true);

                    }

                }

            }

            catch (Exception ex)

            {


            }

        }


        protected void btnApprovalStatus_Click1(object sender, EventArgs e)

        {

            BindModelApprovalStatus(PropFinalCode);

        }


        private void BindModelApprovalStatus(string _documentCode)

        {

            string DocumentCode = _documentCode;

            if (!string.IsNullOrEmpty(DocumentCode))

            {

                ApprovalDocumentDAL activeDAL = new ApprovalDocumentDAL();

                ApprovalDocument activeAppDoc = activeDAL.ApprovalDocumentGetByDocumentCodeObject(DocumentCode);

                if (activeAppDoc != null)

                {

                    ApprovalDAL activeApproDAL = new ApprovalDAL();

                    Approval activeApproval = activeApproDAL.ApprovalGetById(activeAppDoc.ApprovalId);

                    List<ApprovalDocument> activeApprovalDocList = activeDAL.ApprovalDocumentGetByDocumentCodeAndSubId(DocumentCode, activeApproval.SubModuleId);

                    if (activeApprovalDocList != null)

                    {

                        //dataGridViewApprovalStatus.AutoGenerateColumns = false;

                        dataGridViewApprovalStatus.DataSource = activeApprovalDocList;

                        dataGridViewApprovalStatus.DataBind();

                    }

                }

            }

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalApprovalStatus();", true);

        }


        protected void btnRegenerate_Click(object sender, EventArgs e)

        {

            ApprovalDocumentDAL activeDAL = new ApprovalDocumentDAL();

            List<ApprovalDocument> activeAppDocList = activeDAL.ApprovalDocumentGetByDocumentCode(PropFinalCode);

            if (activeAppDocList != null)

            {

                foreach (ApprovalDocument item in activeAppDocList)

                {

                    ApprovalDocument activeAppDoc = new ApprovalDocument();

                    activeAppDoc.Id = item.Id;

                    activeAppDoc.DocumentCode = item.DocumentCode;

                    activeAppDoc.DocumentId = item.DocumentId;

                    activeAppDoc.Status = "Pending";

                    activeAppDoc.UserId = item.UserId;

                    activeAppDoc.ApprovalId = item.ApprovalId;

                    activeAppDoc.Remarks = string.Empty;

                    activeAppDoc.Segment = item.Segment;

                    activeAppDoc.DocumentDate = item.DocumentDate;

                    activeAppDoc.CompanyId = item.CompanyId;

                    activeAppDoc.Narration = "Approval Pending";

                    activeAppDoc.NetTotal = Convert.ToDecimal(txtTotal.Text);

                    activeDAL.ApprovalDocumentUpdate(activeAppDoc);

                }

                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Approval Regenerated.');", true);

            }


        }


        protected void checkboxApplyallDiscount_CheckedChanged(object sender, EventArgs e)

        {

            try

            {

                if (checkboxApplyallDiscount.Checked)

                {

                    txtDiscountTotal.Enabled = true;

                }

                else

                {

                    //txtDiscountTotal.Enabled = false;

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        protected void checkboxApplyallDiscountPercentage_CheckedChanged(object sender, EventArgs e)

        {

            try

            {

                if (checkboxApplyallDiscountPercentage.Checked)

                {

                    txtDiscountTotal.Enabled = true;

                }

                else

                {

                    //txtDiscountTotal.Enabled = false;

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        protected override void Render(HtmlTextWriter writer)

        {

            foreach (GridViewRow r in GridViewPurchaseReq.Rows)

            {

                if (r.RowType == DataControlRowType.DataRow)

                {

                    for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)

                    {

                        Page.ClientScript.RegisterForEventValidation(r.UniqueID + "$ctl00", columnIndex.ToString());

                    }

                }

            }

            base.Render(writer);

        }



        protected void gridtxtQty_TextChanged(object sender, EventArgs e)

        {

            List<PurchaseQuotationDtl> activePurchaseList = new List<PurchaseQuotationDtl>();

            string hiddenFieldValue = ((HiddenField)GridViewPurchaseReq.Rows[rowIndex].FindControl("HidQty")).Value;

            int Activevalue = Convert.ToInt32(hiddenFieldValue);

            if (Activevalue != 0)

            {

                TextBox tb = new TextBox();

                TextBox txt = sender as TextBox;

                GridViewRow row = txt.NamingContainer as GridViewRow;

                activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                int rowIndex = row.RowIndex;


                TextBox gridtxtQty = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtQty") as TextBox;

                TextBox gridtxtUnitPrice = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtUnitPrice") as TextBox;

                TextBox gridtxtDiscount = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtDiscount") as TextBox;



                if (gridtxtQty.Text != null)

                {

                    decimal result;

                    bool res = decimal.TryParse(gridtxtQty.Text, out result);

                    try

                    {

                        //UpdateProductsetToList(rowIndex, gridlblProductName.Text, result, Convert.ToDecimal(gridtxtUnitPrice.Text), gridtxtUnitName.Text);

                        checkboxDiscountPercentage.Checked = false;

                        UpdateProductsetToList(rowIndex, result, gridtxtUnitPrice.Text, gridtxtDiscount.Text);

                    }

                    catch (Exception ex)

                    {


                        throw;

                    }


                }


            }

        }



        private void UpdateProductsetToList(int id, decimal qunatity, string unitprice, string discount)

        {

            if (GridViewPurchaseReq.Rows.Count > 0)

            {

                List<PurchaseQuotationDtl> activePurchaseList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                PurchaseQuotationDtl objpurchasequotationdtl = new PurchaseQuotationDtl();


                foreach (PurchaseQuotationDtl item in activePurchaseList)

                {

                    if (activePurchaseList.IndexOf(item) == id)

                    {


                        item.Qty = qunatity;

                        item.UnitPrice = Convert.ToDecimal(unitprice);

                        item.Price = item.Qty * item.UnitPrice;


                        if (item.DiscountPercentage == true || checkboxDiscountPercentage.Checked)

                        {

                            decimal subtotal = Convert.ToDecimal(item.Price);

                            decimal discountper = Convert.ToDecimal(discount);

                            decimal amount = ((subtotal * discountper) / 100);

                            // amount = TruncateDecimal(amount, 2);

                            decimal d = Math.Floor(100 * amount) / 100;


                            item.Discount = Convert.ToDecimal(discount);

                            item.DiscountPercentage = true;

                            item.Total = (item.Qty * item.UnitPrice) - Convert.ToDecimal(d);

                            //item.Discount = Convert.ToDecimal(d);

                            checkboxDiscountPercentage.Checked = false;

                        }

                        else

                        {

                            item.Discount = Convert.ToDecimal(discount);

                            item.Total = (item.Qty * item.UnitPrice) - item.Discount;

                        }


                        item.FcAmount = item.ConversionRateofCurrency * item.Total;

                        decimal ecost = item.Total * item.ConversionRateofCurrency;

                        ecost = Math.Floor(100 * ecost) / 100;

                        item.FcAmount = ecost;


                    }

                }


                GridViewPurchaseReq.DataSource = activePurchaseList;

                GridViewPurchaseReq.DataBind();

                ViewState["PurchaseQuottion"] = activePurchaseList;

            }

        }


        protected void gridtxtUnitPrice_TextChanged(object sender, EventArgs e)

        {

            string hiddenFieldValue = ((HiddenField)GridViewPurchaseReq.Rows[rowIndex].FindControl("HidUnitPrice")).Value;

            int Activevalue = Convert.ToInt32(hiddenFieldValue);

            if (Activevalue != 0)

            {

                TextBox tb = new TextBox();

                TextBox txt = sender as TextBox;

                GridViewRow row = txt.NamingContainer as GridViewRow;

                int rowIndex = row.RowIndex;

                TextBox gridtxtProductName = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtProductName") as TextBox;

                TextBox gridtxtQty = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtQty") as TextBox;

                TextBox gridtxtUnitPrice = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtUnitPrice") as TextBox;

                TextBox gridtxtDiscount = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtDiscount") as TextBox;

                if (gridtxtUnitPrice.Text != null)

                {

                    decimal result;

                    bool res = decimal.TryParse(gridtxtQty.Text, out result);

                    checkboxDiscountPercentage.Checked = false;

                    UpdateProductsetToList(rowIndex, result, gridtxtUnitPrice.Text, gridtxtDiscount.Text);

                }


            }

        }


        protected void gridtxtDiscount_TextChanged(object sender, EventArgs e)

        {

            string hiddenFieldValue = ((HiddenField)GridViewPurchaseReq.Rows[rowIndex].FindControl("HidDiscount")).Value;

            int Activevalue = Convert.ToInt32(hiddenFieldValue);

            if (Activevalue != 0)

            {

                TextBox tb = new TextBox();

                TextBox txt = sender as TextBox;

                GridViewRow row = txt.NamingContainer as GridViewRow;

                int rowIndex = row.RowIndex;

                TextBox gridtxtProductName = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtProductName") as TextBox;

                TextBox gridtxtQty = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtQty") as TextBox;

                TextBox gridtxtUnitPrice = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtUnitPrice") as TextBox;

                TextBox gridtxtDiscount = GridViewPurchaseReq.Rows[rowIndex].FindControl("gridtxtDiscount") as TextBox;

                if (gridtxtUnitPrice.Text != null)

                {

                    decimal result;

                    bool res = decimal.TryParse(gridtxtQty.Text, out result);

                    if (checkboxDiscountPercentage.Checked)

                    {

                        checkboxDiscountPercentage.Checked = true;

                    }


                    UpdateProductsetToList(rowIndex, result, gridtxtUnitPrice.Text, gridtxtDiscount.Text);

                }


            }

        }


        protected void ddlCurrency_SelectedIndexChanged(object sender, EventArgs e)

        {

            GetDefaultCurrency();

            //CurrencyMasterDAL activeDAL = new CurrencyMasterDAL();

            //CurrencyMaster ActiveMasterList = new CurrencyMaster();

            //CurrencyMaster ActiveMasterDefaultList = new CurrencyMaster();

            //if (Convert.ToInt32(ddlCurrency.SelectedValue) != 0)

            //{


            //    ActiveMasterList = activeDAL.CurrencyMasterGetById(Convert.ToInt32(ddlCurrency.SelectedValue));

            //    ActiveMasterDefaultList = activeDAL.CurrencyMasterGetDefault(Convert.ToInt32(Session["companyid"]));

            //    if (ActiveMasterList != null)

            //    {

            //        txtCurrencyRate.Text = ActiveMasterList.FcRate.ToString();

            //        lblCurrencyCode.Text = ActiveMasterList.CurrencyShortName;

            //        lblDefaultCurrencyCode.Text = ActiveMasterDefaultList.CurrencyShortName;

            //        //txtFcTotal.Text = (Convert.ToDecimal(txtTotal.Text) * ActiveMasterList.FcRate).ToString("0.00");



            //    }


            //}

            //else

            //{

            //    ActiveMasterDefaultList = activeDAL.CurrencyMasterGetDefault(Convert.ToInt32(Session["companyid"]));

            //    txtCurrencyRate.Text = "1.00";

            //    lblCurrencyCode.Text = "";

            //    lblDefaultCurrencyCode.Text = ActiveMasterDefaultList.CurrencyShortName;

            //    //txtFcTotal.Text = txtTotal.Text;


            //}

        }


        protected void btnPickData_Click(object sender, EventArgs e)

        {


            BindPurcahseReq();

        }


        protected void btnPostPickData_Click(object sender, EventArgs e)

        {

            pickdatasaleQuotationdtl();

            GetDefaultCurrency();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "DDPModal", "$('#modelPickData').modal('hide');", true);

            // CalculateFooterArea();

        }



        private void pickdatasaleQuotationdtl()

        {

            try

            {

                activeSaleOrderdtllist.Clear();

                foreach (GridViewRow row in grvPickDataDetail.Rows)

                {

                    ddlCurrency.Enabled = false;

                    txtCurrencyRate.Enabled = false;


                    if (row.RowType == DataControlRowType.DataRow)

                    {

                        CheckBox chkRow = (row.Cells[0].FindControl("chkPickData") as CheckBox);

                        if (chkRow.Checked)

                        {


                            Label lblid = (row.Cells[0].FindControl("lblid") as Label);

                            Label lblProductid = (row.Cells[0].FindControl("lblProductid") as Label);

                            Label lblVATId = (row.Cells[0].FindControl("lblVATId") as Label);

                            Label lblSaleQuotationId = (row.Cells[0].FindControl("lblSaleQuotationId") as Label);

                            Label lblproductName = (row.Cells[0].FindControl("lblproductName") as Label);

                            Label lblFactory = (row.Cells[0].FindControl("lblFactory") as Label);

                            Label lblDiscountQty = (row.Cells[0].FindControl("lblDiscountQty") as Label);

                            Label lblUnitPrice = (row.Cells[0].FindControl("lblUnitPrice") as Label);

                            Label lblPrice = (row.Cells[0].FindControl("lblPrice") as Label);

                            Label lblUnitName = (row.Cells[0].FindControl("lblUnitName") as Label);

                            Label lblUnitID = (row.Cells[0].FindControl("lblUnitID") as Label);

                            Label lblPartNo = (row.Cells[0].FindControl("lblPartNo") as Label);

                            Label lblDiscountAmount = (row.Cells[0].FindControl("lblDiscountAmount") as Label);

                            Label lblDiscountPercentage = (row.Cells[0].FindControl("lblDiscountPercentage") as Label);

                            Label lblTotal = (row.Cells[0].FindControl("lblTotal") as Label);

                            Label lblCurrencyId = (row.Cells[0].FindControl("lblCurrencyId") as Label);

                            Label lblCurrencyRate = (row.Cells[0].FindControl("lblCurrencyRate") as Label);

                            Label lblFcUnitPrice = (row.Cells[0].FindControl("lblFcUnitPrice") as Label);

                            Label lblFcAmount = (row.Cells[0].FindControl("lblFcAmount") as Label);

                            Label lblAfterDiscountFcAmount = (row.Cells[0].FindControl("lblAfterDiscountFcAmount") as Label);

                            Label lblDiscountFc = (row.Cells[0].FindControl("lblDiscountFc") as Label);

                            Label lblRemarks = (row.Cells[0].FindControl("lblRemarks") as Label);

                            Label lblVATPercentage = (row.Cells[0].FindControl("lblVATPercentage") as Label);

                            Label lblVATAmount = (row.Cells[0].FindControl("lblVATAmount") as Label);

                            Label gridlblAmount = (row.Cells[0].FindControl("gridlblAmount") as Label); //Label For After Vat Total 

                            Label gridlblFcAmount = (row.Cells[0].FindControl("gridlblFcAmount") as Label); //Label For After Vat Total FC


                            PurchaseQuotationDtl activePurchase = new PurchaseQuotationDtl();


                            PurchaseRequistion activePurchaseRequistion = new PurchaseRequistionDAl().PurchaseRequistionGetById(Convert.ToInt32(lblSaleQuotationId.Text));

                            single_cal4.Text = activePurchaseRequistion.Date.ToString("yyyy-MM-dd");

                            ddlJob.SelectedValue = activePurchaseRequistion.JobId.ToString();

                            ddlWarehouse.SelectedIndex = ddlWarehouse.Items.IndexOf(ddlWarehouse.Items.FindByText(activePurchaseRequistion.Location));

                            //ddlWarehouse.SelectedValue= activePurchaseRequistion.Location

                            //ddlWarehouse.Items.FindByText(activePurchaseRequistion.Location).Selected = true;

                            txtNarration.Text = activePurchaseRequistion.Remarks;

                            txtClientPO.Text = activePurchaseRequistion.ClientPoNo;

                            txtRefNo.Text = activePurchaseRequistion.RefNo;

                            txtOurPO.Text = activePurchaseRequistion.OurPoNo;


                            if (lblid.Text != "0")

                            {

                                activePurchase.PickDataID = Convert.ToInt32(lblid.Text);

                            }

                            else

                            {

                                activePurchase.PickDataID = 0;

                            }


                            if (lblCurrencyRate.Text != "0")

                            {

                                activePurchase.CurrencyRate = Convert.ToDecimal(lblCurrencyRate.Text);

                                txtCurrencyRate.Text = ApplyFormatofCurrency(activePurchase.CurrencyRate);

                            }

                            else

                            {

                                activePurchase.CurrencyRate = 0;

                                txtCurrencyRate.Text = ApplyFormatofCurrency(activePurchase.CurrencyRate);

                            }

                            if (lblCurrencyId.Text != "0")

                            {

                                activePurchase.CurrencyId = Convert.ToInt32(lblCurrencyId.Text);

                                ddlCurrency.SelectedValue = activePurchase.CurrencyId.ToString();

                            }


                            else

                            {

                                activePurchase.CurrencyId = 0;

                                ddlCurrency.SelectedValue = activePurchase.CurrencyId.ToString();

                            }

                            activePurchase.ConversionRateofCurrency = CalculateCurrencyRate(activePurchase.CurrencyId, activePurchase.CurrencyRate);

                            if (lblDiscountQty.Text != "0")

                            {

                                activePurchase.Qty = Convert.ToDecimal(lblDiscountQty.Text);

                                activePurchase.DiscountQty = Convert.ToDecimal(lblDiscountQty.Text);

                            }

                            else

                            {

                                activePurchase.Qty = 0;

                            }

                            if (lblUnitPrice.Text != "0")

                            {

                                activePurchase.UnitPrice = Convert.ToDecimal(lblUnitPrice.Text);

                            }

                            else

                            {

                                activePurchase.UnitPrice = 0;

                            }


                            if (lblPrice.Text != "0")

                            {

                                activePurchase.Price = activePurchase.Qty * activePurchase.UnitPrice;

                            }

                            else

                            {

                                activePurchase.Price = 0;

                            }

                            if (!string.IsNullOrEmpty(lblDiscountAmount.Text))

                            {

                                activePurchase.DiscountAmount = Convert.ToDecimal(lblDiscountAmount.Text);

                            }

                            else

                            {

                                activePurchase.DiscountAmount = 0.00m;

                            }

                            if (lblTotal.Text != "0")

                            {

                                activePurchase.Total = ApplyRuleofDecimalCurrency(Convert.ToDecimal(lblTotal.Text));

                                activePurchase.DiscountTotal = Convert.ToDecimal(lblTotal.Text);

                            }

                            else

                            {

                                activePurchase.Total = 0;

                            }

                            if (lblFcUnitPrice.Text != "0")

                            {

                                activePurchase.FcUnitPrice = Convert.ToDecimal(lblFcUnitPrice.Text);

                                activePurchase.FcUnitPrice = Convert.ToDecimal(lblUnitPrice.Text) * activePurchase.ConversionRateofCurrency;

                            }

                            else

                            {

                                activePurchase.FcUnitPrice = 0;

                            }

                            if (lblFcAmount.Text != "0")

                            {

                                activePurchase.FcAmount = Convert.ToDecimal(lblFcAmount.Text);

                                activePurchase.FcAmount = activePurchase.Price * activePurchase.ConversionRateofCurrency;

                            }

                            else

                            {

                                activePurchase.Price = 0;

                            }

                            if (lblAfterDiscountFcAmount.Text != "0")

                            {

                                activePurchase.AfterDiscountFcAmount = Convert.ToDecimal(lblAfterDiscountFcAmount.Text);

                                activePurchase.AfterDiscountFcAmount = activePurchase.Total * activePurchase.ConversionRateofCurrency;

                            }

                            else

                            {

                                activePurchase.AfterDiscountFcAmount = 0;

                            }

                            if (lblDiscountFc.Text != "0")

                            {

                                activePurchase.DiscountFc = Convert.ToDecimal(lblDiscountFc.Text);

                            }

                            else

                            {

                                activePurchase.DiscountFc = 0;

                            }

                            if (lblVATId.Text != "0")

                            {

                                activePurchase.VATId = Convert.ToInt32(lblVATId.Text);

                            }

                            else

                            {

                                activePurchase.VATId = 0;

                            }

                            if (lblVATPercentage.Text != "0")

                            {

                                activePurchase.VATPercentage = Convert.ToDecimal(lblVATPercentage.Text);

                            }

                            else

                            {

                                activePurchase.VATPercentage = 0;

                            }

                            if (lblVATAmount.Text != "0")

                            {

                                activePurchase.VATAmount = Convert.ToDecimal(lblVATAmount.Text);

                            }

                            else

                            {

                                activePurchase.VATAmount = 0;

                            }

                            if (gridlblAmount.Text != "0")

                            {

                                activePurchase.AfterVATTotal = Convert.ToDecimal(gridlblAmount.Text);

                                decimal ConversionRateofCurrency = CalculateCurrencyRate(Convert.ToInt32(activePurchase.CurrencyId), Convert.ToDecimal(activePurchase.CurrencyId));

                                activePurchase.AfterVATTotalFC = activePurchase.AfterVATTotal * ConversionRateofCurrency;

                            }

                            else

                            {

                                activePurchase.AfterVATTotal = 0;

                            }

                            //if (gridlblFcAmount.Text != "0")

                            //{

                            //    activePurchase.AfterVATTotalFC = Convert.ToDecimal(gridlblFcAmount.Text);

                            //}

                            //else

                            //{

                            //    activePurchase.AfterVATTotalFC = 0;

                            //}

                            if (lblid.Text != "0")

                            {

                                activePurchase.Id = Convert.ToInt32(lblid.Text);

                            }

                            else

                            {

                                activePurchase.Id = 0;

                            }

                            if (lblProductid.Text != "0")

                            {

                                activePurchase.ProductId = Convert.ToInt32(lblProductid.Text);

                                lblProductId.Text = lblProductid.Text;

                            }

                            else

                            {

                                activePurchase.ProductId = 0;

                            }


                            if (ViewState["MyDate"] != null)

                            {

                                activeSaleOrderdtllist = (List<PurchaseQuotationDtl>)ViewState["MyDate"];

                            }


                            activePurchase.ProductName = lblproductName.Text;

                            activePurchase.ProGrpName = lblFactory.Text;




                            activePurchase.UnitName = lblUnitName.Text;

                            activePurchase.UnitID = !string.IsNullOrEmpty(lblUnitID.Text) ? Convert.ToInt32(lblUnitID.Text) : 0;

                            if (!string.IsNullOrEmpty(lblPartNo.Text))

                            {

                                activePurchase.PartNo = lblPartNo.Text;

                            }


                            if (lblDiscountAmount.Text != "0")

                            {

                                activePurchase.Discount = Convert.ToDecimal(lblDiscountAmount.Text);

                            }

                            else

                            {

                                activePurchase.Discount = 0;

                            }


                            if (lblDiscountPercentage.Text == "True")

                            {

                                activePurchase.DiscountPercentage = true;

                            }

                            else

                            {

                                activePurchase.DiscountPercentage = false;

                            }



                            if (lblSaleQuotationId.Text != "0")

                            {

                                activePurchase.PurReqId = Convert.ToInt32(lblSaleQuotationId.Text);

                                lblPurchaseReqId.Text = lblSaleQuotationId.Text;


                            }

                            else

                            {

                                activePurchase.PurReqId = 0;

                            }

                            if (lblDiscountQty.Text != "0")

                            {

                                activePurchase.BalanceQty = Convert.ToDecimal(lblDiscountQty.Text);


                            }

                            else

                            {

                                activePurchase.BalanceQty = 0;

                            }


                            activePurchase.Remarks = lblRemarks.Text;

                            activePurchase.ispickBalId = true;

                            //activePurchase.ProductId = 

                            activePurchase.Status = true;

                            activePurchase.IsPickData = true;

                            // txtUnit.Text = row.Cells[3].Text;


                            if (CheckAllWarehouse(activePurchase.ProductId))

                            {

                                activeSaleOrderdtllist.Add(activePurchase);



                                ViewState["PurchaseQuottion"] = activeSaleOrderdtllist;

                                decimal sum = 0;

                                foreach (PurchaseQuotationDtl item in activeSaleOrderdtllist)

                                {

                                    sum += Convert.ToDecimal(item.Total);

                                }

                                string totalfinal = String.Format("{0:n}", sum);

                                txtTotal.Text = ApplyFormatofCurrency(sum);

                                decimal sumfc = 0;

                                foreach (PurchaseQuotationDtl item in activeSaleOrderdtllist)

                                {

                                    sumfc += Convert.ToDecimal(item.FcAmount);

                                }

                                string totalfinalfc = String.Format("{0:n}", sumfc);

                                txtFcTotal.Text = ApplyFormatofCurrency(sumfc);


                            }

                            else

                            {

                                if (CheckWarehouseID(activePurchase.ProductId) == Convert.ToInt32(ddlWarehouse.SelectedValue))

                                {

                                    activeSaleOrderdtllist.Add(activePurchase);



                                    ViewState["PurchaseQuottion"] = activeSaleOrderdtllist;

                                    decimal sum = 0;

                                    foreach (PurchaseQuotationDtl item in activeSaleOrderdtllist)

                                    {

                                        sum += Convert.ToDecimal(item.Total);

                                    }

                                    string totalfinal = String.Format("{0:n}", sum);

                                    txtTotal.Text = ApplyFormatofCurrency(sum);

                                    decimal sumfc = 0;

                                    foreach (PurchaseQuotationDtl item in activeSaleOrderdtllist)

                                    {

                                        sumfc += Convert.ToDecimal(item.FcAmount);

                                    }

                                    string totalfinalfc = String.Format("{0:n}", sumfc);

                                    txtFcTotal.Text = ApplyFormatofCurrency(sumfc);

                                }

                            }

                        }

                    }


                    //ScriptManager.RegisterStartupScript(this, this.GetType(), "ModelSalesOrder", "ClosePopup();", true);


                }

                ViewState["MyDate"] = activeSaleOrderdtllist;

                GridViewPurchaseReq.DataSource = activeSaleOrderdtllist;

                GridViewPurchaseReq.DataBind();



                PurchaseRequistionDAl activeDAL = new PurchaseRequistionDAl();

                PurchaseRequistion activePurchaseReq = activeDAL.PurchaseRequistionGetByIdNew(Convert.ToInt32(lblPurchaseReqId.Text));

                if (activePurchaseReq != null)

                {

                    //txtTotal.Text = activePurchaseReq.NetTotal.ToString();

                    //txtFcTotal.Text = activePurchaseReq.NetTotal.ToString();

                    single_cal4.Text = activePurchaseReq.Date.ToString("yyyy-MM-dd");

                    if (activePurchaseReq.NetDiscount > 0)

                    {

                        if (activePurchaseReq.DiscountAllPer == true)

                        {

                            txtDiscountTotal.Text = ApplyFormatofCurrency(activePurchaseReq.DiscountPer);

                            txtPerDiscount.Text = activePurchaseReq.NetDiscount.ToString();

                        }

                        else

                        {

                            txtDiscountTotal.Text = ApplyFormatofCurrency(activePurchaseReq.NetDiscount).ToString();

                        }

                    }


                    if (activePurchaseReq.DiscountAllAmount)

                    {

                        checkboxApplyallDiscount.Checked = activePurchaseReq.DiscountAllAmount;

                    }

                    else

                    {

                        checkboxApplyallDiscountPercentage.Checked = activePurchaseReq.DiscountAllPer;

                    }


                }




                ScriptManager.RegisterStartupScript(this, this.GetType(), "ModelSalesOrder", "ClosePopup();", true);


            }

            catch (Exception ex)

            {

                throw ex;

            }


        }



        protected void grvPickDataMaster_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            _poNo = e.CommandArgument.ToString();


            PurchaseRequistionDAl activeDAL = new PurchaseRequistionDAl();

            PurchaseRequistion activePurchase = activePurchase = activeDAL.PurchaseRequistionGetByIdNew(Convert.ToInt32(_poNo));

            if (activePurchase != null)

            {

                txtClientPO.Text = activePurchase.ClientPoNo;

                txtRefNo.Text = activePurchase.RefNo;

                txtOurPO.Text = activePurchase.OurPoNo;

                ddlpricelist.SelectedValue = activePurchase.VendorPriceListId.ToString();

            }

            BindPurcahseReqDetail(Convert.ToInt32(e.CommandArgument));

        }


        protected void grvPickDataMaster_RowEditing(object sender, GridViewEditEventArgs e)

        {

            e.Cancel = true;

        }


        protected void grvPickDataDetail_RowEditing(object sender, GridViewEditEventArgs e)

        {

            e.Cancel = true;

        }


        protected void grvPickDataMaster_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

                if (e.Row.Cells[3].Text == "Pending")

                {

                    e.Row.Enabled = false;

                    e.Row.Cells[3].BackColor = Color.Red;

                    e.Row.Cells[3].ForeColor = Color.White;

                    // e.Row.Cells[3].ToolTip = "Approval is Pending";

                    e.Row.ToolTip = "Approval is Pending";

                }

                else

                {

                    e.Row.Enabled = true;

                    e.Row.Cells[3].BackColor = Color.Green;

                    e.Row.Cells[3].ForeColor = Color.White;

                    e.Row.Cells[3].ToolTip = "";

                }

            }

        }


        private void BindPurcahseReqDetail(int PurReqId)

        {

            try

            {


                PurchaseRequistionDtLDAL activeDAL = new PurchaseRequistionDtLDAL();

                List<PurchaseRequistionDtl> activeList = activeDAL.PurchaseRequistionRemainingDtlGetByPurchaseRequistionId(PurReqId);

                if (activeList != null)

                {

                    grvPickDataDetail.DataSource = activeList;

                    grvPickDataDetail.DataBind();


                    List<PurchaseQuotationDtl> activePuQtList = new List<PurchaseQuotationDtl>();

                    foreach (PurchaseRequistionDtl item in activeList)

                    {

                        PurchaseQuotationDtl activePurchase = new PurchaseQuotationDtl();


                        activePurchase.Id = item.Id;

                        activePurchase.PurReqId = item.PurchaseRequistionId;

                        activePurchase.ProductId = item.ProductId;

                        activePurchase.ProductName = item.ProductName;

                        activePurchase.PurQuoNo = item.PoNo;

                        activePurchase.Qty = item.Qty;

                        activePurchase.UnitName = item.UnitName;

                        activePurchase.UnitPrice = item.UnitPrice;

                        activePurchase.Remarks = item.Remarks;

                        activePurchase.ProGrpName = item.ProGrpName;

                        activePurchase.ConversionRateofCurrency = item.ConversionRateofCurrency;

                        activePurchase.IsPickData = true;

                        activePurchase.ispickBalId = true;

                        if (item.DiscountPercentage == true)

                        {

                            activePurchase.DiscountPercentage = true;

                        }

                        else

                        {

                            activePurchase.DiscountPercentage = false;

                        }

                        isPickData = true;

                        // activePurchase.Discount = item.Discount;

                        activePuQtList.Add(activePurchase);


                    }

                    //ViewState["MyDate"] = activePuQtList;

                }


                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModallPickData();", true);

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        private void BindPurcahseReqDtl()

        {

            try

            {

                PurchaseQuotationDtLDAL activeDAL = new PurchaseQuotationDtLDAL();

                List<PurchaseQuotationDtl> activeList = activeDAL.PurchaseQuotationDtlGetByPurchaseQuotationId(0);

                if (activeList != null)

                {

                    GridViewPurchaseReq.DataSource = activeList;

                    GridViewPurchaseReq.DataBind();

                }

            }

            catch (Exception)

            {


                throw;

            }

        }



        private void BindPurcahseReq()

        {

            try

            {

                PurchaseRequistionDtLDAL activeDAL = new PurchaseRequistionDtLDAL();

                List<PurchaseRequistionDtl> activeList = activeDAL.PurchaseRequistionOrder(ddlVendor.SelectedValue.Trim());

                if (activeList != null && activeList.Count > 0)

                {

                    grvPickDataMaster.DataSource = activeList;

                    grvPickDataMaster.DataBind();

                }

                else

                {

                    grvPickDataMaster.DataSource = null;

                    grvPickDataMaster.DataBind();

                    grvPickDataDetail.DataSource = null;

                    grvPickDataDetail.DataBind();


                }

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModallPickData();", true);

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }


        //public decimal TruncateDecimal(decimal value, int precision)

        //{

        //    decimal step = (decimal)Math.Pow(10, precision);

        //    decimal tmp = Math.Truncate(step * value);

        //    return tmp / step;

        //}


        [WebMethod(EnableSession = true)]

        public static void UpdateTime()

        {

            int userid = Convert.ToInt32(HttpContext.Current.Session["userid"]);

            if (userid != 0)

            {

                Login1 log = new Login1();

                log.Id = userid;

                log.LastActive = DateTime.Now;

                LoginDAL DAl = new LoginDAL();

                DAl.UpdateLAstActive(log);

            }

        }


        #region Document Attachment

        public string FileName

        {

            get

            {

                return ViewState["FileName"] != null ? ViewState["FileName"].ToString() : "";

            }

            set

            {

                ViewState["FileName"] = value;

            }

        }

        public string EmpDocFileName

        {

            get

            {

                return ViewState["EmpDocFileName"] != null ? ViewState["EmpDocFileName"].ToString() : "";

            }

            set

            {

                ViewState["EmpDocFileName"] = value;

            }

        }

        //public static int EmpDocAttId { get; set; }

        public int EmpDocAttId

        {

            get

            {

                return ViewState["EmpDocAttId"] != null ? Convert.ToInt32(ViewState["EmpDocAttId"].ToString()) : 0;

            }

            set

            {

                ViewState["EmpDocAttId"] = value;

            }

        }

        protected void companylogo_Load(object sender, EventArgs e)

        {

            try

            {

                if (uploadFile.PostedFile != null && uploadFile.PostedFile.ContentLength > 0)

                {

                    string filename = Path.GetFileNameWithoutExtension(uploadFile.PostedFile.FileName);

                    FileName = Path.GetFileName(uploadFile.PostedFile.FileName);

                    uploadFile.SaveAs(Server.MapPath(FileName));

                    this.companylogo.ImageUrl = FileName;

                }

            }

            catch (Exception ex)

            {

                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);

            }

        }

        protected void btnDocAdd_Click(object sender, EventArgs e)

        {

            if (uploadFile.HasFile)

            {

                hdnfile.Value = uploadFile.PostedFile.FileName;

                if (PostDocument())

                {


                    txtDocName.Text = string.Empty;

                    EmpDocAttId = 0;

                    //uploadFile.

                    TabName.Value = "image";

                    // uploadFile.Controls.Clear();

                    ClientScript.RegisterStartupScript(this.GetType(), "selecttab", "$('#tabs').tabs({ selected: tab_content6 });", true);

                }

            }

        }

        private bool PostDocument()

        {

            bool isSave = true;

            try

            {

                List<TradeDocument> activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];

                if (isSave)

                {

                    if (gvAttachment.Rows.Count > 0)

                    {

                        if (EmpDocAttId > 0)

                        {

                            if (ViewState["DocAttachment"] != null)

                            {

                                activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];

                            }

                            int index = rowIndex;

                            TradeDocument activeDocAtt = new TradeDocument();

                            activeDocAtt.TradeDocumentID = 1;

                            activeDocAtt.Name = txtDocName.Text;

                            activeDocAtt.URL = UploadDocuments();

                            activeTradeDocumentList.RemoveAt(index);

                            activeTradeDocumentList.Insert(index, activeDocAtt);

                        }

                        else

                        {

                            if (ActiveId <= 0)

                            {

                                if (ViewState["DocAttachment"] != null)

                                {

                                    activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];

                                }

                                gvAttachment.DataSource = null;

                            }


                            if (ViewState["DocAttachment"] != null)

                            {

                                activeTradeDocumentList = (List<TradeDocument>)ViewState["DocAttachment"];

                            }

                            TradeDocument activeDocAtt = new TradeDocument();

                            activeDocAtt.TradeDocumentID = 1;

                            activeDocAtt.Name = txtDocName.Text;

                            activeDocAtt.URL = UploadDocuments();

                            activeTradeDocumentList.Add(activeDocAtt);

                        }

                    }

                    else

                    {

                        activeTradeDocumentList = new List<TradeDocument>();

                        TradeDocument activeDocAtt = new TradeDocument();

                        activeDocAtt.TradeDocumentID = 1;

                        activeDocAtt.Name = txtDocName.Text;

                        activeDocAtt.URL = UploadDocuments();

                        activeTradeDocumentList.Add(activeDocAtt);

                    }

                    gvAttachment.DataSource = activeTradeDocumentList;

                    gvAttachment.DataBind();

                    //UpdatePanel30.Update();

                    ViewState["DocAttachment"] = activeTradeDocumentList;

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return isSave;

        }

        private string UploadDocuments()

        {

            try

            {

                string test = hdnfile.Value;

                if (uploadFile.HasFile)

                {

                    HttpPostedFile file = uploadFile.PostedFile;

                    string filename = Path.GetFileNameWithoutExtension(file.FileName);

                    string fileextension = Path.GetExtension(file.FileName);

                    string folderPath = Server.MapPath("Documents/");

                    if (!Directory.Exists(folderPath))

                    {

                        Directory.CreateDirectory(folderPath);

                    }


                    file.SaveAs(folderPath + filename + "_" + fileextension);

                    EmpDocFileName = filename + "_" + fileextension;

                    string fpath = folderPath + EmpDocFileName;

                    // uploadFile.Attributes.Clear();

                }

                return EmpDocFileName;

            }


            catch (Exception ex)

            {

                throw ex;

            }


        }

        private void UpdateDocAttach(int id)

        {

            if (gvAttachment.Rows.Count > 0)

            {

                List<TradeDocument> activePurchaseList = (List<TradeDocument>)ViewState["DocAttachment"];


                foreach (TradeDocument item in activePurchaseList)

                {

                    if (activePurchaseList.IndexOf(item) == id)

                    {

                        EmpDocAttId = item.TradeDocumentID;

                        txtDocName.Text = item.URL;

                    }

                }

            }

        }


        protected void gvAttachment_RowEditing(object sender, GridViewEditEventArgs e)

        {

            e.Cancel = true;

        }


        protected void gvAttachment_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            e.Cancel = true;

        }


        protected void gvAttachment_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            if (e.CommandName == "Edit")

            {

                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                rowIndex = row.RowIndex;

                int id = Convert.ToInt32(e.CommandArgument);

                UpdateDocAttach(rowIndex);

            }

            else if (e.CommandName == "Delete")

            {

                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                rowIndex = row.RowIndex;

                int id = Convert.ToInt32(e.CommandArgument);

                List<TradeDocument> activePurchaseList = (List<TradeDocument>)ViewState["DocAttachment"];

                activePurchaseList.RemoveAt(rowIndex);

                gvAttachment.DataSource = activePurchaseList;

                gvAttachment.DataBind();

            }

            else if (e.CommandName == "View")

            {

                ////server folder path which is stored your PDF documents

                //string path = Server.MapPath("PDF-Files");

                //string filename = path + "/Doc1.pdf";


                ////Create new PDF document 

                //Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);


                //PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));


                //document.Open();

                //document.Add(new Paragraph("Welcome to dotnetfox"));

                //document.Close();


                //ShowPdf(filename);


                //string filePath = e.CommandArgument.ToString();

                //Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(filePath) + ".pdf");

                //Response.WriteFile(Server.MapPath("~/PDF-Files/" + filePath));

                //Response.End();

            }

        }


        public void ShowPdf(string filename)

        {

            //Clears all content output from Buffer Stream

            Response.ClearContent();

            //Clears all headers from Buffer Stream

            Response.ClearHeaders();

            //Adds an HTTP header to the output stream

            Response.AddHeader("Content-Disposition", "inline;filename=" + filename);

            //Gets or Sets the HTTP MIME type of the output stream

            Response.ContentType = "application/pdf";

            //Writes the content of the specified file directory to an HTTP response output stream as a file block

            Response.WriteFile(filename);

            //sends all currently buffered output to the client

            Response.Flush();

            //Clears all content output from Buffer Stream

            Response.Clear();

        }


        #endregion


        protected void GridViewPurchaseReq_DataBound(object sender, EventArgs e)

        {

            if (ViewState["MyDate"] != null)

            {

                if (((List<PurchaseQuotationDtl>)ViewState["MyDate"]).Count > 0)

                {

                    ddlCurrency.Enabled = false;

                    txtCurrencyRate.Enabled = false;

                }

                else

                {

                    ddlCurrency.Enabled = true;

                    txtCurrencyRate.Enabled = true;

                }

            }

            else

            {

                ddlCurrency.Enabled = true;

                txtCurrencyRate.Enabled = true;

            }

        }


        private bool GetPurchaseQuotationDtl(int id)

        {

            bool IsConvertedtoOrder = false;

            if (GridViewPurchaseReq.Rows.Count > 0)

            {

                List<PurchaseQuotationDtl> activePurchaseQuotList = (List<PurchaseQuotationDtl>)ViewState["MyDate"];


                foreach (PurchaseQuotationDtl item in activePurchaseQuotList)

                {

                    if (activePurchaseQuotList.IndexOf(item) == id)

                    {

                        IsConvertedtoOrder = CheckPQConvertinPO(item.PoNo);

                    }

                }


            }

            return IsConvertedtoOrder;


        }


        private bool CheckPQConvertinPO(string PurchaseQuoNo)

        {

            bool IsConvertedtoQuotation = false;

            PurchaseQuotationDAl objPurchaseQuotationDAl = new PurchaseQuotationDAl();

            PurchaseQuotation objPurchaseQuotation = objPurchaseQuotationDAl.PurchaseQuotationGetByPONo(PurchaseQuoNo, Convert.ToInt32(Session["FinancialYearID"]));

            if (objPurchaseQuotation != null)

            {

                //List<PurchaseQuotationDtl> objPurchaseQuotationDtlList = new List<PurchaseQuotationDtl>();

                PurchaseQuotationDtLDAL objPurchaseQuotationDtlDAl = new PurchaseQuotationDtLDAL();

                //objPurchaseQuotationDtlList = objPurchaseQuotationDtlDAl.PurchaseQuotationDtlSelectByPoNo1(objPurchaseQuotation.PurQuoNo);

                IsConvertedtoQuotation = objPurchaseQuotationDtlDAl.CheckPerQuotConverttoPurchaseOrder(objPurchaseQuotation.Id);

                if (IsConvertedtoQuotation)

                {


                    IsConvertedtoQuotation = true;

                }

                else

                {

                    IsConvertedtoQuotation = false;

                }

                //if (objPurchaseQuotationDtlList.Count > 0 && objPurchaseQuotationDtlList != null)

                //{

                //    int Count = 0;

                //    foreach (PurchaseQuotationDtl objpurchasequotationdtl in objPurchaseQuotationDtlList)

                //    {


                //    }

                //}


            }

            return IsConvertedtoQuotation;

        }

        //private bool CheckPQConvertinPO(int PickDataID)

        //{

        //    bool isConverted = false;

        //    if (PickDataID > 0)

        //    {

        //        PurchaseQuotationDtLDAL dal = new PurchaseQuotationDtLDAL();

        //        isConverted = dal.CheckPerQuotConverttoPurchaseOrder(Convert.ToInt32(PickDataID));

        //    }

        //    return isConverted;

        //}


        bool isPick = false;

        private decimal GetBalanceQty(int? RequisitionID, int? PickDataID)

        {

            lblPurchaseReqId.Text = RequisitionID.ToString();

            decimal GetQty = 0.00m;

            bool Istrue = false;


            PurchaseRequistionDtLDAL activeDtlDAL = new PurchaseRequistionDtLDAL();

            List<PurchaseRequistionDtl> activeList = activeDtlDAL.PurchaseRequistionRemainingDtlGetByPurchaseRequistionId(Convert.ToInt32(lblPurchaseReqId.Text));


            PurchaseQuotationDtLDAL objQutotdtlDAl = new PurchaseQuotationDtLDAL();

            List<PurchaseQuotationDtl> objlistPurchaseQuotation = objQutotdtlDAl.PurchaseQuotationDtlGetByPurchaseQuotationId(ActiveId);


            decimal Purchasequotqty = 0.00m;

            if (objlistPurchaseQuotation != null && objlistPurchaseQuotation.Count > 0)

            {

                foreach (PurchaseQuotationDtl purchasequotdtl in objlistPurchaseQuotation)

                {

                    if (purchasequotdtl.ProductId == Convert.ToInt32(lblProductId.Text))

                    {


                        Purchasequotqty = purchasequotdtl.Qty;

                    }

                }


            }

            GetQty = Purchasequotqty;

            if (activeList != null && activeList.Count > 0)

            {

                foreach (PurchaseRequistionDtl item in activeList)

                {

                    if (!Istrue)

                    {

                        if (item.ProductId == Convert.ToInt32(lblProductId.Text))

                        {

                            GetQty = Purchasequotqty + item.Qty;

                            Istrue = true;

                            isPick = true;

                        }

                        else

                        {

                            GetQty = Purchasequotqty;

                        }

                    }

                }

            }


            if (RequisitionID > 0)

            {

                isPick = true;

            }


            return GetQty;

        }


        private string GetPurchaseQuotationNo(string iStID)

        {

            string PickedCode = "";

            PurchaseQuotationDAl objPurchaseQuotationDAl = new PurchaseQuotationDAl();

            PurchaseQuotation objPurchasequo = objPurchaseQuotationDAl.PurchaseQuotationGetByPONo(iStID, Convert.ToInt32(Session["FinancialYearID"]));

            if (objPurchasequo != null)

            {

                DataTable pickedPoNo = objPurchaseQuotationDAl.GetPurchaseOrderByPurchaseQuotationId(objPurchasequo.Id);

                if (pickedPoNo != null)

                {


                    int Count = 0;

                    foreach (DataRow dr in pickedPoNo.Rows)

                    {

                        if (Count == 0)

                        {

                            PickedCode += dr["PoNo"].ToString() + " ";

                            Count = 1;

                        }

                        else

                        {

                            PickedCode += ", " + dr["PoNo"].ToString() + " ";

                        }

                    }

                }

            }


            return PickedCode;

        }


        // Currency Work Step 1

        private void GetDefaultCurrency()

        {

            CurrencyMasterDAL activeDAL = new CurrencyMasterDAL();

            CurrencyMaster ActiveMasterList = new CurrencyMaster();

            CurrencyMaster ActiveMasterDefaultList = new CurrencyMaster();

            //if (Convert.ToInt32(ddlCurrency.SelectedValue) != 0)

            //{


            ActiveMasterList = activeDAL.CurrencyMasterGetById(Convert.ToInt32(ddlCurrency.SelectedValue));

            ActiveMasterDefaultList = activeDAL.CurrencyMasterGetDefault(Convert.ToInt32(Session["companyid"]));

            if (ActiveMasterList != null)

            {

                txtCurrencyRate.Text = ApplyFormatofCurrency(ActiveMasterList.FcRate);

                lblDefaultCurrencyCode.Text = ActiveMasterDefaultList.CurrencyShortName;

                if (ActiveMasterList.Id == ActiveMasterDefaultList.Id)

                {

                    lblCurrencyCode.Text = ActiveMasterDefaultList.CurrencyShortName;

                }

                else

                {

                    lblCurrencyCode.Text = ActiveMasterList.CurrencyShortName;

                }


            }

            //}

        }


        // Currency Work Step 3

        private bool ApplyFactoronCurrency(int CurrencyID)

        {

            bool IsDivide = false;

            CurrencyMaster ActiveMaster = new CurrencyMaster();

            CurrencyMasterDAL activeDAL = new CurrencyMasterDAL();

            ActiveMaster = activeDAL.CurrencyMasterGetById(CurrencyID);

            if (ActiveMaster != null)

            {

                IsDivide = ActiveMaster.IsDivide;

            }

            return IsDivide;

        }


        // Currency Work Step 4

        private decimal CalculateCurrencyRate(int? CurrencyID, decimal CurrencyRate)

        {

            bool IsDivide = false;

            IsDivide = ApplyFactoronCurrency(Convert.ToInt32(CurrencyID));

            if (IsDivide)

            {

                CurrencyRate = 1 / CurrencyRate;

            }

            else

            {

                CurrencyRate = 1 * CurrencyRate;

            }

            return CurrencyRate;

        }


        protected void txtCurrencyRate_TextChanged(object sender, EventArgs e)

        {

            // CalculateBaseRate();

        }


        //private void CalculateBaseRate()

        //{

        //    bool IsDivide = false;

        //    decimal CurrencyRate = 0.00m;

        //    decimal UnitPrice = 0.00m;

        //    CurrencyRate = string.IsNullOrEmpty(txtCurrencyRate.Text) ? 1.00m : Convert.ToDecimal(txtCurrencyRate.Text);

        //    UnitPrice = string.IsNullOrEmpty(txtRate.Text) ? 0 : decimal.Parse(ApplyFormatofCurrency(Convert.ToDecimal(txtRate.Text)));


        //    txtRateofBase.Text = (UnitPrice * CurrencyRate).ToString("0.00");

        //}




        protected void txtQty_TextChanged(object sender, EventArgs e)

        {

            // CalculateBaseRate();

        }

        private decimal ApplyRuleofDecimalCurrency(decimal Amount)

        {

            decimal strFormatCurr = 0.00m;

            CurrencySetupDal objSetupDAl = new CurrencySetupDal();

            CurrencySetup objCurrSetup = objSetupDAl.SetupGetByCompanyId(Convert.ToInt32(Session["CompanyID"]));

            if (objCurrSetup != null)

            {

                if (objCurrSetup.IsRoundOff)

                {

                    Amount = Math.Round(Amount, objCurrSetup.DecimalPlace);

                }

                else

                {

                    Amount = TruncateDecimal(Amount, objCurrSetup.DecimalPlace);

                }


                strFormatCurr = Amount;

            }

            else

            {

                strFormatCurr = Amount;

            }


            return strFormatCurr;

        }

        private string ApplyFormatofCurrency(decimal Amount)

        {

            string strFormatCurr = string.Empty;

            CurrencySetupDal objSetupDAl = new CurrencySetupDal();

            CurrencySetup objCurrSetup = objSetupDAl.SetupGetByCompanyId(Convert.ToInt32(Session["CompanyID"]));

            if (objCurrSetup != null)

            {

                if (objCurrSetup.IsRoundOff)

                {

                    Amount = Math.Round(Amount, objCurrSetup.DecimalPlace);

                }

                else

                {

                    Amount = TruncateDecimal(Amount, objCurrSetup.DecimalPlace);

                }


                strFormatCurr = string.Format(objCurrSetup.CurrencyString, Amount);

            }

            else

            {

                strFormatCurr = string.Format("{0:0,0.00}", Amount);

            }


            return strFormatCurr;

        }

        private string CurrencyFormat()

        {

            string strFormatCurr = string.Empty;

            CurrencySetupDal objSetupDAl = new CurrencySetupDal();

            CurrencySetup objCurrSetup = objSetupDAl.SetupGetByCompanyId(Convert.ToInt32(Session["CompanyID"]));

            if (objCurrSetup != null)

            {



                strFormatCurr = objCurrSetup.CurrencyString;

            }

            else

            {

                strFormatCurr = "{0:0,0.00}";

            }


            return strFormatCurr;

        }

        public decimal TruncateDecimal(decimal value, int precision)

        {

            decimal step = (decimal)Math.Pow(10, precision);

            decimal tmp = Math.Truncate(step * value);

            return tmp / step;

        }


        protected void txtRate_TextChanged(object sender, EventArgs e)

        {

            //CalculateBaseRate();

        }


        private bool CheckAllWarehouse(int ProductID)

        {

            bool isAllowInventory = false;

            ProductDAL objProductDAL = new ProductDAL();

            Product activeProduct = objProductDAL.ProductGetById(ProductID);

            if (activeProduct != null)

            {

                isAllowInventory = activeProduct.AllWahrehouseTransaction;

            }

            else

            {

                isAllowInventory = activeProduct.AllWahrehouseTransaction;

            }

            return isAllowInventory;

        }

        private int CheckWarehouseID(int ProductID)

        {

            int WarehouseID = 0;

            ProductDAL objProductDAL = new ProductDAL();

            Product activeProduct = objProductDAL.ProductGetById(ProductID);

            if (activeProduct != null)

            {

                WarehouseID = activeProduct.WarehouseId;

            }

            else

            {

                WarehouseID = activeProduct.WarehouseId;

            }

            return WarehouseID;

        }


        protected void btnAddnewProduct_Click(object sender, EventArgs e)

        {

            ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "<script>$('#SelectProductModal').modal('show');</script>", false);

        }

        private void BindDiscountTax()

        {

            try

            {

                DiscountTaxMasterDAL activeDiscountTaxMasterDAL = new DiscountTaxMasterDAL();

                List<DiscountTaxMaster> activeList = activeDiscountTaxMasterDAL.DiscountTaxMasterSelectByActiveandPurchaseVAT();

                DiscountTaxMaster activeUnit = new DiscountTaxMaster();

                activeUnit.DisTaxName = "None";

                activeUnit.Id = 0;

                activeList.Insert(0, activeUnit);

                ddlVatDiscount.DataSource = activeList;

                ddlVatDiscount.DataValueField = "Id";

                ddlVatDiscount.DataTextField = "DisTaxName";

                ddlVatDiscount.DataBind();

            }

            catch (Exception ex)

            {


            }

        }


        private string RefCode()

        {

            string RefNo = "";

            try

            {


                SaleInquiryDAl activeDAL = new SaleInquiryDAl();

                SaleInquiry activeMemberMaxId = activeDAL.SaleInquiryGetRefNoMaxId();


                if (activeMemberMaxId != null)

                {

                    if (activeMemberMaxId.Ref != "")

                    {


                        string theString = activeMemberMaxId.Ref;

                        var subString = theString.Substring(theString.LastIndexOf('-') + 1);

                        int add = Convert.ToInt32(subString);

                        int code = add + 1;


                        subString = Regex.Replace(subString, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));


                        string sinq = "REF-";

                        //txtCode.Value =  sinq + subString;

                        RefNo = sinq + subString;


                        ViewState["RefNo"] = RefNo;

                    }

                    else

                    {

                        string caption = "REF-00001";

                        //txtCode.Value = caption;

                        RefNo = caption;


                        ViewState["RefNo"] = RefNo;


                    }


                }

                else

                {

                    string caption = "REF-00001";

                    //txtCode.Value = caption;

                    RefNo = caption;


                    ViewState["RefNo"] = RefNo;


                }


            }


            catch (Exception ex)

            {

                throw ex;

            }

            return RefNo;

        }


        private void FixedPrice(bool isFixedPrice)

        {

            if (isFixedPrice)

            {

                txtRate.Enabled = false;

                txtDiscountAmount.Enabled = false;

                checkboxDiscountPercentage.Disabled = true;

            }

            else

            {

                txtRate.Enabled = true;

                txtDiscountAmount.Enabled = true;

                checkboxDiscountPercentage.Disabled = false;

            }

        }


        private void BindPriceList()

        {

            try

            {

                VendorPriceSetupDAL activeDAL = new VendorPriceSetupDAL();

                List<VendorPriceSetup> activeList = activeDAL.VendorPriceSelect();

                VendorPriceSetup activeUnit = new VendorPriceSetup();

                activeUnit.Name = "Master Price";

                activeUnit.Id = 0;

                if (activeList != null)

                {

                    activeList.Insert(0, activeUnit);

                    ddlpricelist.DataSource = activeList;

                    ddlpricelist.DataValueField = "Id";

                    ddlpricelist.DataTextField = "Name";

                    ddlpricelist.DataBind();

                }

                else

                {

                    ddlpricelist.Items.Insert(0, new ListItem("Master Price", "0"));

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)

        {

            VendorDAL objVendorDAL = new VendorDAL();

            Vendor ven = objVendorDAL.VendorGetById(Convert.ToInt32(ddlVendor.SelectedValue));


            if (ven != null)

                if (ddlpricelist.Items.FindByValue(ven.VendorPriceListId.ToString()) != null)

                    ddlpricelist.SelectedValue = ven.VendorPriceListId.ToString();

        }


        protected void ddlpricelist_SelectedIndexChanged(object sender, EventArgs e)

        {

            if (!string.IsNullOrEmpty(txtPartNo.Text) && !string.IsNullOrEmpty(txtProduct.Text))

            {

                ProductDAL activeDAL = new ProductDAL();

                WebDeskValidator Obj_VLDTR = new WebDeskValidator();

                string alertMsgForRate = "";


                Product activeProductRate = activeDAL.ProductGetByPartNoObject(txtPartNo.Text);


                if (activeProductRate != null)

                {

                    Product objprice = new Product();

                    objprice = activeDAL.ProductRateGetById(0, activeProductRate.ProductId, Convert.ToInt32(ddlpricelist.SelectedValue));


                    if (objprice != null)

                    {

                        if (objprice.PriceApplicableDate <= Convert.ToDateTime(single_cal4.Text) || objprice.PriceApplicableDate == null) // Comparing Price list Date With Selected Date

                            txtRate.Text = ApplyFormatofCurrency(objprice.CostPrice);

                        else

                        {

                            txtRate.Text = "0.00";

                            alertMsgForRate = "Price list rate is applicable from this document date " + string.Format("{0:MM/dd/yyyy}", objprice.PriceApplicableDate);

                        }

                    }

                    else

                        txtRate.Text = "0.00";

                }

            }

        }

        public void BindUnit()

        {

            try

            {

                UnitDAL activeDAL = new UnitDAL();

                List<Unit1> activeList = activeDAL.ProductUnitSelectActiveByCompanyId(Convert.ToInt32(Session["companyid"]));

                if (activeList != null && activeList.Count > 0)

                {

                    ddlUnit.DataSource = activeList;

                    ddlUnit.DataValueField = "Id";

                    ddlUnit.DataTextField = "UnitName";

                    ddlUnit.DataBind();

                    ddlUnit.Items.Insert(0, new ListItem("None", "0"));

                    Unit1 objunit = activeList.Find(x => x.Default == true && x.Active == true);

                    if (objunit != null)

                        ddlUnit.SelectedValue = objunit.Id.ToString();

                }

                else

                {

                    ddlUnit.Items.Insert(0, new ListItem("None", "0"));

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }

        public decimal StockingUnitGetByProductID(int ProductID, int UnitID)

        {

            decimal stockingUnit = 0.00m;

            decimal NoofUnit = 0.00m;

            ProductDAL objProductDAL = new ProductDAL();

            Product objProduct = objProductDAL.ProductGetById(ProductID);

            if (objProduct != null)

            {

                stockingUnit = UnitGetByID(objProduct.ProUnitId);

                NoofUnit = UnitGetByID(UnitID);

                NoofUnit = stockingUnit * NoofUnit;

            }

            else

            {

                stockingUnit = 1;

            }

            return NoofUnit;


        }


        private decimal UnitGetByID(int UnitID)

        {

            decimal Qty = 0;

            UnitDAL objUnitDAl = new UnitDAL();

            Unit1 objUnit = objUnitDAl.UnitSelectGetById(UnitID);

            if (objUnit != null)

            {

                if (objUnit.NoofStockUnit != 0)

                {

                    Qty = objUnit.NoofStockUnit;

                }

                else

                {

                    Qty = 1;

                }

            }

            else

            {

                Qty = 1;

            }


            return Qty;

        }


        public decimal GetUnitPricebyproductIdandUnitID(int ProductID, int UnitID)

        {

            decimal UnitPrice = 0.00m;

            decimal stocking = StockingUnitGetByProductID(ProductID, UnitID);

            //UnitDAL objunitDAL = new UnitDAL();

            //Unit1 objunit = objunitDAL.UnitSelectGetById(Convert.ToInt32(UnitID));

            //if (objunit != null)

            //{

            PurcahseDtlDtlDAL objPurchaseDtlDAl = new PurcahseDtlDtlDAL();

            decimal PurchasePrice = objPurchaseDtlDAl.GetAvgAmountFromPurchase(ProductID);

            PurchasePrice = PurchasePrice * stocking;

            // }

            return PurchasePrice;

        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)

        {

            int ProductID = !string.IsNullOrEmpty(lblProductId.Text) ? Convert.ToInt32(lblProductId.Text) : 0;

            txtRate.Text = GetUnitPricebyproductIdandUnitID(ProductID, Convert.ToInt32(ddlUnit.SelectedValue)).ToString("0.00");


        }

        private string FinancialYearStartDateGetById()

        {

            string strdateyear = "";

            try

            {

                FinancialYearMasterDAL activeFinancialYearMasterDAL = new FinancialYearMasterDAL();

                FinancialYearMaster activeFinancialYearMaster = activeFinancialYearMasterDAL.FinancialYearMasterGetById(Convert.ToInt32(Session["FinancialYearID"]));

                if (activeFinancialYearMaster.StartDate != null)

                {

                    strdateyear = activeFinancialYearMaster.StartDate.ToString("yy");

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }

            return strdateyear;

        }

    }

}

No comments:

Post a Comment