public virtual IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCategories))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = _categoryModelFactory.PrepareCategorySearchModel(new CategorySearchModel());

            return(View(model));
        }
Exemplo n.º 2
0
        private async Task PrepareCheckoutAttributes(ShoppingCartModel model, GetShoppingCart request)
        {
            #region Checkout attributes

            var checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(request.Store.Id, !request.Cart.RequiresShipping());

            foreach (var attribute in checkoutAttributes)
            {
                var attributeModel = new ShoppingCartModel.CheckoutAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = attribute.GetTranslation(x => x.Name, request.Language.Id),
                    TextPrompt           = attribute.GetTranslation(x => x.TextPrompt, request.Language.Id),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlTypeId,
                    DefaultValue         = attribute.DefaultValue
                };
                if (!String.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
                {
                    attributeModel.AllowedFileExtensions = attribute.ValidationFileAllowedExtensions
                                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .ToList();
                }

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = attribute.CheckoutAttributeValues;
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new ShoppingCartModel.CheckoutAttributeValueModel
                        {
                            Id              = attributeValue.Id,
                            Name            = attributeValue.GetTranslation(x => x.Name, request.Language.Id),
                            ColorSquaresRgb = attributeValue.ColorSquaresRgb,
                            IsPreSelected   = attributeValue.IsPreSelected,
                        };
                        attributeModel.Values.Add(attributeValueModel);

                        //display price if allowed
                        if (await _permissionService.Authorize(StandardPermission.DisplayPrices))
                        {
                            double priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue)).checkoutPrice;
                            double priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, request.Currency);

                            if (priceAdjustmentBase > 0)
                            {
                                attributeValueModel.PriceAdjustment = "+" + _priceFormatter.FormatPrice(priceAdjustment);
                            }
                            else if (priceAdjustmentBase < 0)
                            {
                                attributeValueModel.PriceAdjustment = "-" + _priceFormatter.FormatPrice(-priceAdjustment);
                            }
                        }
                    }
                }
                //set already selected attributes
                var selectedCheckoutAttributes = request.Customer.GetUserFieldFromEntity <List <CustomAttribute> >(SystemCustomerFieldNames.CheckoutAttributes, request.Store.Id);
                switch (attribute.AttributeControlTypeId)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Checkboxes:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())
                    {
                        //clear default selection
                        foreach (var item in attributeModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        //select new values
                        var selectedValues = await _checkoutAttributeParser.ParseCheckoutAttributeValues(selectedCheckoutAttributes);

                        foreach (var attributeValue in selectedValues)
                        {
                            if (attributeModel.Id == attributeValue.CheckoutAttributeId)
                            {
                                foreach (var item in attributeModel.Values)
                                {
                                    if (attributeValue.Id == item.Id)
                                    {
                                        item.IsPreSelected = true;
                                    }
                                }
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //do nothing
                    //values are already pre-set
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())
                    {
                        var enteredText = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
                        if (enteredText.Any())
                        {
                            attributeModel.DefaultValue = enteredText[0];
                        }
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())
                    {
                        //keep in mind my that the code below works only in the current culture
                        var selectedDateStr = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
                        if (selectedDateStr.Any())
                        {
                            DateTime selectedDate;
                            if (DateTime.TryParseExact(selectedDateStr[0], "D", CultureInfo.CurrentCulture,
                                                       DateTimeStyles.None, out selectedDate))
                            {
                                //successfully parsed
                                attributeModel.SelectedDay   = selectedDate.Day;
                                attributeModel.SelectedMonth = selectedDate.Month;
                                attributeModel.SelectedYear  = selectedDate.Year;
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())
                    {
                        var  downloadGuidStr = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).FirstOrDefault();
                        Guid downloadGuid;
                        Guid.TryParse(downloadGuidStr, out downloadGuid);
                        var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                        if (download != null)
                        {
                            attributeModel.DefaultValue = download.DownloadGuid.ToString();
                        }
                    }
                }
                break;

                default:
                    break;
                }

                model.CheckoutAttributes.Add(attributeModel);
            }
            #endregion
        }
