Exemplo n.º 1
0
        public async Task <IActionResult> ProductUpdate(ProductOverviewModel model)
        {
            var product = await _db.Products.FindByIdAsync(model.Id);

            product.Name                      = model.Name;
            product.Sku                       = model.Sku;
            product.Price                     = model.Price;
            product.StockQuantity             = model.StockQuantity;
            product.Published                 = model.Published;
            product.ManufacturerPartNumber    = model.ManufacturerPartNumber;
            product.Gtin                      = model.Gtin;
            product.MinStockQuantity          = model.MinStockQuantity;
            product.OldPrice                  = model.OldPrice;
            product.AvailableStartDateTimeUtc = model.AvailableStartDateTimeUtc;
            product.AvailableEndDateTimeUtc   = model.AvailableEndDateTimeUtc;

            try
            {
                await _db.SaveChangesAsync();

                return(Json(new { success = true }));
            }
            catch (Exception ex)
            {
                NotifyError(ex.GetInnerMessage());
                return(Json(new { success = false }));
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> ProductInsert(ProductOverviewModel model)
        {
            var product = new Product
            {
                Name                      = model.Name,
                Sku                       = model.Sku,
                Price                     = model.Price,
                StockQuantity             = model.StockQuantity,
                Published                 = model.Published,
                ManufacturerPartNumber    = model.ManufacturerPartNumber,
                Gtin                      = model.Gtin,
                MinStockQuantity          = model.MinStockQuantity,
                OldPrice                  = model.OldPrice,
                AvailableStartDateTimeUtc = model.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = model.AvailableEndDateTimeUtc
            };

            try
            {
                _db.Products.Add(product);
                await _db.SaveChangesAsync();

                return(Json(new { success = true }));
            }
            catch (Exception ex)
            {
                NotifyError(ex.GetInnerMessage());
                return(Json(new { success = false }));
            }
        }
Exemplo n.º 3
0
        private IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(IEnumerable <Product> products)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var modes = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = product.Name,
                    FullDescription  = product.FullDescription,
                    ShortDescription = product.ShortDescription,
                    ProductPrice     = new ProductOverviewModel.ProductPriceModel
                    {
                        Price = product.Price
                    }
                };

                modes.Add(model);
            }
            return(modes);
        }
Exemplo n.º 4
0
 public static void PrepareContentUnitMeasure(this ProductOverviewModel model)
 {
     if (model.ContentUnitPriceMultiplicator > 0 && model.ContentUnitMeasureID > 0)
     {
         var contentUnitMeasure = RP.GetContentUnitMeasureById(model.ContentUnitMeasureID);
         model.ContentUnitName  = contentUnitMeasure.DisplayName;
         model.ContentUnitPrice = Math.Truncate(model.Price * model.ContentUnitPriceMultiplicator * 100) / 100;
     }
 }
Exemplo n.º 5
0
 public static int CalculateMaxQuantity(this ProductOverviewModel product, int stock, int?maximumAllowedPurchaseQuantity)
 {
     return(CalculateMaxQuantity(
                product.IsPharmaceutical,
                product.Discontinued,
                product.BrandEnforcedStockCount,
                product.ProductEnforcedStockCount,
                stock,
                maximumAllowedPurchaseQuantity));
 }
        /// <inheritdoc />
        /// <summary>
        /// Custom code is to always prepareSpecificationAttributes regardless of param. Would be better to instead override
        /// CatalogController.cs' line:
        /// var models =  _productModelFactory.PrepareProductOverviewModels(products, false, _catalogSettings.ShowProductImagesInSearchAutoComplete, _mediaSettings.AutoCompleteSearchThumbPictureSize).ToList();
        /// to:
        /// var models =  _productModelFactory.PrepareProductOverviewModels(products, false, _catalogSettings.ShowProductImagesInSearchAutoComplete, _mediaSettings.AutoCompleteSearchThumbPictureSize
        /// , prepareSpecificationAttributes: true).ToList();
        /// </summary>
        /// <param name="products">Collection of products</param>
        /// <param name="preparePriceModel">Whether to prepare the price model</param>
        /// <param name="preparePictureModel">Whether to prepare the picture model</param>
        /// <param name="productThumbPictureSize">Product thumb picture size (longest side); pass null to use the default value of media settings</param>
        /// <param name="prepareSpecificationAttributes">Whether to prepare the specification attribute models</param>
        /// <param name="forceRedirectionAfterAddingToCart">Whether to force redirection after adding to cart</param>
        /// <returns>Collection of product overview model</returns>
        public override IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(IEnumerable <Product> products,
                                                                                        bool preparePriceModel                 = true, bool preparePictureModel = true,
                                                                                        int?productThumbPictureSize            = null, bool prepareSpecificationAttributes = false,
                                                                                        bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
            {
                throw new ArgumentNullException(nameof(products));
            }

            prepareSpecificationAttributes = true; // THIS IS THE CUSTOM CODE LINE, REST OF FUNCTION IS UNMODIFIED

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = _localizationService.GetLocalized(product, x => x.Name),
                    ShortDescription = _localizationService.GetLocalized(product, x => x.ShortDescription),
                    FullDescription  = _localizationService.GetLocalized(product, x => x.FullDescription),
                    SeName           = _urlRecordService.GetSeName(product),
                    Sku              = product.Sku,
                    ProductType      = product.ProductType,
                    MarkAsNew        = product.MarkAsNew &&
                                       (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) &&
                                       (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow)
                };

                //price
                if (preparePriceModel)
                {
                    model.ProductPrice = PrepareProductOverviewPriceModel(product, forceRedirectionAfterAddingToCart);
                }

                //picture
                if (preparePictureModel)
                {
                    model.DefaultPictureModel = PrepareProductOverviewPictureModel(product, productThumbPictureSize);
                }

                //specs
                if (prepareSpecificationAttributes)
                {
                    model.SpecificationAttributeModels = PrepareProductSpecificationModel(product);
                }

                //reviews
                model.ReviewOverviewModel = PrepareProductReviewOverviewModel(product);

                models.Add(model);
            }
            return(models);
        }
        protected IEnumerable <ProductOverviewModel> PrepareNewProducsModels(IEnumerable <Product> products,
                                                                             bool preparePictureModel = true, int?productThumbPictureSize = null)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            //performance optimization. let's load all variants at one go
            //var allVariants = _productService.GetProductVariantsByProductIds(products.Select(x => x.Id).ToArray());


            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel()
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                };


                //picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : _mediaSettings.ProductThumbPictureSize;
                    //prepare picture model

                    var picture = _pictureService.GetPicturesByProductId(product.Id);
                    model.DefaultPictureModel = new PictureModel()
                    {
                        ImageUrl         = _pictureService.GetPictureUrl(picture[0], pictureSize),
                        FullSizeImageUrl = _pictureService.GetPictureUrl(picture[0]),
                        Title            = string.Format(_localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name),
                        AlternateText    = string.Format(_localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name)
                    };


                    #endregion
                }

                models.Add(model);
            }
            return(models);
        }
