private  ProductPricingViewModel Map(ProductPricing productPricing)
 {
   
     ProductPricingViewModel productPricingVm = new ProductPricingViewModel();
     {
        productPricingVm.CurrentEffectiveDate = productPricing.CurrentEffectiveDate;
         productPricingVm.CurrentExFactory = productPricing.CurrentExFactory;
        productPricingVm. CurrentSellingPrice = productPricing.CurrentSellingPrice;
        productPricingVm. Id = productPricing.Id;
        if (productPricing.ProductRef.ProductId != null)
        {
            productPricingVm.ProductId =  productPricing.ProductRef.ProductId;
            
        }
        productPricingVm.ProductName = _productRepository.GetById(productPricing.ProductRef.ProductId).Description;
        if (_productRepository.GetById(productPricing.ProductRef.ProductId).Description != null)
        {
            productPricingVm.ProductName = _productRepository.GetById(productPricing.ProductRef.ProductId).Description;
        }
        productPricingVm. TierId = productPricing.Tier.Id;
        productPricingVm. TierName = productPricing.Tier.Name;
        productPricingVm.Active = productPricing._Status == EntityStatus.Active ? true : false;
     };
     return productPricingVm;
 }
        public ActionResult Create(ProductPricingViewModel productPricingViewModel)
        {
            try
            {
                var settings = _settingsRepository.GetByKey(SettingsKeys.NumberOfDecimalPlaces);
                var decimalPlaces = settings != null ? settings.Value : "4";
                ViewBag.DecimalPlaces = decimalPlaces;

                if (productPricingViewModel.CurrentExFactory > productPricingViewModel.CurrentSellingPrice)
                {
                    ModelState.AddModelError("","Exfactory should be less than wholesale price");
                    return View(productPricingViewModel);
                }
                else
                {
                    productPricingViewModel.Id = Guid.NewGuid();
                    _ppViewModelBuilder.Save(productPricingViewModel);
                    _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Create", "Product Pricing", DateTime.Now);
                    TempData["msg"]="Pricing Successfully Created";
                    return RedirectToAction("List");
                }
            }
            catch (DomainValidationException ve)
            {
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                //ViewBag.msg = ve.Message;
                _log.ErrorFormat("Error in creating product pricing"+ve.Message);
                _log.InfoFormat("Error in creating product pricing" + ve.Message);
                return View();
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.msg = ex.Message;
                _log.ErrorFormat("Error in creating product pricing" + ex.Message);
                _log.InfoFormat("Error in creating product pricing" + ex.Message);
                return View();
            }
        }
 public void Save(ProductPricingViewModel productPricingViewModel)
 {
     ProductPricing pp=_productPricingRepository.GetById(productPricingViewModel.Id) ;
     ValidationResultInfo vri = productPricingViewModel.BasicValidation();
     if (pp == null)
     {
         var allPricing = _productPricingRepository.GetAll(true)
             .Where(n => n.ProductRef.ProductId == productPricingViewModel.ProductId && n.Tier.Id == productPricingViewModel.TierId)
             .Select(n => Map(n)).ToList();
         if (allPricing.Count > 0)
         {
             throw new DomainValidationException(vri, "Pricing exists for product:");
         }
         else
         {
             pp = _productPricingFactory.CreateProductPricing
                 (
                   productPricingViewModel.ProductId,
                   productPricingViewModel.TierId,
                   productPricingViewModel.CurrentExFactory,
                   productPricingViewModel.CurrentSellingPrice,
                   productPricingViewModel.CurrentEffectiveDate
                 );
             _productPricingRepository.Save(pp);
            
             //GetProductPricings(productPricingViewModel.ProductId,productPricingViewModel.CurrentExFactory);
         }
     }
     else
     {
         _productPricingRepository.AddProductPricing
             (
              productPricingViewModel.Id,
              productPricingViewModel.CurrentExFactory,
              productPricingViewModel.CurrentSellingPrice,
              productPricingViewModel.CurrentEffectiveDate
             );
     }
 }
        public ActionResult List(bool? showInactive, string searchText,int page = 1)
        {
            try
            {
                var user = (CustomIdentity)this.User.Identity;
                Guid? supplerid = user != null ? user.SupplierId : (Guid?)null; 
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                int pageSize = 10;
                bool showinactive = false;
                if (showInactive != null)
                    showinactive = (bool)showInactive;
                ViewBag.showInactive = showinactive;
                //if (itemsperpage != null)
                //{
                //    ViewModelBase.ItemsPerPage = itemsperpage;
                //}
                if (TempData["msg"] != null)
                {
                    ViewBag.msg = TempData["msg"].ToString();
                } 
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;


                // Format and display the TimeSpan value.
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    ts.Hours,
                    ts.Minutes,
                    ts.Seconds,
                    ts.TotalMilliseconds);


                stopWatch.Reset();
                ViewBag.msg = "";
                _log.InfoFormat("Product Pricing\tTime taken to get all product pricing" + elapsedTime);
                _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Timestamp", "Product Pricing Controller:" + elapsedTime, DateTime.Now);

                int currentPageIndex = page < 0 ? 0 : page - 1;
                int take = DistributorWebHelper.GetItemPerPage();
                int skip = currentPageIndex*take;


                var query = new QueryStandard()
                {
                    ShowInactive = showinactive,
                    Skip = skip,
                    Take = take,
                    Name = searchText,
                    SupplierId = supplerid
                };
                
                ViewBag.searchParam = searchText;
                var ls = _ppViewModelBuilder.Query(query);
                var data = ls.Data;
                
                var count = ls.Count;


                var settings = _settingsRepository.GetByKey(SettingsKeys.NumberOfDecimalPlaces);
                var decimalPlaces = settings != null ? settings.Value : "4";
                ViewBag.DecimalFormat = string.Format("N{0}", decimalPlaces);

                return View(data.ToPagedList(currentPageIndex, take,count));
                
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Error in listing product pricing" + ex.Message);
                _log.InfoFormat("Error in listing product pricing" + ex.Message);
                ViewBag.msg = ex.ToString();
                string exception = ex.Message;
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Listing Product Pricing", ex.ToString());
                }
                catch (Exception exx) { }
                    ProductPricingViewModel productPricingVM = new ProductPricingViewModel();
                productPricingVM.ErrorText = exception;
                return View(productPricingVM);
            }
        
        }
        public ActionResult Edit(ProductPricingViewModel productPricingViewModel)
        {
            try
            {

                _ppViewModelBuilder.Save(productPricingViewModel);
                _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Edit", "Product Pricing", DateTime.Now);
                //TempData["msg"] = "Pricing Successfully Edited";
                return RedirectToAction("List");
            }
            catch (DomainValidationException ve)
            {
                ValidationSummary.DomainValidationErrors(ve, ModelState);
                _log.ErrorFormat("Error in editing product pricing" + ve.Message);
                _log.InfoFormat("Error in editing product pricing" + ve.Message);
                return View();
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                _log.ErrorFormat("Error in editing product pricing" + ex.Message);
                _log.InfoFormat("Error in editing product pricing" + ex.Message);
                return View();
            }
        }
        public ActionResult ListPricingItems(Guid id, int? itemsperpage)
        {
            try
            {
                if (itemsperpage != null)
                {
                    ViewModelBase.ItemsPerPage = itemsperpage.Value;
                }
                EditProductPricingViewModel al = _editProductPricingViewModelBuilder.Get(id);
                return View(al);
            }
            catch (Exception ex)
            {
                ViewBag.msg = ex.ToString();
                string exception = ex.Message;
                try
                {
                    HQMailerViewModelBuilder hqm = new HQMailerViewModelBuilder(ConfigurationSettings.AppSettings["ServerIP"], ConfigurationSettings.AppSettings["UserName"], ConfigurationSettings.AppSettings["Password"]);


                    hqm.Send(ConfigurationSettings.AppSettings["ServerEmail"], ConfigurationSettings.AppSettings["MailGroup"], "Listing Product Pricing", ex.ToString());
                }
                catch { }
                    ProductPricingViewModel productPricingVM = new ProductPricingViewModel();

                productPricingVM.ErrorText = exception;
                return View(productPricingVM);
            }
        }
 public ProductPricingViewModel SearchPricing(string searchParam,bool inactive = false)
 {
     var foundProductId = _productRepository.GetAll().Where(n => n.Description.ToLower().StartsWith(searchParam.ToLower())).Select(n => n.Id).ToArray();
     ProductPricingViewModel productPricingVM = new ProductPricingViewModel
     {
         Items = _productPricingRepository.GetAll(inactive).ToList().Where(n => (n.Tier.Name.ToLower().StartsWith(searchParam.ToLower())) || (foundProductId.Contains(n.ProductRef.ProductId)))
         .Select(n => new ProductPricingViewModel.ProductPricingViewModelItems
         {
             TierId = n.Tier.Id,
             ProductId = n.ProductRef.ProductId == null ? Guid.Empty : n.ProductRef.ProductId,
             ProductName = n.ProductRef.ProductId == null ? "" : _productRepository.GetById(n.ProductRef.ProductId).Description == null ? "" : _productRepository.GetById(n.ProductRef.ProductId).Description,
             Active = n._Status == EntityStatus.Active ? true : false,
             Id = n.Id,
             CurrentEffectiveDate = n.CurrentEffectiveDate,
             CurrentExFactory = n.CurrentExFactory,
             CurrentSellingPrice = n.CurrentSellingPrice,
             ErrorText = "",
             TierName = n.Tier.Name
         }).ToList()
     };
     return productPricingVM;
 }
        //public IList<ProductPricingViewModel> Search(string searchParam, bool inactive = false)
        //{
            
        //    return _productPricingRepository.GetAll(inactive).ToList().Where(n=>(n.Tier.Name.ToLower().StartsWith(searchParam.ToLower()))).Select(s => Map(s)).ToList();//.Where(n =>n. (n.ProductName.ToLower().StartsWith(searchParam.ToLower())) || (n.TierName.ToLower().StartsWith(searchParam.ToLower())) || (n.CurrentExFactory.ToString().StartsWith(searchParam.ToLower())) || (n.CurrentSellingPrice.ToString().StartsWith(searchParam)) || (n.CurrentEffectiveDate.ToString("dd-MMM-yyyy").StartsWith(searchParam))).Select(s => Map(s)).ToList();
        //}


        public ProductPricingViewModel GetPricingSkipTake(bool inactive = false)
        {
            ProductPricingViewModel productPricingVM = new ProductPricingViewModel
            {
                Items = _productPricingRepository.GetAll(inactive)
                .Select(n => new ProductPricingViewModel.ProductPricingViewModelItems
            {
                TierId = n.Tier.Id,
                ProductId = n.ProductRef.ProductId == null ? Guid.Empty: n.ProductRef.ProductId,
                ProductName = n.ProductRef.ProductId == null ? "" : _productRepository.GetById(n.ProductRef.ProductId).Description == null ? "" : _productRepository.GetById(n.ProductRef.ProductId).Description,
                Active = n._Status == EntityStatus.Active ? true : false,
                Id=n.Id,
                 CurrentEffectiveDate=n.CurrentEffectiveDate,
                  CurrentExFactory=n.CurrentExFactory,
                   CurrentSellingPrice=n.CurrentSellingPrice,
                    ErrorText="",
                     TierName=n.Tier.Name
            }).ToList()
            };
            return productPricingVM;
        }