public void Save(EditConsolidatedProductOut vm)
        {
            if (vm.brandCode != null || vm.packagingCode != null || vm.packagingTypeCode != null)
            {
                ProductBrand pd = _productBrandRepository.GetAll().FirstOrDefault(n => n.Code == vm.brandCode);
                ProductPackaging ppg = _productPackagingRepository.GetAll().FirstOrDefault(n => n.Code == vm.packagingCode);
                ProductPackagingType ppgT = _productPackagingTypeRepository.GetAll().FirstOrDefault(n => n.Code == vm.packagingTypeCode);


                ConsolidatedProduct _cp = _productRepository.GetById(vm.Id) as ConsolidatedProduct;
                if (_cp==null)
                    _cp = _productFactory.SaveConsolidatedProduct(vm.Id);
                
                   
                _cp.Description = vm.Description;
                _cp.Brand = _productBrandRepository.GetById(pd.Id);
                _cp.Packaging = _productPackagingRepository.GetById(ppg.Id);
                _cp.PackagingType = _productPackagingTypeRepository.GetById(ppgT.Id);
                _cp.ProductCode = vm.ProductCode;
                _cp.ExFactoryPrice = vm.ExFactoryPrice;

                _productRepository.Save(_cp);
            }
            else
            {
                ConsolidatedProduct _cp = _productRepository.GetById(vm.Id) as ConsolidatedProduct;
                if (_cp==null)
                    _cp = _productFactory.SaveConsolidatedProduct(vm.Id);
                  
                _cp.Description = vm.Description;
                _cp.Brand = _productBrandRepository.GetById(vm.BrandId);
                _cp.Packaging = _productPackagingRepository.GetById(vm.PackagingId);
                _cp.PackagingType = _productPackagingTypeRepository.GetById(vm.PackagingTypeId);
                _cp.ProductCode = vm.ProductCode;
                _cp.ExFactoryPrice = vm.ExFactoryPrice;

                _productRepository.Save(_cp);
            }
            
            
            //Get Consolidated Product
           // var cp = _productRepository.GetAll().ToList().OfType<ConsolidatedProduct>().OrderByDescending(n => n._DateCreated).FirstOrDefault();
            //Save(cp.Id,1);
        }
 public void AddItemToConsolidatedProduct(EditConsolidatedProductOut vm)
 {
     ConsolidatedProduct _cp = _productRepository.GetById(vm.Id) as ConsolidatedProduct;
     Product toAdd = _productRepository.GetById(vm.ProductID);
     if (_cp.CanAddProductToConsolidatedProduct(toAdd,_cp))
         _cp.ProductDetails.Add(new ConsolidatedProduct.ProductDetail { Product = toAdd, QuantityPerConsolidatedProduct = vm.Quantity });
     _productRepository.Save(_cp);
 }
        public ActionResult CreateConsolidatedProduct(EditConsolidatedProductOut spvm, Guid? thisId)
        {
            ViewBag.BrandsList = _productViewModelBuilder.GetBrands();

            ViewBag.PackagingsList = _productViewModelBuilder.GetPackaging();
            ViewBag.PackTypeList = _productViewModelBuilder.GetPackagingType();

            try
            {
                if (spvm.Description == null)
                {
                    ModelState.AddModelError("Consolidated Product", "Consolidated product is required");
                    //return View();
                    TempData["msg"] = "Product Name Is Required";
                    ViewBag.msg = TempData["msg"].ToString();
                    return RedirectToAction("CreateConsolidatedProduct", new { @thisId = 0 });
                }
                else
                {
                    spvm.Id = thisId.Value;
                    spvm.Id = Guid.NewGuid();
                    _productViewModelBuilder.Save(spvm);
                    TempData["msg"] = "Consolidated Product Successfully Created";
                    return RedirectToAction("Index");
                }

            }
            catch (Exception ex)
            {
               
                return View();
            }
        }
        public EditConsolidatedProductOut CreateEditConsolidatedProductViewModel(Guid productid)
        {
            ConsolidatedProduct p = _productRepository.GetById(productid) as ConsolidatedProduct;

            var pb  = _productBrandRepository.GetAll().ToDictionary(d => d.Id, d => d.Name);
            var pp  = _productPackagingRepository.GetAll().ToDictionary(d => d.Id, d => d.Name);
            var ppt = _productPackagingTypeRepository.GetAll().ToDictionary(d => d.Id, d => d.Name);
            var pL  = _productRepository.GetAll(false).ToDictionary(d => d.Id, d => d.Description);

            List<EditConsolidatedProductOut.ProductDetailViewModel> cppd = null;
            cppd = p.ProductDetails.Select(n => new EditConsolidatedProductOut.ProductDetailViewModel
                {
                    Brand         = n.Product.Brand.Name,
                    Descritpion   = n.Product.Description,
                    ProductCode   = n.Product.ProductCode,
                    Packaging     = n.Product.Packaging==null ?"": n.Product.Packaging.Name,
                    PackagingType = n.Product.PackagingType.Name,
                    ProductId     = n.Product.Id,
                    Qty           = n.QuantityPerConsolidatedProduct,
                }).ToList();

            //cn : filter to remove already existing products in Consolidated product and itself.
            pL = pL.Where(_p => (!cppd.Select(x => x.ProductId).Contains(_p.Key)) && _p.Key != p.Id).ToDictionary(d => d.Key, d => d.Value);
            var vm = new EditConsolidatedProductOut
            {
                Title                 = "Edit Consolidated Product",
                Id                    = p.Id,
                Description           = p.Description,
                BrandId               = p.Brand.Id,
                PackagingId = p.Packaging == null ? Guid.Empty : p.Packaging.Id,
                PackagingTypeId       = p.PackagingType.Id,
                ProductCode           = p.ProductCode,
                ProductDetails        = cppd,
                ExFactoryPrice=p.ExFactoryPrice,
                ProductPackagings = new SelectList(pp, "Key", "Value", p.Packaging == null ? Guid.Empty : p.Packaging.Id),
                ProductPackagingTypes = new SelectList(ppt, "Key", "Value", p.PackagingType.Id),
                ProductBrands         = new SelectList(pb, "Key", "Value", p.Brand.Id),
                ProductList           = new SelectList(pL, "Key", "Value"),
            };
            return vm;

           
        }
        public ActionResult EditConsolidatedProduct(EditConsolidatedProductOut vm, Guid? thisId)
        {

            ViewBag.BrandsList = _productViewModelBuilder.GetBrands();
            ViewBag.FlavoursList = _productViewModelBuilder.GetFlavours();
            ViewBag.PackagingsList = _productViewModelBuilder.GetPackaging();
            ViewBag.PackTypeList = _productViewModelBuilder.GetPackagingType();
            ViewBag.ProductTypeList = _productViewModelBuilder.GetProductType();
            //vm.Id = thisId.Value;
            try
            {
                //vm.Id = thisId;
                _productViewModelBuilder.Save(vm);
                TempData["msg"] = "Consolidated Product Successfully Edited";
                return RedirectToAction("Index");
            }
            catch (DomainValidationException dve)
            {
                ValidationSummary.DomainValidationErrors(dve, ModelState);
                ViewBag.msg = dve.Message;
                return View();
            }
            catch (Exception ex)
            {
                ViewBag.msg = ex.Message;
                return View();
            }
        }
        public ActionResult ImportProduct(HttpPostedFileBase file)
        {

            try
            {

                var fileName = Path.GetFileName(file.FileName);


                var directory = Server.MapPath("~/Uploads");
                if (Directory.Exists(directory) == false)
                {
                    Directory.CreateDirectory(directory);
                }
                var path = Server.MapPath("~/Uploads") + "\\" + fileName;


                file.SaveAs(path);


                string fileExtension = Path.GetExtension(fileName);
                if (fileExtension == ".xlsx")
                {
                    ViewBag.msg = "Please wait. Upload in progress";

                    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;'";

                    OleDbConnection conn = new OleDbConnection(connectionString);
                    try
                    {
                        conn.Open();
                        string product = "";
                        OleDbCommand commProduct = new OleDbCommand("SELECT product FROM [Sheet1$]", conn);
                        OleDbDataReader readProduct = commProduct.ExecuteReader();
                        while (readProduct.Read())
                        {
                            product = readProduct["product"].ToString();
                        }
                        if (product == "Sale Product")
                        {
                            OleDbCommand command = new OleDbCommand("SELECT brandCode,subBrandCode,packagingtypeCode,packagingCode,productTypeCode,vatClass,code,description FROM [Sheet1$]", conn);
                            OleDbDataReader reader = command.ExecuteReader();
                            SaleProductViewModel pdvm = new SaleProductViewModel();
                            while (reader.Read())
                            {

                                string brandCode = reader["brandCode"].ToString();
                                string subBrandCode = reader["subBrandCode"].ToString();
                                string packagingTypeCode = reader["packagingTypeCode"].ToString();
                                string packagingCode = reader["packagingCode"].ToString();
                                string productTypeCode = reader["productTypeCode"].ToString();
                                string vatClass = reader["vatClass"].ToString();
                                string productCode = reader["code"].ToString();
                                string description = reader["description"].ToString();

                                pdvm.brandCode = brandCode;
                                pdvm.subBrandCode = subBrandCode;
                                pdvm.packTypeCode = packagingTypeCode;
                                pdvm.packCode = packagingCode;
                                pdvm.productTypeCode = productTypeCode;
                                pdvm.vatClass = vatClass;
                                pdvm.ProductCode = productCode;
                                pdvm.Description = description;
                                _productViewModelBuilder.SaveSaleProduct(pdvm);

                            }
                        }
                        else if (product == "Returnable Product")
                        {
                            OleDbCommand command = new OleDbCommand("SELECT Brand,SubBrand,PackagingType,Packaging,ProductType,VatClass,ProductCode,Description,returnableType FROM [Sheet1$]", conn);
                            OleDbDataReader reader = command.ExecuteReader();
                            EditReturnableProductViewModelIn pdvm = new EditReturnableProductViewModelIn();
                            while (reader.Read())
                            {

                                string brandCode = reader["brand"].ToString();
                                string subBrandCode = reader["subBrand"].ToString();
                                string packagingTypeCode = reader["packagingType"].ToString();
                                string packagingCode = reader["packaging"].ToString();
                                string productTypeCode = reader["productType"].ToString();
                                string vatClass = reader["vatClass"].ToString();
                                string productCode = reader["productcode"].ToString();
                                string description = reader["description"].ToString();
                                string returnableType = reader["returnableType"].ToString();

                                pdvm.brandCode = brandCode;
                                pdvm.subBrandCode = subBrandCode;
                                pdvm.packTypeCode = packagingTypeCode;
                                pdvm.packCode = packagingCode;
                                pdvm.productTypeCode = productTypeCode;
                                pdvm.vatClass = vatClass;
                                pdvm.ProductCode = productCode;
                                pdvm.Description = description;
                                pdvm.RetunableTypeName = returnableType;
                                _productViewModelBuilder.Save(pdvm);

                            }
                        }
                        else if (product == "Consolidated Product")
                        {
                            OleDbCommand command = new OleDbCommand("SELECT brandCode,packagingtypeCode,packagingCode,code,description FROM [Sheet1$]", conn);
                            OleDbDataReader reader = command.ExecuteReader();
                            EditConsolidatedProductOut vm = new EditConsolidatedProductOut();

                            string brandCode = reader["brandCode"].ToString();
                            string packagingTypeCode = reader["packagingTypeCode"].ToString();
                            string packagingCode = reader["packagingCode"].ToString();
                            string code = reader["Code"].ToString();
                            string description = reader["description"].ToString();

                            vm.brandCode = brandCode;
                            vm.packagingTypeCode = packagingTypeCode;
                            vm.packagingCode = packagingCode;
                            vm.ProductCode = code;
                            vm.Description = description;
                            _productViewModelBuilder.Save(vm);
                        }
                    }
                    catch (OleDbException ex)
                    {
                        ViewBag.msg = ex.ToString();
                        try
                        {
                            HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                            hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Test", "editing sale product error:" + ex.Message);
                        }
                        catch (Exception exx)
                        { }
                        return View();
                    }

                    finally
                    {
                        conn.Close();

                    }

                    fi = new FileInfo(path);

                    fi.Delete();
                    _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Import", "Product", DateTime.Now);
                    ViewBag.msg = "Upload Successful";
                    return RedirectToAction("Index");
                }

                else
                {
                    fi = new FileInfo(path);

                    fi.Delete();
                    ViewBag.msg = "Please upload excel file with extension .xlsx";
                    return View();
                }
            }
            catch (Exception ex)
            {

                ViewBag.msg = ex.ToString();
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Test", "editing sale product error:" + ex.Message);
                }
                catch (Exception exx)
                { }
                return View();
            }


        }
        public ActionResult AddItem(EditConsolidatedProductOut spvm, Guid parentId)
        {
            ViewBag.BrandsList = _productViewModelBuilder.GetBrands();

            ViewBag.PackagingsList = _productViewModelBuilder.GetPackaging();
            ViewBag.PackTypeList = _productViewModelBuilder.GetPackagingType();
            try
            {
                spvm.Id = parentId;
                _productViewModelBuilder.AddItemToConsolidatedProduct(spvm);
                _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Create", "Consolidated Product Item", DateTime.Now);
                return RedirectToAction("AddItem", new { id = spvm.Id });
            }
            catch (Exception ex)
            {
                ViewBag.msg = ex.Message;
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Test", "editing sale product error:" + ex.Message);
                }
                catch (Exception exx)
                { }
                return RedirectToAction("AddItem", new { id = spvm.Id });
            }
        }
         public ActionResult CreateConsolidatedProduct(EditConsolidatedProductOut spvm, Guid? thisId)
        {
            ViewBag.BrandsList = _productViewModelBuilder.GetBrands();
           
            ViewBag.PackagingsList = _productViewModelBuilder.GetPackaging();
            ViewBag.PackTypeList = _productViewModelBuilder.GetPackagingType();
           
            try
            {
                if (spvm.Description == null)
                {
                    ModelState.AddModelError("Consolidated Product", "Consolidated product is required");
                   //return View();
                   TempData["msg"] = "Product Name Is Required";
                   ViewBag.msg = TempData["msg"].ToString();
                    return RedirectToAction("CreateConsolidatedProduct", new { @thisId = 0 });
                }
                else
                {
                    spvm.Id = thisId.Value;
                    spvm.Id = Guid.NewGuid();
                    _productViewModelBuilder.Save(spvm);
                    _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Create", "Consolidated Product", DateTime.Now);
                    _log.Info("Saving Consolidated Product:" + spvm);
                    TempData["msg"] = "Consolidated Product Successfully Created";
                    return RedirectToAction("Index");
                }
                
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Error in creating consolidated product " + ex.Message);
                _log.InfoFormat("Error in creating consolidated product " + ex.Message);
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Test", "editing sale product error:" + ex.Message);
                }
                catch (Exception exx)
                { }
                return View();
            }
        }
         public ActionResult EditConsolidatedProduct(EditConsolidatedProductOut vm, Guid? thisId)
        {
            
            ViewBag.BrandsList = _productViewModelBuilder.GetBrands();
            ViewBag.FlavoursList = _productViewModelBuilder.GetFlavours();
            ViewBag.PackagingsList = _productViewModelBuilder.GetPackaging();
            ViewBag.PackTypeList = _productViewModelBuilder.GetPackagingType();
            ViewBag.ProductTypeList = _productViewModelBuilder.GetProductType();
            //vm.Id = thisId.Value;
            try
            {
                //vm.Id = thisId;
                _productViewModelBuilder.Save(vm);
                _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Edit", "Consolidated Product", DateTime.Now);
                TempData["msg"] = "Consolidated Product Successfully Edited";
                return RedirectToAction("Index");
            }
            catch (DomainValidationException dve)
            {
                ValidationSummary.DomainValidationErrors(dve, ModelState);
                _log.ErrorFormat("Error in consolidated product " + dve.Message);
                _log.InfoFormat("Error in consolidated product " + dve.Message);
                ViewBag.msg = dve.Message;
                return View();
            }
            catch (Exception ex)
            {
                ViewBag.msg = ex.Message;
                _log.ErrorFormat("Error in consolidated product pricing" + ex.Message);
                _log.InfoFormat("Error in consolidated product pricing" + ex.Message);
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Test", "editing sale product error:" + ex.Message);
                }
                catch (Exception exx)
                { }
                return View();
            }
        }