Exemplo n.º 8
0
        protected AddProductReviewModel PrepareAddProductReviewModel(ProductOverviewModel product)
        {
            var model = new AddProductReviewModel
            {
                Name   = string.IsNullOrWhiteSpace(product.H1Title) ? product.Name : product.H1Title,
                UrlKey = product.UrlKey
            };

            model.ProductBox        = product.PrepareProductBoxModel();
            model.ProductBreadcrumb = PrepareProductBreadcrumbModel(product.Id);

            return(model);
        }
        protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ProductOverviewModel product = e.Row.DataItem as ProductOverviewModel;
                CheckBox             cb      = e.Row.FindControl("cbChosen") as CheckBox;

                if (ChosenProducts.Contains(product.Id))
                {
                    cb.Checked = true;
                }
            }
        }
Exemplo n.º 10
0
        protected AddToCartModel PrepareAddToCartModel(ProductOverviewModel product, ProductPrice productPrice, CartItemOverviewModel cartItem = null)
        {
            var model = new AddToCartModel();

            model.ProductId            = product.Id;
            model.AvailableForPreOrder = product.ShowPreOrderButton;

            if (product.Enabled == false)
            {
                return(model);
            }
            if (productPrice == null)
            {
                return(model);
            }
            if (productPrice.PriceExclTax <= 0M)
            {
                return(model);
            }
            if (productPrice.Enabled == false)
            {
                return(model);
            }
            if ((product.ProductEnforcedStockCount || product.BrandEnforcedStockCount) && productPrice.Stock <= 0)
            {
                return(model);
            }

            var maxQuantity = product.CalculateMaxQuantity(productPrice.Stock, productPrice.MaximumAllowedPurchaseQuantity);

            //allowed quantities
            if (maxQuantity > 0)
            {
                model.Visible = true;

                var increment = product.StepQuantity <= 0 ? 1 : product.StepQuantity;

                for (int i = product.StepQuantity; i <= maxQuantity; i = i + increment)
                {
                    model.AllowedQuantities.Add(new SelectListItem
                    {
                        Text  = i.ToString(),
                        Value = i.ToString()
                    });
                }
            }

            return(model);
        }
Exemplo n.º 11
0
        public ActionResult Product(string productType)
        {
            ProductOverviewModel model = new ProductOverviewModel();

            model.ProductType = productType;
            List <Product> products;

            if (string.IsNullOrEmpty(productType))
            {
                products = this._productService.GetProducts().Where(m => m.ProductType != "ContactLense").ToList();
            }
            else
            {
                products = this._productService.GetProducts().Where(m => m.ProductType == productType).ToList();
            }
            if (products != null)
            {
                model.Products = TransformProductToProductModel(products);
            }
            return(View(model));
        }
        public virtual IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(IEnumerable <Product> products,
                                                                                       bool preparePictureModel    = true,
                                                                                       int?productThumbPictureSize = null)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                    Sku              = product.Sku,
                    ProductType      = product.ProductType,
                    MarkAsNew        = product.MarkAsNew &&
                                       (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) &&
                                       (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow)
                };

                //picture
                if (preparePictureModel)
                {
                    model.DefaultPictureModel = PrepareProductOverviewPictureModel(product, productThumbPictureSize);
                }

                //reviews
                model.ReviewOverviewModel = PrepareProductReviewOverviewModel(product);

                models.Add(model);
            }
            return(models);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> ProductUpdate(ProductOverviewModel model)
        {
            var product = await _db.Products.FindByIdAsync(model.Id);

            product.Name          = model.Name;
            product.Sku           = model.Sku;
            product.Price         = model.Price;
            product.StockQuantity = model.StockQuantity;
            product.Published     = model.Published;

            try
            {
                await _db.SaveChangesAsync();

                return(Json(new { success = true }));
            }
            catch (Exception ex)
            {
                NotifyError(ex.GetInnerMessage());
                return(Json(new { success = false }));
            }
        }