Exemplo n.º 3
0
        public ActionResult List(bool liveRates = false)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCurrencies))
            {
                return(AccessDeniedView());
            }

            var currenciesModel = _currencyService.GetAllCurrencies(true).Select(x => x.ToModel()).ToList();

            foreach (var currency in currenciesModel)
            {
                currency.IsPrimaryExchangeRateCurrency = currency.Id == _currencySettings.PrimaryExchangeRateCurrencyId ? true : false;
            }
            foreach (var currency in currenciesModel)
            {
                currency.IsPrimaryStoreCurrency = currency.Id == _currencySettings.PrimaryStoreCurrencyId ? true : false;
            }
            if (liveRates)
            {
                try
                {
                    var primaryExchangeCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
                    if (primaryExchangeCurrency == null)
                    {
                        throw new NasException("Primary exchange rate currency is not set");
                    }

                    ViewBag.Rates = _currencyService.GetCurrencyLiveRates(primaryExchangeCurrency.CurrencyCode);
                }
                catch (Exception exc)
                {
                    ErrorNotification(exc, false);
                }
            }
            ViewBag.ExchangeRateProviders = new List <SelectListItem>();
            foreach (var erp in _currencyService.LoadAllExchangeRateProviders())
            {
                ViewBag.ExchangeRateProviders.Add(new SelectListItem()
                {
                    Text     = erp.PluginDescriptor.FriendlyName,
                    Value    = erp.PluginDescriptor.SystemName,
                    Selected = erp.PluginDescriptor.SystemName.Equals(_currencySettings.ActiveExchangeRateProviderSystemName, StringComparison.InvariantCultureIgnoreCase)
                });
            }
            ViewBag.AutoUpdateEnabled = _currencySettings.AutoUpdateEnabled;
            var gridModel = new GridModel <CurrencyModel>
            {
                Data  = currenciesModel,
                Total = currenciesModel.Count()
            };

            return(View(gridModel));
        }
        public virtual IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
            {
                return(AccessDeniedView());
            }

            //select "customer form fields" tab
            //SaveSelectedTabName("tab-contractformfields");

            //we just redirect a user to the customer settings page
            return(RedirectToAction("ContractAttribute", "Setting"));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Prepare FeedGoogleShoppingModel
        /// </summary>
        /// <param name="model">Model</param>
        private void PrepareModel(FeedGoogleShoppingModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return;
            }

            //load settings for a chosen store scope
            var storeScope             = _storeContext.ActiveStoreScopeConfiguration;
            var googleShoppingSettings = _settingService.LoadSetting <GoogleShoppingSettings>(storeScope);

            model.ProductPictureSize         = googleShoppingSettings.ProductPictureSize;
            model.PassShippingInfoWeight     = googleShoppingSettings.PassShippingInfoWeight;
            model.PassShippingInfoDimensions = googleShoppingSettings.PassShippingInfoDimensions;
            model.PricesConsiderPromotions   = googleShoppingSettings.PricesConsiderPromotions;

            //currencies
            model.CurrencyId = googleShoppingSettings.CurrencyId;
            foreach (var c in _currencyService.GetAllCurrencies())
            {
                model.AvailableCurrencies.Add(new SelectListItem {
                    Text = c.Name, Value = c.Id.ToString()
                });
            }
            //Google categories
            model.DefaultGoogleCategory = googleShoppingSettings.DefaultGoogleCategory;
            model.AvailableGoogleCategories.Add(new SelectListItem {
                Text = "Select a category", Value = ""
            });
            foreach (var gc in _googleService.GetTaxonomyList())
            {
                model.AvailableGoogleCategories.Add(new SelectListItem {
                    Text = gc, Value = gc
                });
            }

            model.HideGeneralBlock         = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, GoogleShoppingDefaults.HideGeneralBlock);
            model.HideProductSettingsBlock = _genericAttributeService.GetAttribute <bool>(_workContext.CurrentCustomer, GoogleShoppingDefaults.HideProductSettingsBlock);

            //prepare nested search models
            model.GoogleProductSearchModel.SetGridPageSize();

            //file paths
            foreach (var store in _storeService.GetAllStores())
            {
                var localFilePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "files\\exportimport", store.Id + "-" + googleShoppingSettings.StaticFileName);
                if (System.IO.File.Exists(localFilePath))
                {
                    model.GeneratedFiles.Add(new GeneratedFileModel
                    {
                        StoreName = store.Name,
                        FileUrl   = $"{_webHelper.GetStoreLocation(false)}files/exportimport/{store.Id}-{googleShoppingSettings.StaticFileName}"
                    });
                }
            }

            model.ActiveStoreScopeConfiguration = storeScope;
            if (storeScope > 0)
            {
                model.CurrencyId_OverrideForStore                 = _settingService.SettingExists(googleShoppingSettings, x => x.CurrencyId, storeScope);
                model.DefaultGoogleCategory_OverrideForStore      = _settingService.SettingExists(googleShoppingSettings, x => x.DefaultGoogleCategory, storeScope);
                model.PassShippingInfoDimensions_OverrideForStore = _settingService.SettingExists(googleShoppingSettings, x => x.PassShippingInfoDimensions, storeScope);
                model.PassShippingInfoWeight_OverrideForStore     = _settingService.SettingExists(googleShoppingSettings, x => x.PassShippingInfoWeight, storeScope);
                model.PricesConsiderPromotions_OverrideForStore   = _settingService.SettingExists(googleShoppingSettings, x => x.PricesConsiderPromotions, storeScope);
                model.ProductPictureSize_OverrideForStore         = _settingService.SettingExists(googleShoppingSettings, x => x.ProductPictureSize, storeScope);
            }
        }
        public virtual IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
            {
                return(AccessDeniedView());
            }

            //select "address form fields" tab
            SaveSelectedTabName("tab-addressformfields");

            //we just redirect a user to the address settings page
            return(RedirectToAction("CustomerUser", "Setting"));
        }
        /// <summary>
        /// Process the incoming request
        /// </summary>
        /// <returns>A task that represents the completion of the operation</returns>
        protected virtual async Task ProcessRequestAsync()
        {
            var action = "DIRLIST";

            try
            {
                if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures))
                {
                    throw new Exception("You don't have required permission");
                }

                if (!StringValues.IsNullOrEmpty(HttpContext.Request.Query["a"]))
                {
                    action = HttpContext.Request.Query["a"];
                }

                switch (action.ToUpper())
                {
                case "DIRLIST":
                    await GetDirectoriesAsync(HttpContext.Request.Query["type"]);

                    break;

                case "FILESLIST":
                    await GetFilesAsync(HttpContext.Request.Query["d"], HttpContext.Request.Query["type"]);

                    break;

                case "COPYDIR":
                    await CopyDirectoryAsync(HttpContext.Request.Query["d"], HttpContext.Request.Query["n"]);

                    break;

                case "COPYFILE":
                    await CopyFileAsync(HttpContext.Request.Query["f"], HttpContext.Request.Query["n"]);

                    break;

                case "CREATEDIR":
                    await CreateDirectoryAsync(HttpContext.Request.Query["d"], HttpContext.Request.Query["n"]);

                    break;

                case "DELETEDIR":
                    await DeleteDirectoryAsync(HttpContext.Request.Query["d"]);

                    break;

                case "DELETEFILE":
                    await DeleteFileAsync(HttpContext.Request.Query["f"]);

                    break;

                case "DOWNLOAD":
                    await DownloadFileAsync(HttpContext.Request.Query["f"]);

                    break;

                case "DOWNLOADDIR":
                    await DownloadDirectoryAsync(HttpContext.Request.Query["d"]);

                    break;

                case "MOVEDIR":
                    await MoveDirectoryAsync(HttpContext.Request.Query["d"], HttpContext.Request.Query["n"]);

                    break;

                case "MOVEFILE":
                    await MoveFileAsync(HttpContext.Request.Query["f"], HttpContext.Request.Query["n"]);

                    break;

                case "RENAMEDIR":
                    await RenameDirectoryAsync(HttpContext.Request.Query["d"], HttpContext.Request.Query["n"]);

                    break;

                case "RENAMEFILE":
                    await RenameFileAsync(HttpContext.Request.Query["f"], HttpContext.Request.Query["n"]);

                    break;

                case "GENERATETHUMB":
                    int.TryParse(HttpContext.Request.Query["width"].ToString().Replace("px", string.Empty), out var w);
                    int.TryParse(HttpContext.Request.Query["height"].ToString().Replace("px", string.Empty), out var h);
                    CreateThumbnail(HttpContext.Request.Query["f"], w, h);
                    break;

                case "UPLOAD":
                    await UploadFilesAsync(HttpContext.Request.Form["d"]);

                    break;

                default:
                    await HttpContext.Response.WriteAsync(GetErrorResponse("This action is not implemented."));

                    break;
                }
            }
            catch (Exception ex)
            {
                if (action == "UPLOAD" && !IsAjaxRequest())
                {
                    await HttpContext.Response.WriteAsync($"<script>parent.fileUploaded({GetErrorResponse(GetLanguageResource("E_UploadNoFiles"))});</script>");
                }
                else
                {
                    await HttpContext.Response.WriteAsync(GetErrorResponse(ex.Message));
                }
            }
        }
