protected void btnSaveCetification_Click(object sender, ImageClickEventArgs e)
 {
     ProductManager productManager = new ProductManager(this);
     productManager.InsertProductCertificate(productId, new ProductCertificate()
     {
         Name = txtCertification.Text
     });
     DataBind();
     txtCertification.Text = String.Empty;
 }
 protected void btnSavePackage_Click(object sender, ImageClickEventArgs e)
 {
     var productManager = new ProductManager(this);
     productManager.InsertProductPackage(productId, new ProductPackage
                                                    {
                                                        Name = txtPackage.Text,
                                                        RequiresQuotationInPurchasing = chkRequiredQuotation.Checked
                                                        
                                                    });
     DataBind();
     txtPackage.Text = String.Empty;
 }
        protected void btnSaveFabricante_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtManufacturer.Text))
                return;

            var productManager = new ProductManager(this);
            productManager.InsertProductManufacturer(productId,
                                                     new ProductManufacturer
                                                     {
                                                         Name = txtManufacturer.Text
                                                     });

            grdManufacturer.DataBind();
            txtManufacturer.Text = String.Empty;
        }
        protected void btnGeneratePurchaseOrder_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(Request["requestItems"]))
            {
                ShowError("É necessário escolher produtos para avançar!");
                return;
            }

            
            int previousCity = -1;
            var productManager = new ProductManager(this);
            foreach (string requestItem in Request["requestItems"].Split(','))
            {
                string[] item = requestItem.Trim().Split('|');
                int productId = Convert.ToInt32(item[0]);
                //int productPackageId = Convert.ToInt32(item[1]);
                //int productManufacturerId = Convert.ToInt32(item[2]);
                //int requestAmount = Convert.ToInt32(item[3]);
                //string centerCost = item[4];
                int cityId = Convert.ToInt32("0" + item[5]);


                Product product = productManager.GetProduct(productId, Company.CompanyId);
                if (product != null)
                    if (product.RequiresAuthorization.Value && (Employee.CentralBuyer != true))
                    {
                        ShowError(product.Name + " é comprado apenas pela sede, requisição encaminhada ao setor de compras!");
                        return;
                    }

                if (previousCity != -1 && cityId != previousCity)
                {
                    ShowError("Não pode gerar um processo de compra para cidades diferentes!");
                    return;
                }

                previousCity = cityId;
            }

            Context.Items["PurchaseRequest"] = true;
            Server.Transfer("PurchaseOrder.aspx");
        }
        public void InventoryDrop(Inventory currentInventory, int? quantity, Int32 dropTypeId, Int32? saleId)
        {
            Inventory originalInventory = GetProductInventory(currentInventory.CompanyId, currentInventory.ProductId,
                                                              currentInventory.DepositId);

            var inventoryManager = new InventoryManager(this);
            if (dropTypeId != (int)DropType.Sell &&
                !inventoryManager.CheckIfCanTransfer(currentInventory.CompanyId, currentInventory.ProductId,
                                                     currentInventory.DepositId, quantity.Value))
                throw new InvalidOperationException();

            //
            //insert one row in InventoryHistory
            //

            InsertHistoryFromInventory(originalInventory, dropTypeId, saleId, null);

            originalInventory.Quantity -= Convert.ToInt32(quantity);
           
            //
            //drop StockComposite
            //
           
            var productManager = new ProductManager(this);

            Product product = productManager.GetProduct(originalInventory.ProductId);

            if (product.DropCompositeInStock)
            {
                List<CompositeProduct> listCompositProduct =
                    productManager.GetChildCompositeProducts(product.ProductId).ToList();
                for (int i = 0; i < listCompositProduct.Count; i++)
                {
                    Inventory compositeInventory = GetProductInventory(currentInventory.CompanyId,
                                                                       listCompositProduct[i].ProductId,
                                                                       originalInventory.DepositId);
                    if (compositeInventory != null)
                        InventoryDrop(compositeInventory, 1, dropTypeId, saleId);
                }
            }

            DbContext.SubmitChanges();
        }
        protected void AddExistentSaleItem()
        {
            SaleItem saleItem = new SaleItem();
            Product product = new ProductManager(this).GetProductByName((int)Company.MatrixId, selProduct.Name);
            Inventory productInInventory = new InventoryManager(this).GetProductInventory(
                 Company.CompanyId, product.ProductId, Deposit.DepositId);

            saleItem.ProductId = product.ProductId;
            saleItem.Name = selProduct.Name;
            //se o preco na tela for != de null, então ele é convertido e arqmazenado
            //senão verificamos se o preco do produto já existe em inventário, se este for o caso, armazenamos o preco
            //senão, setamos 0 para o price 
            saleItem.Price = ucCurrFieldUnitPrice.CurrencyValue.HasValue ? ucCurrFieldUnitPrice.CurrencyValue.Value : (productInInventory != null ? Convert.ToDecimal(productInInventory.UnitPrice) : Decimal.Zero);
            saleItem.Quantity = ucCurrFieldQuantityData.IntValue;
            if (productInInventory != null)
                saleItem.UnitCost = productInInventory.RealCost;

            SaleItemList.Add(saleItem);
        }
        /// <summary>
        /// Method to insert a Item in the saleItem
        /// This method verifies if you are trying to insert a composite product, and treat it
        /// insert a customerEquipment If the customer exists
        /// This method also, drop off the quantity in the inventory
        /// </summary>
        /// <param name="item"></param>
        /// <param name="sale"></param>
        public void InsertSaleItem(SaleItem saleItem, Sale sale)
        {
            DbContext.SaleItems.InsertOnSubmit(saleItem);
            DbContext.SubmitChanges();

            var product = new ProductManager(this).GetProduct(Convert.ToInt32(saleItem.ProductId),
                                                                             saleItem.CompanyId);
            if (product != null)
                saleItem.ProductId = product.ProductId;
            DbContext.SubmitChanges();

            SaveSaleItemAsCustomerEquipment(saleItem);
            DropProductInSale(saleItem);
        }
        private void ShowProduct()
        {
            _productManager = new ProductManager(this);
            Product product = _productManager.GetProduct(Convert.ToInt32(Page.ViewState["ProductId"]));

            if (product == null)
                product = _productManager.GetTempProduct(Convert.ToInt32(Page.ViewState["ProductId"]), Company.CompanyId);

            if (product == null)
                return;

            if (product.IsTemp == true)
                btnApproveProduct.Visible = true;

            txtProduct.Name = product.Name;
            txtProductCode.Text = product.ProductCode;
            txtBarCode.Text = product.BarCode;
            txtIdentificationOrPlaca.Text = product.IdentificationOrPlaca;
            txtPatrimonioOrRenavam.Text = product.PatrimonioOrRenavam;
            txtSerialNumberOrChassi.Text = product.SerialNumberOrChassi;
            DescriptionTextBox.Value = product.Description;
            ucCurrFieldIPI.CurrencyValue = product.IPI;
            ucCurrFieldICMS.CurrencyValue = product.ICMS;
            ucCurrFieldWarrantyDays.CurrencyValue = product.WarrantyDays;
            txtFiscalClass.Text = product.FiscalClass;
            chkAddCustomerEquipment.Checked = Convert.ToBoolean(product.AddCustomerEquipmentInSale);
            chkAllowNegativeStock.Checked = Convert.ToBoolean(product.AllowNegativeStock);
            chkAllowSaleBelowCost.Checked = Convert.ToBoolean(product.AllowSaleBelowCost);
            chkDropCompositeInStock.Checked = Convert.ToBoolean(product.DropCompositeInStock);
            ChkIsActive.Checked = Convert.ToBoolean(product.IsActive);


            #region non required/opcional fields

            /*
             * Add fields here that may not be used or only used in some companies(_companies)
             * Here is made a verification if there's value in the field of the DataBank to not assign a
             * null value to a control and prevent exceptions
             */


            if (cboCategories != null && product.CategoryId.HasValue)
                cboCategories.SelectedValue = product.CategoryId.ToString();

            if (txtManufacturer != null && product.ManufacturerId.HasValue)
                txtManufacturer.Text = product.Manufacturer.Name;

            if (cboBarCodeType != null && product.BarCodeTypeId.HasValue)
                cboBarCodeType.SelectedValue = product.BarCodeTypeId.ToString();

            if (chkRequiresAuthorization != null && product.RequiresAuthorization.HasValue)
                chkRequiresAuthorization.Checked = (bool)product.RequiresAuthorization;

            if (txtUnit != null)
                txtUnit.Text = product.Unit;

            if (txtPackage != null)
                txtPackage.Text = product.Package;

            if (txtKeyWord != null)
                txtKeyWord.Text = product.Keywords;

            if (chkIsCasting != null)
                chkIsCasting.Checked = Convert.ToBoolean(product.IsCasting);

            if (chkIsEmphasizeInHome != null)
                chkIsEmphasizeInHome.Checked = Convert.ToBoolean(product.EmphasizeInHome);

            if (ucCurrFieldWheight != null)
                ucCurrFieldWheight.CurrencyValue = product.Weight;

            #endregion
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            _productManager = new ProductManager(this);
            product = new Product();

            if (Page.ViewState["ProductId"] != null)
            {
                originalProduct = _productManager.GetProduct(Convert.ToInt32(Page.ViewState["ProductId"]));
            }
            else if (_productManager.CheckIfProductCodeExists(Company.CompanyId, txtProductCode.Text))
            {
                ShowError(Exception.DuplicateCode);
                return;
            }

            if (originalProduct == null)
                originalProduct = _productManager.GetTempProduct(Convert.ToInt32(Page.ViewState["ProductId"]), Company.CompanyId);

            if (originalProduct != null)
                product.CopyPropertiesFrom(originalProduct);

            product.CompanyId = (Int32)Company.MatrixId;

            if (!String.IsNullOrEmpty(cboCategories.SelectedValue))
                product.CategoryId = Convert.ToInt32(cboCategories.SelectedValue);

            product.Name = txtProduct.Name;
            InsertManufacturer(product);

            product.ProductCode = txtProductCode.Text;
                        
            product.BarCode = txtBarCode.Text;
            product.IdentificationOrPlaca = txtIdentificationOrPlaca.Text;
            product.PatrimonioOrRenavam = txtPatrimonioOrRenavam.Text;

            product.SerialNumberOrChassi = txtSerialNumberOrChassi.Text;
            product.IPI = ucCurrFieldIPI.CurrencyValue;
            product.ICMS = ucCurrFieldICMS.CurrencyValue;
            product.FiscalClass = txtFiscalClass.Text;
            product.WarrantyDays = ucCurrFieldWarrantyDays.IntValue;

            product.Description = DescriptionTextBox.Value;
            product.IsActive = ChkIsActive.Checked;
            product.DropCompositeInStock = Convert.ToBoolean(chkDropCompositeInStock.Checked);
            product.AddCustomerEquipmentInSale = Convert.ToBoolean(chkAddCustomerEquipment.Checked);
            product.AllowNegativeStock = Convert.ToBoolean(chkAllowNegativeStock.Checked);

            product.AllowSaleBelowCost = Convert.ToBoolean(chkAllowSaleBelowCost.Checked);
            product.ModifiedDate = DateTime.Now;
            product.RequiresAuthorization = chkRequiresAuthorization.Checked;

            #region Optional Fields
            /*
             * Add fields here that may not be used or only used in some companies(_companies)
             * Here is made a verification if there's value in the control to not assign a value
             * to the DataBank from a null control and prevent exceptions
             */

            if (!String.IsNullOrEmpty(cboBarCodeType.SelectedValue))
                product.BarCodeTypeId = Convert.ToInt32(cboBarCodeType.SelectedValue);

            if (txtUnit != null)
                product.Unit = txtUnit.Text;

            if (txtKeyWord != null)
                product.Keywords = txtKeyWord.Text;

            if (txtPackage != null)
                product.Package = txtPackage.Text;

            if (chkIsEmphasizeInHome != null)
                product.EmphasizeInHome = chkIsEmphasizeInHome.Checked;

            if (chkIsCasting != null)
                product.IsCasting = chkIsCasting.Checked;

            if (ucCurrFieldWheight != null)
                product.Weight = ucCurrFieldWheight.CurrencyValue;



            #endregion

            if (!String.IsNullOrEmpty(Request["IsTemp"]))
                product.IsTemp = true;

            string redirectUrl = "";

            if (originalProduct == null)
            {
                product.CreatedByUser = User.Identity.UserName;
                _productManager.Insert(product);
            }
            else
            {
                product.ModifiedByUser = User.Identity.UserName;
                _productManager.Update(originalProduct, product);
                redirectUrl = "parent.";
            }

            if (((WebControl)sender).ID == "btnSaveAndNew")
                redirectUrl += "location='Product_General.aspx';";
            else
            {
                if (product.IsTemp == true)
                    redirectUrl += "location='../Purchasing/PurchaseRequests.aspx';";
                else
                    redirectUrl += "location='Product.aspx?ProductId=" + product.ProductId + "'";
            }

            Page.ClientScript.RegisterClientScriptBlock(GetType(), "", redirectUrl, true);
        }
 public ClientResponse FindProductInInventory(string q, int limit)
 {
     return new ClientResponse(() =>
     {
         using (var manager = new ProductManager(null))
             return manager.SearchProductInInventory(User.Identity.UserId, q, limit).ToArray();
     });
 }
 public ClientResponse FindProducts(string q, int limit)
 {
     return new ClientResponse(() =>
     {
         using (var manager = new ProductManager(null))
             return manager.SearchProduct((int)Company.MatrixId, q, limit).ToArray();
     });
 }