Exemplo n.º 14
0
        public static ProductOverviewModel ToProductOverviewModel(this Product product)
        {
            var productService = EngineContext.Current.Resolve <IProductService>();
            var productModel   = new ProductOverviewModel();
            var pr             = productService.GetProductById(product.nopid);

            if (pr == null)
            {
                return(null);
            }
            productModel.Id               = product.nopid;
            productModel.Name             = pr.Name;
            productModel.ShortDescription = product.pagetext;
            productModel.CustomProperties.Add("page_number", product.page_number);
            productModel.CustomProperties.Add("link_to_documnet", GetLinkToDocumnet(product.page_number, product.nopid));
            productModel.SeName = pr.GetSeName();

            productModel.DefaultPictureModel          = PrepareProductOverviewPictureModel(product.nopid);
            productModel.SpecificationAttributeModels = PrepareProductSpecificationModel(product.nopid);
            /*Prepare specifications*/
            /*Prepare image for product*/

            return(productModel);
        }
Exemplo n.º 15
0
        public static IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(this Controller controller,
                                                                                      IWorkContext workContext,
                                                                                      IStoreContext storeContext,
                                                                                      ICategoryService categoryService,
                                                                                      IProductService productService,
                                                                                      ISpecificationAttributeService specificationAttributeService,
                                                                                      IPriceCalculationService priceCalculationService,
                                                                                      IPriceFormatter priceFormatter,
                                                                                      IPermissionService permissionService,
                                                                                      ILocalizationService localizationService,
                                                                                      ITaxService taxService,
                                                                                      ICurrencyService currencyService,
                                                                                      IPictureService pictureService,
                                                                                      IWebHelper webHelper,
                                                                                      ICacheManager cacheManager,
                                                                                      CatalogSettings catalogSettings,
                                                                                      MediaSettings mediaSettings,
                                                                                      IEnumerable <Product> products,
                                                                                      bool preparePriceModel                 = true, bool preparePictureModel = true,
                                                                                      int?productThumbPictureSize            = null, bool prepareSpecificationAttributes = false,
                                                                                      bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                    ProductType      = product.ProductType,
                    MarkAsNew        = product.MarkAsNew &&
                                       (!product.MarkAsNewStartDateTimeUtc.HasValue || product.MarkAsNewStartDateTimeUtc.Value < DateTime.UtcNow) &&
                                       (!product.MarkAsNewEndDateTimeUtc.HasValue || product.MarkAsNewEndDateTimeUtc.Value > DateTime.UtcNow)
                };
                //price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel
                    {
                        ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart
                    };

                    switch (product.ProductType)
                    {
                    case ProductType.GroupedProduct:
                    {
                        #region Grouped product

                        var associatedProducts = productService.GetAssociatedProducts(product.Id, storeContext.CurrentStore.Id);

                        //add to cart button (ignore "DisableBuyButton" property for grouped products)
                        priceModel.DisableBuyButton = !permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button (ignore "DisableWishlistButton" property for grouped products)
                        priceModel.DisableWishlistButton = !permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //compare products
                        priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;
                        switch (associatedProducts.Count)
                        {
                        case 0:
                        {
                            //no associated products
                        }
                        break;

                        default:
                        {
                            //we have at least one associated product
                            //compare products
                            priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;
                            //priceModel.AvailableForPreOrder = false;

                            if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                            {
                                //find a minimum possible price
                                decimal?minPossiblePrice = null;
                                Product minPriceProduct  = null;
                                foreach (var associatedProduct in associatedProducts)
                                {
                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    var tmpPrice = priceCalculationService.GetFinalPrice(associatedProduct,
                                                                                         workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                                    if (!minPossiblePrice.HasValue || tmpPrice < minPossiblePrice.Value)
                                    {
                                        minPriceProduct  = associatedProduct;
                                        minPossiblePrice = tmpPrice;
                                    }
                                }
                                if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice)
                                {
                                    if (minPriceProduct.CallForPrice)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = localizationService.GetResource("Products.CallForPrice");
                                    }
                                    else if (minPossiblePrice.HasValue)
                                    {
                                        //calculate prices
                                        decimal taxRate;
                                        decimal finalPriceBase = taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate);
                                        decimal finalPrice     = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency);

                                        priceModel.OldPrice   = null;
                                        priceModel.Price      = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice));
                                        priceModel.PriceValue = finalPrice;
                                    }
                                    else
                                    {
                                        //Actually it's not possible (we presume that minimalPrice always has a value)
                                        //We never should get here
                                        Debug.WriteLine("Cannot calculate minPrice for product #{0}", product.Id);
                                    }
                                }
                            }
                            else
                            {
                                //hide prices
                                priceModel.OldPrice = null;
                                priceModel.Price    = null;
                            }
                        }
                        break;
                        }

                        #endregion
                    }
                    break;

                    case ProductType.SimpleProduct:
                    default:
                    {
                        #region Simple product

                        //add to cart button
                        priceModel.DisableBuyButton = product.DisableBuyButton ||
                                                      !permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button
                        priceModel.DisableWishlistButton = product.DisableWishlistButton ||
                                                           !permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !permissionService.Authorize(StandardPermissionProvider.DisplayPrices);
                        //compare products
                        priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;

                        //rental
                        priceModel.IsRental = product.IsRental;

                        //pre-order
                        if (product.AvailableForPreOrder)
                        {
                            priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
                                                              product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow;
                            priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
                        }

                        //prices
                        if (permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            if (!product.CustomerEntersPrice)
                            {
                                if (product.CallForPrice)
                                {
                                    //call for price
                                    priceModel.OldPrice = null;
                                    priceModel.Price    = localizationService.GetResource("Products.CallForPrice");
                                }
                                else
                                {
                                    //prices

                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    decimal minPossiblePrice = priceCalculationService.GetFinalPrice(product,
                                                                                                     workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);

                                    decimal taxRate;
                                    decimal oldPriceBase   = taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                    decimal finalPriceBase = taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                                    decimal oldPrice   = currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, workContext.WorkingCurrency);
                                    decimal finalPrice = currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, workContext.WorkingCurrency);

                                    //do we have tier prices configured?
                                    var tierPrices = new List <TierPrice>();
                                    if (product.HasTierPrices)
                                    {
                                        tierPrices.AddRange(product.TierPrices
                                                            .OrderBy(tp => tp.Quantity)
                                                            .ToList()
                                                            .FilterByStore(storeContext.CurrentStore.Id)
                                                            .FilterForCustomer(workContext.CurrentCustomer)
                                                            .RemoveDuplicatedQuantities());
                                    }
                                    //When there is just one tier (with  qty 1),
                                    //there are no actual savings in the list.
                                    bool displayFromMessage = tierPrices.Count > 0 &&
                                                              !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1);
                                    if (displayFromMessage)
                                    {
                                        priceModel.OldPrice   = null;
                                        priceModel.Price      = String.Format(localizationService.GetResource("Products.PriceRangeFrom"), priceFormatter.FormatPrice(finalPrice));
                                        priceModel.PriceValue = finalPrice;
                                    }
                                    else
                                    {
                                        if (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero)
                                        {
                                            priceModel.OldPrice   = priceFormatter.FormatPrice(oldPrice);
                                            priceModel.Price      = priceFormatter.FormatPrice(finalPrice);
                                            priceModel.PriceValue = finalPrice;
                                        }
                                        else
                                        {
                                            priceModel.OldPrice   = null;
                                            priceModel.Price      = priceFormatter.FormatPrice(finalPrice);
                                            priceModel.PriceValue = finalPrice;
                                        }
                                    }
                                    if (product.IsRental)
                                    {
                                        //rental product
                                        priceModel.OldPrice = priceFormatter.FormatRentalProductPeriod(product, priceModel.OldPrice);
                                        priceModel.Price    = priceFormatter.FormatRentalProductPeriod(product, priceModel.Price);
                                    }


                                    //property for German market
                                    //we display tax/shipping info only with "shipping enabled" for this product
                                    //we also ensure this it's not free shipping
                                    priceModel.DisplayTaxShippingInfo = catalogSettings.DisplayTaxShippingInfoProductBoxes &&
                                                                        product.IsShipEnabled &&
                                                                        !product.IsFreeShipping;
                                }
                            }
                        }
                        else
                        {
                            //hide prices
                            priceModel.OldPrice = null;
                            priceModel.Price    = null;
                        }

                        #endregion
                    }
                    break;
                    }

                    model.ProductPrice = priceModel;

                    #endregion
                }

                //picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : mediaSettings.ProductThumbPictureSize;
                    //prepare picture model
                    var defaultProductPictureCacheKey = string.Format(ModelCacheEventConsumer.PRODUCT_DEFAULTPICTURE_MODEL_KEY, product.Id, pictureSize, true, workContext.WorkingLanguage.Id, webHelper.IsCurrentConnectionSecured(), storeContext.CurrentStore.Id);
                    model.DefaultPictureModel = cacheManager.Get(defaultProductPictureCacheKey, () =>
                    {
                        var picture      = pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault();
                        var pictureModel = new PictureModel
                        {
                            ImageUrl         = pictureService.GetPictureUrl(picture, pictureSize),
                            FullSizeImageUrl = pictureService.GetPictureUrl(picture)
                        };
                        //"title" attribute
                        pictureModel.Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute)) ?
                                             picture.TitleAttribute :
                                             string.Format(localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name);
                        //"alt" attribute
                        pictureModel.AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute)) ?
                                                     picture.AltAttribute :
                                                     string.Format(localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name);

                        return(pictureModel);
                    });

                    #endregion
                }

                //specs
                if (prepareSpecificationAttributes)
                {
                    model.SpecificationAttributeModels = PrepareProductSpecificationModel(controller, workContext,
                                                                                          specificationAttributeService, cacheManager, product);
                }

                //reviews
                model.ReviewOverviewModel = controller.PrepareProductReviewOverviewModel(storeContext, catalogSettings, cacheManager, product);

                models.Add(model);
            }
            return(models);
        }