Exemplo n.º 8
0
        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return(AccessDeniedView());
            }

            var model = new PluginListModel();

            //load modes
            model.AvailableLoadModes = LoadPluginsMode.All.ToSelectList(false).ToList();
            //groups
            model.AvailableGroups.Add(new SelectListItem {
                Text = _localizationService.GetResource("Admin.Common.All"), Value = ""
            });
            foreach (var g in _pluginFinder.GetPluginGroups())
            {
                model.AvailableGroups.Add(new SelectListItem {
                    Text = g, Value = g
                });
            }
            return(View(model));
        }
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAttributes))
            {
                return(AccessDeniedView());
            }

            return(View());
        }
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageDiscounts))
            {
                return(AccessDeniedView());
            }

            var model = new DiscountListModel();

            model.AvailableDiscountTypes = DiscountType.AssignedToOrderTotal.ToSelectList(false).ToList();
            model.AvailableDiscountTypes.Insert(0, new SelectListItem {
                Text = _localizationService.GetResource("Admin.Common.All"), Value = "0"
            });

            return(View(model));
        }
Exemplo n.º 11
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize("ManageEvents"))
            {
                return(AccessDeniedView());
            }

            var model = new List <EventModel>();

            return(View(model));
        }
Exemplo n.º 12
0
        public virtual IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return(AccessDeniedView());
            }

            var model = _pluginModelFactory.PreparePluginsConfigurationModel(new PluginsConfigurationModel());

            return(View(model));
        }
