Beispiel #1
0
        public override IViewComponentResult Invoke(object data = null)
        {
            var dataAsDict = data as Dictionary <string, object>;

            if (dataAsDict == null)
            {
                return(R.Fail.ComponentResult);
            }

            dataAsDict.TryGetValue("productId", out var productIdObj);
            if (productIdObj == null || !int.TryParse(productIdObj.ToString(), out var productId))
            {
                return(R.Fail.ComponentResult);
            }

            //get the product
            var product = _productService.Get(productId);

            if (product == null)
            {
                return(R.Fail.ComponentResult);
            }
            if (!product.IsPublic(CurrentStore.Id) && !CurrentUser.Can(CapabilitySystemNames.EditProduct))
            {
                return(R.Fail.ComponentResult);
            }
            var productModel = _productModelFactory.Create(product);

            var response = R.Success;

            response.With("product", productModel);

            if (product.HasVariants)
            {
                //any variants
                var variants      = _productVariantService.GetByProductId(product.Id);
                var variantModels = new List <object>();
                foreach (var variant in variants)
                {
                    _priceAccountant.GetProductPriceDetails(product, null, variant.Price, out decimal priceWithoutTax, out decimal tax, out decimal taxRate, out _);
                    var variantObject = new
                    {
                        attributes = new Dictionary <string, string>(),
                        price      = _priceAccountant
                                     .ConvertCurrency(
                            (_taxSettings.DisplayProductPricesWithoutTax ? priceWithoutTax : priceWithoutTax + tax),
                            ApplicationEngine.CurrentCurrency).ToCurrency(),
                        isAvailable = !variant.TrackInventory ||
                                      (variant.TrackInventory && variant.IsAvailableInStock(product)),
                        sku  = !variant.Sku.IsNullEmptyOrWhiteSpace() ? variant.Sku : product.Sku,
                        gtin = !variant.Gtin.IsNullEmptyOrWhiteSpace() ? variant.Gtin : product.Gtin,
                        mpn  = !variant.Mpn.IsNullEmptyOrWhiteSpace() ? variant.Mpn : product.Mpn
                    };
                    foreach (var pva in variant.ProductVariantAttributes)
                    {
                        variantObject.attributes.Add(pva.ProductAttribute.Label, pva.ProductAttributeValue.AvailableAttributeValue.Value);
                    }
                    variantModels.Add(variantObject);
                }

                if (variantModels.Any())
                {
                    response.With("variants", variantModels);
                }
                productModel.IsAvailable = variantModels.Any(x => (bool)((dynamic)x).isAvailable);
            }

            return(response.ComponentResult);
        }
        public ProductModel Create(Product product)
        {
            var productModel = _modelMapper.Map <ProductModel>(product);

            productModel.IsAvailable = !product.TrackInventory || (product.TrackInventory && product.IsAvailableInStock());
            productModel.SeName      = product.SeoMeta?.Slug;

            var mediaModels = product.MediaItems?.OrderBy(x => x.DisplayOrder).Select(y =>
            {
                var mediaModel          = _modelMapper.Map <MediaModel>(y);
                mediaModel.ThumbnailUrl =
                    _mediaAccountant.GetPictureUrl(y, ApplicationEngine.ActiveTheme.ProductBoxImageSize, true);
                mediaModel.Url = _mediaAccountant.GetPictureUrl(y, 0, 0, true);
                return(mediaModel);
            }).ToList() ?? new List <MediaModel>()
            {
                new MediaModel()
                {
                    ThumbnailUrl = _mediaAccountant.GetPictureUrl(null,
                                                                  ApplicationEngine.ActiveTheme.ProductBoxImageSize, true),
                    Url = _mediaAccountant.GetPictureUrl(null, 0, 0, true)
                }
            };

            productModel.Media = mediaModels;
            if (product.ProductAttributes != null)
            {
                productModel.ProductAttributes = product.ProductAttributes.Select(x =>
                {
                    var paModel = new ProductAttributeModel
                    {
                        Name           = x.Label,
                        Id             = x.Id,
                        InputFieldType = x.InputFieldType,
                        IsRequired     = x.IsRequired,
                    };
                    if (x.AvailableAttribute.AvailableAttributeValues != null)
                    {
                        paModel.AvailableValues = x.AvailableAttribute.AvailableAttributeValues.Select(y =>
                        {
                            var avModel = new ProductAttributeValueModel()
                            {
                                Name = y.Value
                            };
                            return(avModel);
                        })
                                                  .ToList();
                    }
                    if (paModel.Name.IsNullEmptyOrWhiteSpace())
                    {
                        paModel.Name = x.AvailableAttribute.Name;
                    }
                    return(paModel);
                })
                                                 .ToList();
            }

            if (product.ProductSpecifications != null)
            {
                productModel.ProductSpecificationGroups = new List <ProductSpecificationGroupModel>();

                foreach (var grp in product.ProductSpecifications.GroupBy(x => x.ProductSpecificationGroup))
                {
                    var groupName = grp?.Key?.Name ?? "";
                    var specs     = grp.Select(x => new ProductSpecificationModel()
                    {
                        Name   = x.Label,
                        Values = x.ProductSpecificationValues.Select(y => y.Label).ToList()
                    }).ToList();
                    productModel.ProductSpecificationGroups.Add(new ProductSpecificationGroupModel()
                    {
                        Name = groupName,
                        ProductSpecifications = specs
                    });
                }
            }

            if (_catalogSettings.EnableReviews)
            {
                //reviews
                if (product.ReviewSummary != null)
                {
                    productModel.ReviewSummary = _modelMapper.Map <ReviewSummaryModel>(product.ReviewSummary);
                }
            }
            else
            {
                product.ReviewSummary = null;
            }
            if (productModel.RequireLoginToViewPrice && ApplicationEngine.CurrentUser.IsVisitor())
            {
                productModel.Price        = 0;
                productModel.ComparePrice = null;
            }
            else
            {
                IList <DiscountCoupon> coupons = null;
                //any autodiscounted price
                var price = _priceAccountant.GetAutoDiscountedPriceForUser(product, null, ApplicationEngine.CurrentUser, 1, ref coupons, out decimal discount);
                if (price < product.Price)
                {
                    productModel.ComparePrice = product.Price;
                    if (productModel.ComparePrice < product.ComparePrice)
                    {
                        productModel.ComparePrice = product.ComparePrice;
                    }
                }
                _priceAccountant.GetProductPriceDetails(product, null, price, out decimal priceWithoutTax,
                                                        out decimal tax, out decimal taxRate, out _);
                if (_taxSettings.DisplayProductPricesWithoutTax)
                {
                    productModel.Price = priceWithoutTax;
                }
                else
                {
                    productModel.Price = priceWithoutTax + tax;
                }

                //change display prices to current currency
                var targetCurrency = ApplicationEngine.CurrentCurrency;
                productModel.Price = _priceAccountant.ConvertCurrency(productModel.Price, targetCurrency);
            }

            return(productModel);
        }