Exemplo n.º 16
0
        protected IEnumerable <ProductOverviewModel> PrepareProductOverviewModels(IEnumerable <Product> products,
                                                                                  bool preparePriceModel                 = true, bool preparePictureModel = true,
                                                                                  int?productThumbPictureSize            = null, bool prepareSpecificationAttributes = false,
                                                                                  bool forceRedirectionAfterAddingToCart = false)
        {
            if (products == null)
            {
                throw new ArgumentNullException("products");
            }

            var models = new List <ProductOverviewModel>();

            foreach (var product in products)
            {
                var model = new ProductOverviewModel()
                {
                    Id               = product.Id,
                    Name             = product.GetLocalized(x => x.Name),
                    ShortDescription = product.GetLocalized(x => x.ShortDescription),
                    FullDescription  = product.GetLocalized(x => x.FullDescription),
                    SeName           = product.GetSeName(),
                };
                //price
                if (preparePriceModel)
                {
                    #region Prepare product price

                    var priceModel = new ProductOverviewModel.ProductPriceModel();

                    switch (product.ProductType)
                    {
                    case ProductType.GroupedProduct:
                    {
                        #region Grouped product

                        var associatedProducts = _productService.GetAssociatedProducts(product.Id, _storeContext.CurrentStore.Id);

                        switch (associatedProducts.Count)
                        {
                        case 0:
                        {
                            //no associated products
                            priceModel.OldPrice              = null;
                            priceModel.Price                 = null;
                            priceModel.DisableBuyButton      = true;
                            priceModel.DisableWishlistButton = true;
                            priceModel.AvailableForPreOrder  = false;
                        }
                        break;

                        default:
                        {
                            //we have at least one associated product
                            priceModel.DisableBuyButton      = true;
                            priceModel.DisableWishlistButton = true;
                            priceModel.AvailableForPreOrder  = false;

                            if (_permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                            {
                                //find a minimum possible price
                                decimal?minPossiblePrice = null;
                                Product minPriceProduct  = null;
                                foreach (var associatedProduct in associatedProducts)
                                {
                                    //calculate for the maximum quantity (in case if we have tier prices)
                                    var tmpPrice = _priceCalculationService.GetFinalPrice(associatedProduct,
                                                                                          _workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                                    if (!minPossiblePrice.HasValue || tmpPrice < minPossiblePrice.Value)
                                    {
                                        minPriceProduct  = associatedProduct;
                                        minPossiblePrice = tmpPrice;
                                    }
                                }
                                if (minPriceProduct != null && !minPriceProduct.CustomerEntersPrice)
                                {
                                    if (minPriceProduct.CallForPrice)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = _localizationService.GetResource("Products.CallForPrice");
                                    }
                                    else if (minPossiblePrice.HasValue)
                                    {
                                        //calculate prices
                                        decimal taxRate        = decimal.Zero;
                                        decimal finalPriceBase = _taxService.GetProductPrice(minPriceProduct, minPossiblePrice.Value, out taxRate);
                                        decimal finalPrice     = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _workContext.WorkingCurrency);

                                        priceModel.OldPrice = null;
                                        priceModel.Price    = String.Format(_localizationService.GetResource("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                    }
                                    else
                                    {
                                        //Actually it's not possible (we presume that minimalPrice always has a value)
                                        //We never should get here
                                        Debug.WriteLine(string.Format("Cannot calculate minPrice for product #{0}", product.Id));
                                    }
                                }
                            }
                            else
                            {
                                //hide prices
                                priceModel.OldPrice = null;
                                priceModel.Price    = null;
                            }
                        }
                        break;
                        }

                        #endregion
                    }
                    break;

                    case ProductType.SimpleProduct:
                    default:
                    {
                        #region Simple product

                        //add to cart button
                        priceModel.DisableBuyButton = product.DisableBuyButton ||
                                                      !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart) ||
                                                      !_permissionService.Authorize(StandardPermissionProvider.DisplayPrices);

                        //add to wishlist button
                        priceModel.DisableWishlistButton = product.DisableWishlistButton ||
                                                           !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist) ||
                                                           !_permissionService.Authorize(StandardPermissionProvider.DisplayPrices);
                        //pre-order
                        if (product.AvailableForPreOrder)
                        {
                            priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
                                                              product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow;
                            priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
                        }

                        //prices
                        if (_permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            //calculate for the maximum quantity (in case if we have tier prices)
                            decimal minPossiblePrice = _priceCalculationService.GetFinalPrice(product,
                                                                                              _workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                            if (!product.CustomerEntersPrice)
                            {
                                if (product.CallForPrice)
                                {
                                    //call for price
                                    priceModel.OldPrice = null;
                                    priceModel.Price    = _localizationService.GetResource("Products.CallForPrice");
                                }
                                else
                                {
                                    //calculate prices
                                    decimal taxRate        = decimal.Zero;
                                    decimal oldPriceBase   = _taxService.GetProductPrice(product, product.OldPrice, out taxRate);
                                    decimal finalPriceBase = _taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                                    decimal oldPrice   = _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase, _workContext.WorkingCurrency);
                                    decimal finalPrice = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, _workContext.WorkingCurrency);

                                    //do we have tier prices configured?
                                    var tierPrices = new List <TierPrice>();
                                    if (product.HasTierPrices)
                                    {
                                        tierPrices.AddRange(product.TierPrices
                                                            .OrderBy(tp => tp.Quantity)
                                                            .ToList()
                                                            .FilterByStore(_storeContext.CurrentStore.Id)
                                                            .FilterForCustomer(_workContext.CurrentCustomer)
                                                            .RemoveDuplicatedQuantities());
                                    }
                                    //When there is just one tier (with  qty 1),
                                    //there are no actual savings in the list.
                                    bool displayFromMessage = tierPrices.Count > 0 &&
                                                              !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1);
                                    if (displayFromMessage)
                                    {
                                        priceModel.OldPrice = null;
                                        priceModel.Price    = String.Format(_localizationService.GetResource("Products.PriceRangeFrom"), _priceFormatter.FormatPrice(finalPrice));
                                    }
                                    else
                                    {
                                        if (finalPriceBase != oldPriceBase && oldPriceBase != decimal.Zero)
                                        {
                                            priceModel.OldPrice = _priceFormatter.FormatPrice(oldPrice);
                                            priceModel.Price    = _priceFormatter.FormatPrice(finalPrice);
                                        }
                                        else
                                        {
                                            priceModel.OldPrice = null;
                                            priceModel.Price    = _priceFormatter.FormatPrice(finalPrice);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //hide prices
                            priceModel.OldPrice = null;
                            priceModel.Price    = null;
                        }

                        #endregion
                    }
                    break;
                    }

                    model.ProductPrice = priceModel;

                    #endregion
                }

                //picture
                if (preparePictureModel)
                {
                    #region Prepare product picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = productThumbPictureSize.HasValue ? productThumbPictureSize.Value : 125;
                    //prepare picture model
                    var picture = _pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault();
                    model.DefaultPictureModel = new PictureModel()
                    {
                        ImageUrl         = _pictureService.GetPictureUrl(picture, pictureSize),
                        FullSizeImageUrl = _pictureService.GetPictureUrl(picture),
                        Title            = string.Format(_localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name),
                        AlternateText    = string.Format(_localizationService.GetResource("Media.Product.ImageAlternateTextFormat"), model.Name)
                    };
                    #endregion
                }

                models.Add(model);
            }
            return(models);
        }
Exemplo n.º 17
0
        protected ProductDetailsModel PrepareProductDetailsModel(ProductOverviewModel product, int?selectedPriceId = null)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            #region Standard properties

            var model = new ProductDetailsModel
            {
                Id                  = product.Id,
                Name                = string.IsNullOrWhiteSpace(product.H1Title) ? product.Name : product.H1Title,
                ShortDescription    = product.ShortDescription,
                FullDescription     = product.FullDescription,
                DeliveryTimeLine    = product.DeliveryTimeLine,
                OptionType          = product.OptionType,
                AverageReviewRating = product.AverageReviewRating,
                IsPhoneOrder        = product.IsPhoneOrder,
                PhoneOrderMessage   = product.IsPhoneOrder ? _catalogSettings.PhoneOrderMessage : string.Empty,
                UrlKey              = product.UrlKey,
                Enabled             = product.Enabled,
                Discontinued        = product.Discontinued,
                MetaDescription     = product.MetaDescription,
                MetaKeywords        = product.MetaKeywords,
                MetaTitle           = product.MetaTitle
            };

            #endregion

            #region Brand

            var brand = _brandService.GetBrandById(product.BrandId);
            if (brand != null)
            {
                PictureModel brandPicture = null;
                if (string.IsNullOrEmpty(brand.FlashImage) == false)
                {
                    brandPicture = new PictureModel
                    {
                        AlternateText = brand.Name,
                        Title         = brand.Name,
                        ImageUrl      = "/media/brand/" + brand.FlashImage
                    };
                }
                var productBrandModel = new ProductBrandModel();
                productBrandModel.Picture  = brandPicture;
                productBrandModel.Name     = brand.Name;
                productBrandModel.BrandUrl = Url.RouteUrl("Brand", new { urlKey = brand.UrlRewrite }, Request.Url.Scheme);
                productBrandModel.Visible  = true;

                model.ProductBrand = productBrandModel;
            }

            #endregion

            #region Pictures

            var medias              = product.Images;
            var defaultPicture      = medias.Where(x => x.Enabled == true).FirstOrDefault();
            var defaultPictureModel = new PictureModel();
            if (defaultPicture != null)
            {
                defaultPictureModel = new PictureModel
                {
                    Title            = product.Name,
                    AlternateText    = product.Name,
                    ImageUrl         = string.Format("/media/product/{0}", defaultPicture.ThumbnailFilename),
                    FullSizeImageUrl = string.Format("/media/product/{0}", string.IsNullOrEmpty(defaultPicture.HighResFilename) ? defaultPicture.MediaFilename : defaultPicture.HighResFilename)
                };
            }

            var pictureModels = new List <PictureModel>();
            foreach (var picture in medias)
            {
                if (picture.Enabled)
                {
                    pictureModels.Add(new PictureModel
                    {
                        Id               = picture.Id,
                        Title            = product.Name,
                        AlternateText    = product.Name,
                        ImageUrl         = string.Format("/media/product/{0}", picture.ThumbnailFilename),
                        FullSizeImageUrl = string.Format("/media/product/{0}", string.IsNullOrEmpty(picture.HighResFilename) ? picture.MediaFilename : picture.HighResFilename)
                    });
                }
            }

            model.DefaultPicture = defaultPictureModel;
            model.PictureModels  = pictureModels;

            #endregion

            #region Product prices

            var productPrices = _productService.GetProductPricesByProductId(product.Id);
            productPrices = productPrices.OrderBy(pp => pp.Priority).ToList();

            var defaultProductPrice = productPrices.Where(x => x.Stock > 0).FirstOrDefault();
            if (defaultProductPrice == null)
            {
                defaultProductPrice = productPrices.Where(x => x.Enabled == true).FirstOrDefault();
            }

            if (selectedPriceId.HasValue)
            {
                var found = productPrices.Where(x => x.Id == selectedPriceId.Value).FirstOrDefault();
                if (found != null)
                {
                    defaultProductPrice = found;
                }
            }

            var defaultProductPriceModel = new ProductPriceModel();
            if (defaultProductPrice != null)
            {
                defaultProductPriceModel = defaultProductPrice.PrepareProductPriceModel(
                    product.OptionType,
                    product.Discontinued,
                    product.ProductEnforcedStockCount,
                    product.BrandEnforcedStockCount,
                    isPreSelected: true);
            }
            model.DefaultProductPrice = defaultProductPriceModel;

            foreach (var item in productPrices)
            {
                var price = item.PrepareProductPriceModel(
                    product.OptionType,
                    product.Discontinued,
                    product.ProductEnforcedStockCount,
                    product.BrandEnforcedStockCount,
                    isPreSelected: item.Id == defaultProductPriceModel.Id);

                model.ProductPrices.Add(price);
            }

            #endregion

            #region Add to cart

            model.AddToCart = PrepareAddToCartModel(product, defaultProductPrice);

            #endregion

            #region Product offer

            if (defaultProductPrice != null && (defaultProductPrice.OfferRuleId > 0))
            {
                var offerRule = _offerService.GetOfferRuleById(defaultProductPrice.OfferRuleId);
                if (offerRule != null &&
                    offerRule.ShowCountDown &&
                    offerRule.EndDate != null &&
                    offerRule.EndDate.Value != DateTime.MinValue &&
                    offerRule.EndDate.Value.CompareTo(DateTime.Now) >= 0)
                {
                    model.ProductOffer = new ProductOfferModel
                    {
                        ExpiryDate = offerRule.EndDate.Value,
                        Visible    = true
                    };
                }
            }

            #endregion

            #region Product tags

            var productTags = _productService.GetProductTagsByProductId(product.Id);

            if (productTags != null)
            {
                foreach (var productTag in productTags)
                {
                    model.ProductTags.Add(new ProductTagModel
                    {
                        Id          = productTag.TagId,
                        Tag         = productTag.Tag.Name,
                        Description = productTag.Value
                    });
                }
            }

            #endregion

            #region Product reviews

            var reviews = _productService.GetApprovedProductReviewsByProductId(product.Id);

            if (reviews != null)
            {
                foreach (var review in reviews)
                {
                    model.Reviews.Add(new ProductReviewModel
                    {
                        Title     = review.Title,
                        Comment   = review.Comment,
                        Score     = review.Score,
                        Alias     = review.Alias,
                        TimeStamp = review.TimeStamp
                    });
                }
            }

            #endregion

            #region Breadcrumb

            model.ProductBreadcrumb = PrepareProductBreadcrumbModel(product.Id);

            #endregion

            return(model);
        }
Exemplo n.º 18
0
        public async Task <IActionResult> ProductList(GridCommand command, ProductListModel model)
        {
            var gridModel = new GridModel <ProductOverviewModel>();

            var fields = new List <string> {
                "name"
            };

            if (_searchSettings.SearchFields.Contains("sku"))
            {
                fields.Add("sku");
            }

            if (_searchSettings.SearchFields.Contains("shortdescription"))
            {
                fields.Add("shortdescription");
            }

            var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchProductName)
                              .HasStoreId(model.SearchStoreId)
                              .WithCurrency(_workContext.WorkingCurrency)
                              .WithLanguage(_workContext.WorkingLanguage);

            if (model.SearchIsPublished.HasValue)
            {
                searchQuery = searchQuery.PublishedOnly(model.SearchIsPublished.Value);
            }

            if (model.SearchHomePageProducts.HasValue)
            {
                searchQuery = searchQuery.HomePageProductsOnly(model.SearchHomePageProducts.Value);
            }

            if (model.SearchProductTypeId > 0)
            {
                searchQuery = searchQuery.IsProductType((ProductType)model.SearchProductTypeId);
            }

            if (model.SearchWithoutManufacturers.HasValue)
            {
                searchQuery = searchQuery.HasAnyManufacturer(!model.SearchWithoutManufacturers.Value);
            }
            else if (model.SearchManufacturerId != 0)
            {
                searchQuery = searchQuery.WithManufacturerIds(null, model.SearchManufacturerId);
            }


            if (model.SearchWithoutCategories.HasValue)
            {
                searchQuery = searchQuery.HasAnyCategory(!model.SearchWithoutCategories.Value);
            }
            else if (model.SearchCategoryId != 0)
            {
                searchQuery = searchQuery.WithCategoryIds(null, model.SearchCategoryId);
            }

            IPagedList <Product> products;

            if (_searchSettings.UseCatalogSearchInBackend)
            {
                searchQuery = searchQuery.Slice((command.Page - 1) * command.PageSize, command.PageSize);

                var sort = command.Sorting?.FirstOrDefault();
                if (sort != null)
                {
                    switch (sort.Member)
                    {
                    case nameof(ProductModel.Name):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.NameDesc : ProductSortingEnum.NameAsc);
                        break;

                    case nameof(ProductModel.Price):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.PriceDesc : ProductSortingEnum.PriceAsc);
                        break;

                    case nameof(ProductModel.CreatedOn):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.CreatedOn : ProductSortingEnum.CreatedOnAsc);
                        break;
                    }
                }

                if (!searchQuery.Sorting.Any())
                {
                    searchQuery = searchQuery.SortBy(ProductSortingEnum.NameAsc);
                }

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                products = await searchResult.GetHitsAsync();
            }
            else
            {
                var query = _catalogSearchService
                            .PrepareQuery(searchQuery)
                            .ApplyGridCommand(command, false);

                products = await new PagedList <Product>(query, command.Page - 1, command.PageSize).LoadAsync();
            }

            var fileIds = products.AsEnumerable()
                          .Select(x => x.MainPictureId ?? 0)
                          .Where(x => x != 0)
                          .Distinct()
                          .ToArray();

            var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

            gridModel.Rows = products.AsEnumerable().Select(x =>
            {
                var productModel = new ProductOverviewModel
                {
                    Sku                  = x.Sku,
                    Published            = x.Published,
                    ProductTypeLabelHint = x.ProductTypeLabelHint,
                    Name                 = x.Name,
                    Id                        = x.Id,
                    StockQuantity             = x.StockQuantity,
                    Price                     = x.Price,
                    LimitedToStores           = x.LimitedToStores,
                    EditUrl                   = Url.Action("Edit", "Product", new { id = x.Id }),
                    ManufacturerPartNumber    = x.ManufacturerPartNumber,
                    Gtin                      = x.Gtin,
                    MinStockQuantity          = x.MinStockQuantity,
                    OldPrice                  = x.OldPrice,
                    AvailableStartDateTimeUtc = x.AvailableStartDateTimeUtc,
                    AvailableEndDateTimeUtc   = x.AvailableEndDateTimeUtc
                };

                //MiniMapper.Map(x, productModel);

                files.TryGetValue(x.MainPictureId ?? 0, out var file);

                // TODO: (core) Use IImageModel
                productModel.PictureThumbnailUrl = _mediaService.GetUrl(file, _mediaSettings.CartThumbPictureSize);
                productModel.NoThumb             = file == null;

                productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService);
                productModel.UpdatedOn       = _dateTimeHelper.ConvertToUserTime(x.UpdatedOnUtc, DateTimeKind.Utc);
                productModel.CreatedOn       = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);

                return(productModel);
            });

            gridModel.Total = products.TotalCount;

            return(Json(gridModel));
        }