Exemplo n.º 13
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            {
                return(AccessDeniedView());
            }

            var model            = new CategoryListModel();
            var categories       = _categoryService.GetAllCategories(null, 0, _adminAreaSettings.GridPageSize, true);
            var mappedCategories = categories.ToDictionary(x => x.Id);

            model.Categories = new GridModel <CategoryModel>
            {
                Data = categories.Select(x =>
                {
                    var categoryModel        = x.ToModel();
                    categoryModel.Breadcrumb = x.GetCategoryBreadCrumb(_categoryService, mappedCategories);
                    return(categoryModel);
                }),
                Total = categories.TotalCount
            };
            return(View(model));
        }
Exemplo n.º 14
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(),
                };
                //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);

                        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);
                                        }
                                    }


                                    //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            = string.Format(localizationService.GetResource("Media.Product.ImageLinkTitleFormat"), model.Name),
                            AlternateText    = 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 = new ProductReviewOverviewModel()
                {
                    ProductId            = product.Id,
                    RatingSum            = product.ApprovedRatingSum,
                    TotalReviews         = product.ApprovedTotalReviews,
                    AllowCustomerReviews = product.AllowCustomerReviews
                };

                models.Add(model);
            }
            return(models);
        }
Exemplo n.º 15
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
            {
                return(AccessDeniedView());
            }

            var model = new NewsItemListModel();

            foreach (var s in _storeService.GetAllStores())
            {
                model.AvailableStores.Add(new SelectListItem {
                    Text = s.Name, Value = s.Id.ToString()
                });
            }

            return(View(model));
        }
Exemplo n.º 16
0
        public virtual ActionResult CategoryTemplates()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance))
            {
                return(AccessDeniedView());
            }

            return(View());
        }
Exemplo n.º 17
0
        public virtual IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAttributes))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = _specificationAttributeModelFactory.PrepareSpecificationAttributeSearchModel(new SpecificationAttributeSearchModel());

            return(View(model));
        }
Exemplo n.º 18
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings))
            {
                return(AccessDeniedView());
            }

            //we just redirect a user to the address settings page

            //select third tab
            const int addressFormFieldIndex = 2;

            SaveSelectedTabIndex(addressFormFieldIndex);
            return(RedirectToAction("CustomerUser", "Setting"));
        }
Exemplo n.º 19
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            {
                return(AccessDeniedView());
            }

            ViewData["GridPageSize"] = _adminAreaSettings.GridPageSize;

            return(View());
        }