Beispiel #3
0
        public IActionResult Index(int id)
        {
            if (id < 1)
            {
                return(NotFound());
            }
            var product = _productService.Get(id);

            if (!product.IsPublic() && !CurrentUser.Can(CapabilitySystemNames.EditProduct))
            {
                return(NotFound());
            }
            //is the product restricted to roles
            if (product.RestrictedToRoles)
            {
                var userRoleIds = CurrentUser?.Roles?.Select(x => x.Id).ToList();
                if (userRoleIds == null || product.EntityRoles.All(x => !userRoleIds.Contains(x.RoleId)))
                {
                    return(NotFound());
                }
            }
            var productModel = _productModelFactory.Create(product);

            var response = R.Success;

            response.With("product", productModel);

            if (_catalogSettings.EnableRelatedProducts)
            {
                var productRelations = _productRelationService.GetByProductId(id, ProductRelationType.RelatedProduct, 1,
                                                                              _catalogSettings.NumberOfRelatedProducts);
                if (productRelations.Any())
                {
                    var relatedProductsModel = productRelations.Select(x => x.DestinationProduct).Select(_productModelFactory.Create).ToList();
                    response.With("relatedProducts", relatedProductsModel);
                }
            }

            if (product.HasVariants)
            {
                //any variants
                var variants      = _productVariantService.GetByProductId(product.Id);
                var variantModels = new List <object>();
                foreach (var variant in variants)
                {
                    _priceAccountant.GetProductPriceDetails(product, null, variant.Price, out decimal priceWithoutTax, out decimal tax, out decimal taxRate, out _);
                    var variantObject = new
                    {
                        attributes = new Dictionary <string, string>(),
                        price      = _priceAccountant
                                     .ConvertCurrency(
                            (_taxSettings.DisplayProductPricesWithoutTax ? priceWithoutTax : priceWithoutTax + tax),
                            ApplicationEngine.CurrentCurrency).ToCurrency(),
                        isAvailable = !variant.TrackInventory ||
                                      (variant.TrackInventory && variant.IsAvailableInStock(product)),
                        sku  = !variant.Sku.IsNullEmptyOrWhiteSpace() ? variant.Sku : product.Sku,
                        gtin = !variant.Gtin.IsNullEmptyOrWhiteSpace() ? variant.Gtin : product.Gtin,
                        mpn  = !variant.Mpn.IsNullEmptyOrWhiteSpace() ? variant.Mpn : product.Mpn
                    };
                    foreach (var pva in variant.ProductVariantAttributes)
                    {
                        variantObject.attributes.Add(pva.ProductAttribute.Label, pva.ProductAttributeValue.AvailableAttributeValue.Value);
                    }
                    variantModels.Add(variantObject);
                }

                if (variantModels.Any())
                {
                    response.With("variants", variantModels);
                }
                productModel.IsAvailable = variantModels.Any(x => (bool)((dynamic)x).isAvailable);
            }

            //downloads
            if (product.IsDownloadable)
            {
                var downloads = _downloadService.GetWithoutBytes(x => x.ProductId == product.Id && !x.RequirePurchase).ToList();
                if (CurrentUser.IsVisitor())
                {
                    downloads = downloads.Where(x => !x.RequireLogin).ToList();
                }

                var downloadModels = downloads.Select(_productModelFactory.Create).ToList();
                response.With("downloads", downloadModels);
            }
            //reviews
            if (_catalogSettings.EnableReviews)
            {
                var reviews = _reviewService.Get(x => x.ProductId == product.Id, 1,
                                                 _catalogSettings.NumberOfReviewsToDisplayOnProductPage).ToList();

                if (reviews.Any())
                {
                    var reviewModels = reviews.Select(x =>
                    {
                        var model         = _modelMapper.Map <ReviewModel>(x);
                        model.DisplayName = x.Private ? _catalogSettings.DisplayNameForPrivateReviews : x.User?.Name;
                        if (model.DisplayName.IsNullEmptyOrWhiteSpace())
                        {
                            model.DisplayName = T("Store Customer");
                        }
                        return(model);
                    }).ToList();
                    response.With("reviews", reviewModels);
                }
            }

            //breadcrumbs
            if (_generalSettings.EnableBreadcrumbs)
            {
                var categoryTree        = _categoryService.GetFullCategoryTree();
                var category            = product.Categories?.FirstOrDefault();
                var currentCategoryFull = categoryTree.FirstOrDefault(x => x.Id == category?.Id);
                BreadcrumbHelper.SetCategoryBreadcrumb(currentCategoryFull, categoryTree);
                SetBreadcrumbToRoute(product.Name, RouteNames.SingleProduct, new { seName = product.SeoMeta.Slug }, localize: false);
            }
            //seo data
            SeoMetaHelper.SetSeoData(product.Name, product.Description, product.Description);
            return(response.With("preview", !product.Published).Result);
        }