Exemplo n.º 19
0
        public static ProductBoxModel PrepareProductBoxModel(this ProductOverviewModel product, string styleClass = "", string imageLoadType = "")
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            var workContext = EngineContext.Current.Resolve <IWorkContext>();

            var model = new ProductBoxModel
            {
                Id                    = product.Id,
                Name                  = product.Name,
                DefaultOption         = product.DefaultOption,
                Options               = product.Options,
                UrlKey                = product.UrlKey,
                StyleClass            = styleClass,
                AverageReviewRating   = product.AverageReviewRating,
                ReviewCount           = product.ReviewCount,
                ProductMark           = product.ProductMark,
                ProductMarkType       = product.ProductMarkType,
                ProductMarkExpiryDate = product.ProductMarkExpiryDate,
                ShortDescription      = product.FullDescription,
                StockAvailability     = product.StockAvailability,
                CurrencyCode          = workContext.WorkingCurrency.CurrencyCode,
                RelatedOffers         = product.RelatedOffers,
                ImageLoadType         = imageLoadType
            };

            #region Image

            var picture = new PictureModel
            {
                ImageUrl      = string.IsNullOrEmpty(product.GridMediaFilename) ? "/content/img/no-image.gif" : product.GridMediaFilename,
                AlternateText = product.Name,
                Title         = product.Name
            };

            model.Picture = picture;

            #endregion

            #region Stock availability

            if (product.StockAvailability == false)
            {
                if (product.Discontinued == true)
                {
                    model.DisableBuyButton = true;
                    model.AMPNote          = model.Note = "DISCONTINUED";
                    model.ButtonMessage    = "View";
                }
                else if (product.ProductEnforcedStockCount || product.BrandEnforcedStockCount)
                {
                    model.DisableBuyButton = true;
                    model.AMPNote          = model.Note = "SOLD OUT";
                    model.ButtonMessage    = "View";
                }
                else if (product.ShowPreOrderButton == true)
                {
                    model.AMPNote       = model.Note = "AVAILABLE FOR PRE-ORDER";
                    model.ButtonMessage = "Pre-order Now";
                }
            }

            #endregion

            #region Price range

            if (product.PriceExclTaxRange != null && product.PriceExclTaxRange.Length > 0)
            {
                var priceFormatter = EngineContext.Current.Resolve <IPriceFormatter>();

                if (product.PriceExclTaxRange.Length == 1)
                {
                    if (workContext.CurrentCountry.IsEC)
                    {
                        model.PriceRange = priceFormatter.FormatPrice(product.PriceInclTaxRange[0]);
                        model.PriceValue = priceFormatter.FormatPrice(product.PriceInclTaxRange[0], showCurrency: false);
                    }
                    else
                    {
                        model.PriceRange = priceFormatter.FormatPrice(product.PriceExclTaxRange[0]);
                        model.PriceValue = priceFormatter.FormatPrice(product.PriceExclTaxRange[0], showCurrency: false);
                    }
                }
                else
                {
                    if (workContext.CurrentCountry.IsEC)
                    {
                        model.PriceRange = priceFormatter.FormatPrice(product.PriceInclTaxRange[0]) + " - " + priceFormatter.FormatPrice(product.PriceInclTaxRange[1]);
                        model.PriceValue = priceFormatter.FormatPrice(product.PriceInclTaxRange[0], showCurrency: false);
                    }
                    else
                    {
                        model.PriceRange = priceFormatter.FormatPrice(product.PriceExclTaxRange[0]) + " - " + priceFormatter.FormatPrice(product.PriceExclTaxRange[1]);
                        model.PriceValue = priceFormatter.FormatPrice(product.PriceExclTaxRange[0], showCurrency: false);
                    }
                }
            }

            #endregion

            return(model);
        }