Exemplo n.º 20
0
        public virtual IActionResult List(bool liveRates = false)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCurrencies))
            {
                return(AccessDeniedView());
            }

            var model = new CurrencySearchModel();

            try
            {
                //prepare model
                model = _currencyModelFactory.PrepareCurrencySearchModel(new CurrencySearchModel(), liveRates);
            }
            catch (Exception e)
            {
                _notificationService.ErrorNotification(e);
            }

            return(View(model));
        }
Exemplo n.º 21
0
 protected async Task <bool> CheckPermission(string objectType, string entityId)
 {
     Enum.TryParse(objectType, out EntityType objType);
     if (objType == EntityType.Category)
     {
         return(await PermissionForCategory(entityId));
     }
     if (objType == EntityType.Product)
     {
         return(await PermissionForProduct(entityId));
     }
     if (objType == EntityType.Collection)
     {
         return(await PermissionForCollection(entityId));
     }
     if (objType == EntityType.Course)
     {
         return(await PermissionForCourse(entityId));
     }
     if (objType == EntityType.Order)
     {
         return(await PermissionForOrder(entityId));
     }
     if (objType == EntityType.Customer)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManageCustomers))
         {
             return(false);
         }
     }
     if (objType == EntityType.CustomerGroup)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManageCustomerGroups))
         {
             return(false);
         }
     }
     if (objType == EntityType.Vendor)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManageVendors))
         {
             return(false);
         }
     }
     if (objType == EntityType.Shipment)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManageShipments))
         {
             return(false);
         }
     }
     if (objType == EntityType.MerchandiseReturn)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManageMerchandiseReturns))
         {
             return(false);
         }
     }
     if (objType == EntityType.Page)
     {
         if (!await _permissionService.Authorize(StandardPermission.ManagePages))
         {
             return(false);
         }
     }
     if (objType == EntityType.BlogPost)
     {
         return(await PermissionForBlog(entityId));
     }
     return(true);
 }
Exemplo n.º 22
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return(AccessDeniedView());
            }

            var model = PrepareLocalPluginsModel();

            return(View(model));
        }
Exemplo n.º 23
0
        public virtual IActionResult SystemInfo()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = _commonModelFactory.PrepareSystemInfoModel(new SystemInfoModel());

            return(View(model));
        }
        public IActionResult Configure()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePaymentMethods))
            {
                return(AccessDeniedView());
            }

            //load settings for a chosen store scope
            var storeScope           = _storeContext.ActiveStoreScopeConfiguration;
            var paytmPaymentSettings = _settingService.LoadSetting <PaytmPaymentSettings>(storeScope);
            ConfigurationModel model;

            if (paytmPaymentSettings.env == "Stage")
            {
                model = new ConfigurationModel
                {
                    MerchantId                    = paytmPaymentSettings.MerchantId,
                    MerchantKey                   = paytmPaymentSettings.MerchantKey,
                    Website                       = paytmPaymentSettings.Website,
                    IndustryTypeId                = paytmPaymentSettings.IndustryTypeId,
                    CallBackUrl                   = paytmPaymentSettings.CallBackUrl,
                    UseDefaultCallBack            = paytmPaymentSettings.UseDefaultCallBack,
                    PaymentUrl                    = "https://securegw-stage.paytm.in/order/process",
                    TxnStatusUrl                  = "https://securegw-stage.paytm.in/order/status",
                    ActiveStoreScopeConfiguration = storeScope,
                    env = paytmPaymentSettings.env
                };
                // return View("~/Plugins/Payments.Paytm/Views/Configure.cshtml", model);
            }
            else
            {
                model = new ConfigurationModel
                {
                    MerchantId                    = paytmPaymentSettings.MerchantId,
                    MerchantKey                   = paytmPaymentSettings.MerchantKey,
                    Website                       = paytmPaymentSettings.Website,
                    IndustryTypeId                = paytmPaymentSettings.IndustryTypeId,
                    CallBackUrl                   = paytmPaymentSettings.CallBackUrl,
                    PaymentUrl                    = "https://securegw.paytm.in/order/process",
                    TxnStatusUrl                  = "https://securegw.paytm.in/order/status",
                    UseDefaultCallBack            = paytmPaymentSettings.UseDefaultCallBack,
                    ActiveStoreScopeConfiguration = storeScope,
                    env = paytmPaymentSettings.env
                };
                //  return View("~/Plugins/Payments.Paytm/Views/Configure.cshtml", model);
            }

            //  return View("~/Plugins/Payments.Paytm/Views/Configure.cshtml", model);

            if (storeScope <= 0)
            {
                return(View("~/Plugins/Payments.Paytm/Views/Configure.cshtml", model));
            }
            model.MerchantId_OverrideForStore         = _settingService.SettingExists(paytmPaymentSettings, x => x.MerchantId, storeScope);
            model.IndustryTypeId_OverrideForStore     = _settingService.SettingExists(paytmPaymentSettings, x => x.IndustryTypeId, storeScope);
            model.MerchantKey_OverrideForStore        = _settingService.SettingExists(paytmPaymentSettings, x => x.MerchantKey, storeScope);
            model.CallBackUrl_OverrideForStore        = _settingService.SettingExists(paytmPaymentSettings, x => x.CallBackUrl, storeScope);
            model.PaymentUrl_OverrideForStore         = _settingService.SettingExists(paytmPaymentSettings, x => x.PaymentUrl, storeScope);
            model.TxnStatusUrl_OverrideForStore       = _settingService.SettingExists(paytmPaymentSettings, x => x.TxnStatusUrl, storeScope);
            model.UseDefaultCallBack_OverrideForStore = _settingService.SettingExists(paytmPaymentSettings, x => x.UseDefaultCallBack, storeScope);
            model.env_OverrideForStore = _settingService.SettingExists(paytmPaymentSettings, x => x.env, storeScope);
            return(View("~/Plugins/Payments.Paytm/Views/Configure.cshtml", model));
        }
Exemplo n.º 25
0
        public ActionResult ProcessRequest()
        {
            string action = "DIRLIST";

            if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures))
            {
                _r.Write(GetErrorRes("You don't have required permission"));
            }

            try
            {
                if (_context.Request["a"] != null)
                {
                    action = (string)_context.Request["a"];
                }

                switch (action.ToUpper())
                {
                case "DIRLIST":
                    ListDirTree(_context.Request["type"]);
                    break;

                case "FILESLIST":
                    ListFiles(_context.Request["d"], _context.Request["type"]);
                    break;

                case "COPYDIR":
                    CopyDir(_context.Request["d"], _context.Request["n"]);
                    break;

                case "COPYFILE":
                    CopyFile(_context.Request["f"], _context.Request["n"]);
                    break;

                case "CREATEDIR":
                    CreateDir(_context.Request["d"], _context.Request["n"]);
                    break;

                case "DELETEDIR":
                    DeleteDir(_context.Request["d"]);
                    break;

                case "DELETEFILE":
                    DeleteFile(_context.Request["f"]);
                    break;

                case "DOWNLOAD":
                    DownloadFile(_context.Request["f"]);
                    break;

                case "DOWNLOADDIR":
                    DownloadDir(_context.Request["d"]);
                    break;

                case "MOVEDIR":
                    MoveDir(_context.Request["d"], _context.Request["n"]);
                    break;

                case "MOVEFILE":
                    MoveFile(_context.Request["f"], _context.Request["n"]);
                    break;

                case "RENAMEDIR":
                    RenameDir(_context.Request["d"], _context.Request["n"]);
                    break;

                case "RENAMEFILE":
                    RenameFile(_context.Request["f"], _context.Request["n"]);
                    break;

                case "GENERATETHUMB":
                    int w = 140, h = 0;
                    int.TryParse(_context.Request["width"].Replace("px", ""), out w);
                    int.TryParse(_context.Request["height"].Replace("px", ""), out h);
                    ShowThumbnail(_context.Request["f"], w, h);
                    break;

                case "UPLOAD":
                    Upload(_context.Request["d"]);
                    break;

                default:
                    _r.Write(GetErrorRes("This action is not implemented."));
                    break;
                }
            }
            catch (Exception ex)
            {
                if (action == "UPLOAD")
                {
                    _r.Write("<script>");
                    _r.Write("parent.fileUploaded(" + GetErrorRes(LangRes("E_UploadNoFiles")) + ");");
                    _r.Write("</script>");
                }
                else
                {
                    _r.Write(GetErrorRes(ex.Message));
                }
            }

            return(Content(""));
        }
Exemplo n.º 26
0
        public ActionResult SystemInfo()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance))
            {
                return(AccessDeniedView());
            }

            var model = new SystemInfoModel();

            model.NopVersion = NopVersion.CurrentVersion;
            try
            {
                model.OperatingSystem = Environment.OSVersion.VersionString;
            }
            catch (Exception) { }
            try
            {
                model.AspNetInfo = RuntimeEnvironment.GetSystemVersion();
            }
            catch (Exception) { }
            try
            {
                model.IsFullTrust = AppDomain.CurrentDomain.IsFullyTrusted.ToString();
            }
            catch (Exception) { }
            model.ServerTimeZone  = TimeZone.CurrentTimeZone.StandardName;
            model.ServerLocalTime = DateTime.Now;
            model.UtcTime         = DateTime.UtcNow;
            model.HttpHost        = _webHelper.ServerVariables("HTTP_HOST");
            foreach (var key in _httpContext.Request.ServerVariables.AllKeys)
            {
                model.ServerVariables.Add(new SystemInfoModel.ServerVariableModel
                {
                    Name  = key,
                    Value = _httpContext.Request.ServerVariables[key]
                });
            }
            //Environment.GetEnvironmentVariable("USERNAME");
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                model.LoadedAssemblies.Add(new SystemInfoModel.LoadedAssembly
                {
                    FullName = assembly.FullName,
                    //we cannot use Location property in medium trust
                    //Location = assembly.Location
                });
            }
            return(View(model));
        }
Exemplo n.º 27
0
        public IActionResult Index()
        {
            //权限
            if (!_permissionService.Authorize("ViewPurchasingOrders"))
            {
                return(View("_AccessDeniedView"));
            }

            ViewBag.Suppliers = new SelectList(_purchasingService.GetAllSuppliers(), "SupplierName", "SupplierName");
            ViewBag.WareHouse = new SelectList(_wareHouseService.GetWareHouses(), "Name", "Name");

            return(View());
        }
Exemplo n.º 28
0
        public virtual IActionResult List(int?filterByBlogPostId)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageBlog))
            {
                return(AccessDeniedView());
            }

            //prepare model
            var model = _blogModelFactory.PrepareBlogContentModel(new BlogContentModel(), filterByBlogPostId);

            return(View(model));
        }
Exemplo n.º 29
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
            {
                return(AccessDeniedView());
            }

            var polls     = _pollService.GetPolls(0, false, 0, _adminAreaSettings.GridPageSize, true);
            var gridModel = new GridModel <PollModel>
            {
                Data = polls.Select(x =>
                {
                    var m = x.ToModel();
                    if (x.StartDateUtc.HasValue)
                    {
                        m.StartDate = _dateTimeHelper.ConvertToUserTime(x.StartDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (x.EndDateUtc.HasValue)
                    {
                        m.EndDate = _dateTimeHelper.ConvertToUserTime(x.EndDateUtc.Value, DateTimeKind.Utc);
                    }
                    m.LanguageName = x.Language.Name;
                    return(m);
                }),
                Total = polls.TotalCount
            };

            return(View(gridModel));
        }
        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(),
                };
                //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);

                                switch (associatedProducts.Count)
                                {
                                    case 0:
                                        {
                                            //no associated products
                                            //priceModel.DisableBuyButton = true;
                                            //priceModel.DisableWishlistButton = true;
                                            //compare products
                                            priceModel.DisableAddToCompareListButton = !catalogSettings.CompareProductsEnabled;
                                            //priceModel.AvailableForPreOrder = false;
                                        }
                                        break;
                                    default:
                                        {
                                            //we have at least one associated product
                                            //priceModel.DisableBuyButton = true;
                                            //priceModel.DisableWishlistButton = true;
                                            //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));

                                                    }
                                                    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));
                                            }
                                            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);
                                                }
                                            }
                                            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 = new ProductReviewOverviewModel
                {
                    ProductId = product.Id,
                    RatingSum = product.ApprovedRatingSum,
                    TotalReviews = product.ApprovedTotalReviews,
                    AllowCustomerReviews = product.AllowCustomerReviews
                };

                models.Add(model);
            }
            return models;
        }
Exemplo n.º 31
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            {
                return(AccessDeniedView());
            }

            var specificationAttributes = _specificationAttributeService.GetSpecificationAttributes();
            var gridModel = new GridModel <SpecificationAttributeModel>
            {
                Data  = specificationAttributes.Select(x => x.ToModel()),
                Total = specificationAttributes.Count()
            };

            return(View(gridModel));
        }