Ejemplo n.º 1
0
        private void PrepareDiscountModel(DiscountModel model, Discount discount)
        {
            Guard.NotNull(model, nameof(model));

            var language = _services.WorkContext.WorkingLanguage;

            model.PrimaryStoreCurrencyCode = _services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode;
            model.AvailableDiscountRequirementRules.Add(new SelectListItem {
                Text = T("Admin.Promotions.Discounts.Requirements.DiscountRequirementType.Select"), Value = ""
            });

            var discountRules = _discountService.LoadAllDiscountRequirementRules();

            foreach (var discountRule in discountRules)
            {
                model.AvailableDiscountRequirementRules.Add(new SelectListItem
                {
                    Text  = _pluginMediator.GetLocalizedFriendlyName(discountRule.Metadata),
                    Value = discountRule.Metadata.SystemName
                });
            }

            if (discount != null)
            {
                model.AppliedToCategories = discount.AppliedToCategories
                                            .Where(x => x != null && !x.Deleted)
                                            .Select(x => new DiscountModel.AppliedToEntityModel {
                    Id = x.Id, Name = x.GetLocalized(y => y.Name, language)
                })
                                            .ToList();

                model.AppliedToManufacturers = discount.AppliedToManufacturers
                                               .Where(x => x != null && !x.Deleted)
                                               .Select(x => new DiscountModel.AppliedToEntityModel {
                    Id = x.Id, Name = x.GetLocalized(y => y.Name, language)
                })
                                               .ToList();

                model.AppliedToProducts = discount.AppliedToProducts
                                          .Where(x => x != null && !x.Deleted)
                                          .Select(x => new DiscountModel.AppliedToEntityModel {
                    Id = x.Id, Name = x.GetLocalized(y => y.Name, language)
                })
                                          .ToList();

                foreach (var dr in discount.DiscountRequirements.OrderBy(dr => dr.Id))
                {
                    var drr = _discountService.LoadDiscountRequirementRuleBySystemName(dr.DiscountRequirementRuleSystemName);
                    if (drr != null)
                    {
                        model.DiscountRequirementMetaInfos.Add(new DiscountModel.DiscountRequirementMetaInfo
                        {
                            DiscountRequirementId = dr.Id,
                            RuleName         = _pluginMediator.GetLocalizedFriendlyName(drr.Metadata),
                            ConfigurationUrl = GetRequirementUrlInternal(drr.Value, discount, dr.Id)
                        });
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private void PrepareCurrencyModel(CurrencyModel model, Currency currency, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var allStores        = _services.StoreService.GetAllStores();
            var paymentMethods   = _paymentService.GetAllPaymentMethods();
            var paymentProviders = _paymentService.LoadAllPaymentMethods().ToDictionarySafe(x => x.Metadata.SystemName);

            model.AvailableStores = allStores.Select(s => s.ToModel()).ToList();

            foreach (var paymentMethod in paymentMethods.Where(x => x.RoundOrderTotalEnabled))
            {
                string friendlyName = null;
                Provider <IPaymentMethod> provider;
                if (paymentProviders.TryGetValue(paymentMethod.PaymentMethodSystemName, out provider))
                {
                    friendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata);
                }

                model.RoundOrderTotalPaymentMethods[paymentMethod.PaymentMethodSystemName] = friendlyName ?? paymentMethod.PaymentMethodSystemName;
            }

            if (currency != null)
            {
                model.PrimaryStoreCurrencyStores = allStores
                                                   .Where(x => x.PrimaryStoreCurrencyId == currency.Id)
                                                   .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = Url.Action("Edit", "Store", new { id = x.Id })
                })
                                                   .ToList();

                model.PrimaryExchangeRateCurrencyStores = allStores
                                                          .Where(x => x.PrimaryExchangeRateCurrencyId == currency.Id)
                                                          .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = Url.Action("Edit", "Store", new { id = x.Id })
                })
                                                          .ToList();
            }

            if (!excludeProperties)
            {
                model.SelectedStoreIds = (currency == null ? new int[0] : _storeMappingService.GetStoresIdsWithAccess(currency));
            }
        }
        public ActionResult EditProviderPopup(string systemName)
        {
            var provider = _providerManager.GetProvider(systemName);

            if (provider == null)
            {
                return(HttpNotFound());
            }

            var infos = GetProviderInfos(provider);

            if (infos.ReadPermission.HasValue() && !Services.Permissions.Authorize(infos.ReadPermission))
            {
                return(AccessDeniedPartialView());
            }

            var model     = _pluginMediator.ToProviderModel(provider, true);
            var pageTitle = model.FriendlyName;

            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata, languageId, false);
                locale.Description  = _pluginMediator.GetLocalizedDescription(provider.Metadata, languageId, false);

                if (pageTitle.IsEmpty() && languageId == Services.WorkContext.WorkingLanguage.Id)
                {
                    pageTitle = locale.FriendlyName;
                }
            });

            ViewBag.Title = pageTitle;

            return(View(model));
        }
Ejemplo n.º 4
0
        public ActionResult EditProviderPopup(string systemName)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return(AccessDeniedView());
            }

            var provider = _providerManager.GetProvider(systemName);

            if (provider == null)
            {
                return(HttpNotFound());
            }

            var model     = _pluginMediator.ToProviderModel(provider, true);
            var pageTitle = model.FriendlyName;

            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata, languageId, false);
                locale.Description  = _pluginMediator.GetLocalizedDescription(provider.Metadata, languageId, false);

                if (pageTitle.IsEmpty() && languageId == _services.WorkContext.WorkingLanguage.Id)
                {
                    pageTitle = locale.FriendlyName;
                }
            });

            ViewBag.Title = pageTitle;

            return(View(model));
        }
Ejemplo n.º 5
0
        public ActionResult Edit(string systemName)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManagePaymentMethods))
            {
                return(AccessDeniedView());
            }

            var provider      = _paymentService.LoadPaymentMethodBySystemName(systemName);
            var paymentMethod = _paymentService.GetPaymentMethodBySystemName(systemName);

            var model         = new PaymentMethodEditModel();
            var providerModel = _pluginMediator.ToProviderModel <IPaymentMethod, ProviderModel>(provider, true);

            model.SystemName   = providerModel.SystemName;
            model.IconUrl      = providerModel.IconUrl;
            model.FriendlyName = providerModel.FriendlyName;
            model.Description  = providerModel.Description;

            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata, languageId, false);
                locale.Description  = _pluginMediator.GetLocalizedDescription(provider.Metadata, languageId, false);

                if (paymentMethod != null)
                {
                    locale.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, languageId, false, false);
                }
            });

            PreparePaymentMethodEditModel(model, paymentMethod);

            return(View(model));
        }
Ejemplo n.º 6
0
        private void PrepareCurrencyModel(CurrencyModel model, Currency currency, bool excludeProperties)
        {
            Guard.NotNull(model, nameof(model));

            var paymentMethods   = _paymentService.GetAllPaymentMethods();
            var paymentProviders = _paymentService.LoadAllPaymentMethods();

            foreach (var provider in paymentProviders)
            {
                if (paymentMethods.TryGetValue(provider.Metadata.SystemName, out var paymentMethod) && paymentMethod.RoundOrderTotalEnabled)
                {
                    var friendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata);
                    model.RoundOrderTotalPaymentMethods[provider.Metadata.SystemName] = friendlyName ?? provider.Metadata.SystemName;
                }
            }

            if (currency != null)
            {
                var allStores = _services.StoreService.GetAllStores();

                model.PrimaryStoreCurrencyStores = allStores
                                                   .Where(x => x.PrimaryStoreCurrencyId == currency.Id)
                                                   .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = Url.Action("Edit", "Store", new { id = x.Id })
                })
                                                   .ToList();

                model.PrimaryExchangeRateCurrencyStores = allStores
                                                          .Where(x => x.PrimaryExchangeRateCurrencyId == currency.Id)
                                                          .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = Url.Action("Edit", "Store", new { id = x.Id })
                })
                                                          .ToList();
            }

            if (!excludeProperties)
            {
                model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(currency);
            }
        }
Ejemplo n.º 7
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 SmartException("Primary exchange rate currency is not set");
                    }

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

            return(View(gridModel));
        }
Ejemplo n.º 8
0
        public ActionResult Edit(string systemName)
        {
            var provider      = _paymentService.LoadPaymentMethodBySystemName(systemName);
            var paymentMethod = _paymentService.GetPaymentMethodBySystemName(systemName);

            var model         = new PaymentMethodEditModel();
            var providerModel = _pluginMediator.ToProviderModel <IPaymentMethod, ProviderModel>(provider, true);
            var pageTitle     = providerModel.FriendlyName;

            model.SystemName       = providerModel.SystemName;
            model.IconUrl          = providerModel.IconUrl;
            model.FriendlyName     = providerModel.FriendlyName;
            model.Description      = providerModel.Description;
            model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(paymentMethod);

            if (paymentMethod != null)
            {
                model.Id = paymentMethod.Id;
                model.FullDescription        = paymentMethod.FullDescription;
                model.RoundOrderTotalEnabled = paymentMethod.RoundOrderTotalEnabled;
                model.LimitedToStores        = paymentMethod.LimitedToStores;
                model.SelectedRuleSetIds     = paymentMethod.RuleSets.Select(x => x.Id).ToArray();
            }

            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata, languageId, false);
                locale.Description  = _pluginMediator.GetLocalizedDescription(provider.Metadata, languageId, false);

                if (pageTitle.IsEmpty() && languageId == Services.WorkContext.WorkingLanguage.Id)
                {
                    pageTitle = locale.FriendlyName;
                }

                if (paymentMethod != null)
                {
                    locale.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, languageId, false, false);
                }
            });

            ViewBag.Title = pageTitle;

            return(View(model));
        }
Ejemplo n.º 9
0
        private string GetPaymentMethodName(Provider <IPaymentMethod> provider)
        {
            if (provider != null)
            {
                var name = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata);

                if (name.IsEmpty())
                {
                    name = provider.Metadata.FriendlyName;
                }

                if (name.IsEmpty())
                {
                    name = provider.Metadata.SystemName;
                }

                return(name);
            }
            return("");
        }
Ejemplo n.º 10
0
        public ActionResult Edit(string systemName)
        {
            var provider      = _paymentService.LoadPaymentMethodBySystemName(systemName);
            var paymentMethod = _paymentService.GetPaymentMethodBySystemName(systemName);

            var model         = new PaymentMethodEditModel();
            var providerModel = _pluginMediator.ToProviderModel <IPaymentMethod, ProviderModel>(provider, true);
            var pageTitle     = providerModel.FriendlyName;

            model.SystemName   = providerModel.SystemName;
            model.IconUrl      = providerModel.IconUrl;
            model.FriendlyName = providerModel.FriendlyName;
            model.Description  = providerModel.Description;

            AddLocales(_languageService, model.Locales, (locale, languageId) =>
            {
                locale.FriendlyName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata, languageId, false);
                locale.Description  = _pluginMediator.GetLocalizedDescription(provider.Metadata, languageId, false);

                if (pageTitle.IsEmpty() && languageId == Services.WorkContext.WorkingLanguage.Id)
                {
                    pageTitle = locale.FriendlyName;
                }

                if (paymentMethod != null)
                {
                    locale.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, languageId, false, false);
                }
            });

            PreparePaymentMethodEditModel(model, paymentMethod);

            ViewBag.Title = pageTitle;

            return(View(model));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get a select list of all payment methods.
        /// </summary>
        /// <param name="paymentProviders">Payment providers.</param>
        /// <param name="pluginMediator">Plugin mediator.</param>
        /// <param name="selectedMethods">System name of selected methods.</param>
        /// <returns>List of select items</returns>
        public static IList <ExtendedSelectListItem> ToSelectListItems(
            this IEnumerable <Provider <IPaymentMethod> > paymentProviders,
            PluginMediator pluginMediator,
            params string[] selectedMethods)
        {
            var list = new List <ExtendedSelectListItem>();

            foreach (var provider in paymentProviders)
            {
                var systemName = provider.Metadata.SystemName;
                var name       = pluginMediator.GetLocalizedFriendlyName(provider.Metadata);

                if (name.IsEmpty())
                {
                    name = provider.Metadata.FriendlyName;
                }

                if (name.IsEmpty())
                {
                    name = provider.Metadata.SystemName;
                }

                var item = new ExtendedSelectListItem
                {
                    Text     = name.NaIfEmpty(),
                    Value    = systemName,
                    Selected = selectedMethods != null && selectedMethods.Contains(systemName)
                };

                item.CustomProperties.Add("hint", systemName.Replace("SmartStore.", "").Replace("Payments.", ""));

                list.Add(item);
            }

            return(list.OrderBy(x => x.Text).ToList());
        }
Ejemplo n.º 12
0
        private PayPalPlusCheckoutModel.ThirdPartyPaymentMethod GetThirdPartyPaymentMethodModel(
            Provider <IPaymentMethod> provider,
            PayPalPlusPaymentSettings settings,
            Store store)
        {
            var model = new PayPalPlusCheckoutModel.ThirdPartyPaymentMethod();

            try
            {
                model.RedirectUrl = Url.Action("CheckoutReturn", "PayPalPlus", new { area = Plugin.SystemName, systemName = provider.Metadata.SystemName }, store.SslEnabled ? "https" : "http");

                if (provider.Metadata.SystemName == PayPalInstalmentsProvider.SystemName)
                {
                    // "The methodName contains up to 25 characters. All additional characters are truncated."
                    // https://developer.paypal.com/docs/paypal-plus/germany/how-to/integrate-third-party-payments/
                    model.MethodName = T("Plugins.Payments.PayPalInstalments.ShortMethodName");
                }
                else
                {
                    model.MethodName = _pluginMediator.GetLocalizedFriendlyName(provider.Metadata).NullEmpty()
                                       ?? provider.Metadata.FriendlyName.NullEmpty()
                                       ?? provider.Metadata.SystemName;
                }

                model.MethodName = model.MethodName.EmptyNull();

                if (settings.DisplayPaymentMethodDescription)
                {
                    // Not the short description, the full description is intended for frontend.
                    var paymentMethod = _paymentService.GetPaymentMethodBySystemName(provider.Metadata.SystemName);
                    if (paymentMethod != null)
                    {
                        string description = paymentMethod.GetLocalized(x => x.FullDescription);
                        if (description.HasValue())
                        {
                            description = HtmlUtils.ConvertHtmlToPlainText(description);
                            description = HtmlUtils.StripTags(HttpUtility.HtmlDecode(description));

                            if (description.HasValue())
                            {
                                model.Description = description.EncodeJsString();
                            }
                        }
                    }
                }
            }
            catch { }

            try
            {
                if (settings.DisplayPaymentMethodLogo && provider.Metadata.PluginDescriptor != null && store.SslEnabled)
                {
                    // Special case PayPal instalments.
                    if (provider.Metadata.SystemName == PayPalInstalmentsProvider.SystemName && model.ImageUrl.IsEmpty())
                    {
                        var uri = new UriBuilder(Uri.UriSchemeHttps, Request.Url.Host, -1, "Plugins/SmartStore.PayPal/Content/instalments-sm.png");
                        model.ImageUrl = uri.ToString();
                    }
                    else
                    {
                        var brandImageUrl = _pluginMediator.GetBrandImageUrl(provider.Metadata);
                        if (brandImageUrl.HasValue())
                        {
                            if (brandImageUrl.StartsWith("~"))
                            {
                                brandImageUrl = brandImageUrl.Substring(1);
                            }

                            var uri = new UriBuilder(Uri.UriSchemeHttps, Request.Url.Host, -1, brandImageUrl);
                            model.ImageUrl = uri.ToString();
                        }
                    }
                }
            }
            catch { }

            return(model);
        }
Ejemplo n.º 13
0
        protected CheckoutPaymentMethodModel PreparePaymentMethodModel(IList <OrganizedShoppingCartItem> cart)
        {
            var model = new CheckoutPaymentMethodModel();

            // was shipping skipped
            var shippingOptions = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress, "", _storeContext.CurrentStore.Id).ShippingOptions;

            if (!cart.RequiresShipping() || (shippingOptions.Count <= 1 && _shippingSettings.SkipShippingIfSingleOption))
            {
                model.SkippedSelectShipping = true;
            }

            var paymentTypes = new PaymentMethodType[] { PaymentMethodType.Standard, PaymentMethodType.Redirection, PaymentMethodType.StandardAndRedirection };

            var boundPaymentMethods = _paymentService
                                      .LoadActivePaymentMethods(_workContext.CurrentCustomer, cart, _storeContext.CurrentStore.Id, paymentTypes)
                                      .ToList();

            var allPaymentMethods = _paymentService.GetAllPaymentMethods();

            foreach (var pm in boundPaymentMethods)
            {
                if (cart.IsRecurring() && pm.Value.RecurringPaymentType == RecurringPaymentType.NotSupported)
                {
                    continue;
                }

                var paymentMethod = allPaymentMethods.FirstOrDefault(x => x.PaymentMethodSystemName.IsCaseInsensitiveEqual(pm.Metadata.SystemName));

                var pmModel = new CheckoutPaymentMethodModel.PaymentMethodModel
                {
                    Name                    = _pluginMediator.GetLocalizedFriendlyName(pm.Metadata),
                    Description             = _pluginMediator.GetLocalizedDescription(pm.Metadata),
                    PaymentMethodSystemName = pm.Metadata.SystemName,
                    PaymentInfoRoute        = pm.Value.GetPaymentInfoRoute(),
                    RequiresInteraction     = pm.Value.RequiresInteraction
                };

                if (paymentMethod != null)
                {
                    pmModel.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, _workContext.WorkingLanguage.Id);
                }

                pmModel.BrandUrl = _pluginMediator.GetBrandImageUrl(pm.Metadata);

                // payment method additional fee
                decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, pm.Metadata.SystemName);
                decimal rateBase = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, _workContext.CurrentCustomer);
                decimal rate     = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);

                if (rate != decimal.Zero)
                {
                    pmModel.Fee = _priceFormatter.FormatPaymentMethodAdditionalFee(rate, true);
                }

                model.PaymentMethods.Add(pmModel);
            }

            // find a selected (previously) payment method
            var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute <string>(
                SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id);

            bool selected = false;

            if (selectedPaymentMethodSystemName.HasValue())
            {
                var paymentMethodToSelect = model.PaymentMethods.Find(pm => pm.PaymentMethodSystemName.IsCaseInsensitiveEqual(selectedPaymentMethodSystemName));
                if (paymentMethodToSelect != null)
                {
                    paymentMethodToSelect.Selected = true;
                    selected = true;
                }
            }

            // if no option has been selected, let's do it for the first one
            if (!selected)
            {
                var paymentMethodToSelect = model.PaymentMethods.FirstOrDefault();
                if (paymentMethodToSelect != null)
                {
                    paymentMethodToSelect.Selected = true;
                }
            }

            return(model);
        }
Ejemplo n.º 14
0
        private void PrepareDiscountModel(DiscountModel model, Discount discount)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var language = _services.WorkContext.WorkingLanguage;

            model.PrimaryStoreCurrencyCode = _services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode;
            model.AvailableDiscountRequirementRules.Add(
                new SelectListItem {
                Text = _services.Localization.GetResource("Admin.Promotions.Discounts.Requirements.DiscountRequirementType.Select"), Value = ""
            }
                );

            var discountRules = _discountService.LoadAllDiscountRequirementRules();

            foreach (var discountRule in discountRules)
            {
                model.AvailableDiscountRequirementRules.Add(new SelectListItem
                {
                    Text  = _pluginMediator.GetLocalizedFriendlyName(discountRule.Metadata),
                    Value = discountRule.Metadata.SystemName
                });
            }

            if (discount != null)
            {
                // applied to categories
                model.AppliedToCategoryModels = discount.AppliedToCategories
                                                .Where(x => x != null && !x.Deleted)
                                                .Select(x => new DiscountModel.AppliedToCategoryModel {
                    CategoryId = x.Id, Name = x.GetLocalized(y => y.Name, language.Id)
                })
                                                .ToList();

                // applied to manufacturers
                model.AppliedToManufacturerModels = discount.AppliedToManufacturers
                                                    .Where(x => x != null && !x.Deleted)
                                                    .Select(x => new DiscountModel.AppliedToManufacturerModel {
                    ManufacturerId = x.Id, ManufacturerName = x.GetLocalized(y => y.Name, language.Id)
                })
                                                    .ToList();

                // applied to products
                model.AppliedToProductModels = discount.AppliedToProducts
                                               .Where(x => x != null && !x.Deleted)
                                               .Select(x => new DiscountModel.AppliedToProductModel {
                    ProductId = x.Id, ProductName = x.GetLocalized(y => y.Name, language.Id)
                })
                                               .ToList();

                // requirements
                foreach (var dr in discount.DiscountRequirements.OrderBy(dr => dr.Id))
                {
                    var drr = _discountService.LoadDiscountRequirementRuleBySystemName(dr.DiscountRequirementRuleSystemName);
                    if (drr != null)
                    {
                        model.DiscountRequirementMetaInfos.Add(new DiscountModel.DiscountRequirementMetaInfo
                        {
                            DiscountRequirementId = dr.Id,
                            RuleName         = _pluginMediator.GetLocalizedFriendlyName(drr.Metadata),
                            ConfigurationUrl = GetRequirementUrlInternal(drr.Value, discount, dr.Id)
                        });
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private void PrepareDiscountModel(DiscountModel model, Discount discount)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            model.PrimaryStoreCurrencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
            model.AvailableDiscountRequirementRules.Add(new SelectListItem()
            {
                Text = _localizationService.GetResource("Admin.Promotions.Discounts.Requirements.DiscountRequirementType.Select"), Value = ""
            });
            var discountRules = _discountService.LoadAllDiscountRequirementRules();

            foreach (var discountRule in discountRules)
            {
                model.AvailableDiscountRequirementRules.Add(new SelectListItem()
                {
                    Text  = _pluginMediator.GetLocalizedFriendlyName(discountRule.Metadata),
                    Value = discountRule.Metadata.SystemName
                });
            }

            if (discount != null)
            {
                //applied to categories
                foreach (var category in discount.AppliedToCategories)
                {
                    if (category != null && !category.Deleted)
                    {
                        model.AppliedToCategoryModels.Add(new DiscountModel.AppliedToCategoryModel()
                        {
                            CategoryId = category.Id,
                            Name       = category.Name
                        });
                    }
                }

                //applied to products
                foreach (var product in discount.AppliedToProducts)
                {
                    if (product != null && !product.Deleted)
                    {
                        var appliedToProductModel = new DiscountModel.AppliedToProductModel()
                        {
                            ProductId   = product.Id,
                            ProductName = product.Name
                        };
                        model.AppliedToProductModels.Add(appliedToProductModel);
                    }
                }

                //requirements
                foreach (var dr in discount.DiscountRequirements.OrderBy(dr => dr.Id))
                {
                    var drr = _discountService.LoadDiscountRequirementRuleBySystemName(dr.DiscountRequirementRuleSystemName);
                    if (drr != null)
                    {
                        model.DiscountRequirementMetaInfos.Add(new DiscountModel.DiscountRequirementMetaInfo()
                        {
                            DiscountRequirementId = dr.Id,
                            RuleName         = _pluginMediator.GetLocalizedFriendlyName(drr.Metadata),
                            ConfigurationUrl = GetRequirementUrlInternal(drr.Value, discount, dr.Id)
                        });
                    }
                }
            }
        }
Ejemplo n.º 16
0
        protected OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            var store = _storeService.GetStoreById(order.StoreId) ?? _services.StoreContext.CurrentStore;

            var orderSettings       = _services.Settings.LoadSetting <OrderSettings>(store.Id);
            var catalogSettings     = _services.Settings.LoadSetting <CatalogSettings>(store.Id);
            var taxSettings         = _services.Settings.LoadSetting <TaxSettings>(store.Id);
            var pdfSettings         = _services.Settings.LoadSetting <PdfSettings>(store.Id);
            var addressSettings     = _services.Settings.LoadSetting <AddressSettings>(store.Id);
            var companyInfoSettings = _services.Settings.LoadSetting <CompanyInformationSettings>(store.Id);

            var model = new OrderDetailsModel();

            model.MerchantCompanyInfo = companyInfoSettings;
            model.Id                     = order.Id;
            model.StoreId                = order.StoreId;
            model.OrderNumber            = order.GetOrderNumber();
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            model.IsReOrderAllowed       = orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.DisplayPdfInvoice      = pdfSettings.Enabled;
            model.RenderOrderNotes       = pdfSettings.RenderOrderNotes;

            //shipping info
            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable = true;
                model.ShippingAddress.PrepareModel(order.ShippingAddress, false, addressSettings);
                model.ShippingMethod = order.ShippingMethod;


                //shipments (only already shipped)
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel()
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };
                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }
                    model.Shipments.Add(shipmentModel);
                }
            }


            //billing info
            model.BillingAddress.PrepareModel(order.BillingAddress, false, addressSettings);

            //VAT number
            model.VatNumber = order.VatNumber;

            //payment method
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod = paymentMethod != null?_pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : order.PaymentMethodSystemName;

            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);

            //purchase order number (we have to find a better to inject this information because it's related to a certain plugin)
            if (paymentMethod != null && paymentMethod.Metadata.SystemName.Equals("Payments.PurchaseOrder", StringComparison.InvariantCultureIgnoreCase))
            {
                model.DisplayPurchaseOrderNumber = true;
                model.PurchaseOrderNumber        = order.PurchaseOrderNumber;
            }


            // totals
            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                //order subtotal
                var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, false, false);

                //discount (applied to order subtotal)
                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true,
                                                                              order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, false, false);
                }

                //order shipping
                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, false, false);
                //payment method additional fee
                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, false, false);
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                //order subtotal
                var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, true, false);

                //discount (applied to order subtotal)
                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true,
                                                                              order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, true, false);
                }

                //order shipping
                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, true, false);

                //payment method additional fee
                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _services.WorkContext.WorkingLanguage, true, false);
                }
            }
            break;
            }

            //tax
            bool displayTax      = true;
            bool displayTaxRates = true;

            if (taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
                    //TODO pass languageId to _priceFormatter.FormatPrice
                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage);
                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        var rate     = _priceFormatter.FormatTaxRate(tr.Key);
                        var labelKey = "ShoppingCart.Totals.TaxRateLine" + (_services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "Incl" : "Excl");
                        model.TaxRates.Add(new OrderDetailsModel.TaxRate()
                        {
                            Rate  = rate,
                            Label = T(labelKey).Text.FormatCurrent(rate),
                            //TODO pass languageId to _priceFormatter.FormatPrice
                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage),
                        });
                    }
                }
            }
            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;


            //discount (applied to order total)
            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage);
            }


            //gift cards
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                model.GiftCards.Add(new OrderDetailsModel.GiftCard()
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage),
                });
            }

            //reward points
            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage);
            }

            //total
            var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, _services.WorkContext.WorkingLanguage);

            //checkout attributes
            model.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable(HtmlUtils.ConvertHtmlToPlainText(order.CheckoutAttributeDescription));

            //order notes
            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                model.OrderNotes.Add(new OrderDetailsModel.OrderNote()
                {
                    Note      = orderNote.FormatOrderNoteText(),
                    CreatedOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc)
                });
            }


            //purchased products
            model.ShowSku = catalogSettings.ShowProductSku;
            var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null);

            foreach (var orderItem in orderItems)
            {
                var orderItemModel = PrepareOrderItemModel(order, orderItem);

                model.Items.Add(orderItemModel);
            }

            return(model);
        }
        public ActionResult List(bool liveRates = false)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManageCurrencies))
            {
                return(AccessDeniedView());
            }

            var language      = _services.WorkContext.WorkingLanguage;
            var allCurrencies = _currencyService.GetAllCurrencies(true)
                                .ToDictionarySafe(x => x.CurrencyCode.EmptyNull().ToUpper(), x => x);

            var models = allCurrencies.Select(x => CreateCurrencyListModel(x.Value)).ToList();

            if (liveRates)
            {
                try
                {
                    var primaryExchangeCurrency = _services.StoreContext.CurrentStore.PrimaryExchangeRateCurrency;
                    if (primaryExchangeCurrency == null)
                    {
                        throw new SmartException(T("Admin.System.Warnings.ExchangeCurrency.NotSet"));
                    }

                    var rates = _currencyService.GetCurrencyLiveRates(primaryExchangeCurrency.CurrencyCode);

                    // get localized name of currencies
                    var currencyNames = allCurrencies.ToDictionarySafe(
                        x => x.Key,
                        x => x.Value.GetLocalized(y => y.Name, language.Id, true, false)
                        );

                    // fallback to english name where no localized currency name exists
                    foreach (var info in CultureInfo.GetCultures(CultureTypes.AllCultures).Where(x => !x.IsNeutralCulture))
                    {
                        try
                        {
                            var region = new RegionInfo(info.LCID);

                            if (!currencyNames.ContainsKey(region.ISOCurrencySymbol))
                            {
                                currencyNames.Add(region.ISOCurrencySymbol, region.CurrencyEnglishName);
                            }
                        }
                        catch { }
                    }

                    // provide rate with currency name and whether it is available in store
                    rates.Each(x =>
                    {
                        x.IsStoreCurrency = allCurrencies.ContainsKey(x.CurrencyCode);

                        if (x.Name.IsEmpty() && currencyNames.ContainsKey(x.CurrencyCode))
                        {
                            x.Name = currencyNames[x.CurrencyCode];
                        }
                    });

                    ViewBag.Rates = rates;
                }
                catch (Exception exception)
                {
                    NotifyError(exception, false);
                }
            }

            ViewBag.AutoUpdateEnabled     = _currencySettings.AutoUpdateEnabled;
            ViewBag.ExchangeRateProviders = new List <SelectListItem>();

            foreach (var erp in _currencyService.LoadAllExchangeRateProviders())
            {
                ViewBag.ExchangeRateProviders.Add(new SelectListItem
                {
                    Text     = _pluginMediator.GetLocalizedFriendlyName(erp.Metadata),
                    Value    = erp.Metadata.SystemName,
                    Selected = erp.Metadata.SystemName.Equals(_currencySettings.ActiveExchangeRateProviderSystemName, StringComparison.InvariantCultureIgnoreCase)
                });
            }

            return(View(new GridModel <CurrencyModel>
            {
                Data = models,
                Total = models.Count()
            }));
        }
Ejemplo n.º 18
0
        protected CheckoutPaymentMethodModel PreparePaymentMethodModel(IList<OrganizedShoppingCartItem> cart)
        {
            var model = new CheckoutPaymentMethodModel();

            //reward points
            if (_rewardPointsSettings.Enabled && !cart.IsRecurring())
            {
                int rewardPointsBalance = _workContext.CurrentCustomer.GetRewardPointsBalance();
                decimal rewardPointsAmountBase = _orderTotalCalculationService.ConvertRewardPointsToAmount(rewardPointsBalance);
                decimal rewardPointsAmount = _currencyService.ConvertFromPrimaryStoreCurrency(rewardPointsAmountBase, _workContext.WorkingCurrency);
                if (rewardPointsAmount > decimal.Zero)
                {
                    model.DisplayRewardPoints = true;
                    model.RewardPointsAmount = _priceFormatter.FormatPrice(rewardPointsAmount, true, false);
                    model.RewardPointsBalance = rewardPointsBalance;
                }
            }

            var boundPaymentMethods = _paymentService
                .LoadActivePaymentMethods(_workContext.CurrentCustomer.Id, _storeContext.CurrentStore.Id)
                .Where(pm => pm.Value.PaymentMethodType == PaymentMethodType.Standard || pm.Value.PaymentMethodType == PaymentMethodType.Redirection ||
                    pm.Value.PaymentMethodType == PaymentMethodType.StandardAndRedirection)
                .ToList();

            foreach (var pm in boundPaymentMethods)
            {
                if (cart.IsRecurring() && pm.Value.RecurringPaymentType == RecurringPaymentType.NotSupported)
                    continue;

                var pmModel = new CheckoutPaymentMethodModel.PaymentMethodModel()
                {
                    Name = _pluginMediator.GetLocalizedFriendlyName(pm.Metadata),
                    Description = _pluginMediator.GetLocalizedDescription(pm.Metadata),
                    PaymentMethodSystemName = pm.Metadata.SystemName,
                    PaymentInfoRoute = pm.Value.GetPaymentInfoRoute(),
                    RequiresInteraction = pm.Value.RequiresInteraction
                };

                pmModel.BrandUrl = _pluginMediator.GetBrandImageUrl(pm.Metadata);

                // payment method additional fee
                decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, pm.Metadata.SystemName);
                decimal rateBase = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, _workContext.CurrentCustomer);
                decimal rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);

                if (rate != decimal.Zero)
                    pmModel.Fee = _priceFormatter.FormatPaymentMethodAdditionalFee(rate, true);

                model.PaymentMethods.Add(pmModel);
            }

            // find a selected (previously) payment method
            var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
                 SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id);

            bool selected = false;
            if (selectedPaymentMethodSystemName.HasValue())
            {
                var paymentMethodToSelect = model.PaymentMethods.Find(pm => pm.PaymentMethodSystemName.IsCaseInsensitiveEqual(selectedPaymentMethodSystemName));
                if (paymentMethodToSelect != null)
                {
                    paymentMethodToSelect.Selected = true;
                    selected = true;
                }
            }

            // if no option has been selected, let's do it for the first one
            if (!selected)
            {
                var paymentMethodToSelect = model.PaymentMethods.FirstOrDefault();
                if (paymentMethodToSelect != null)
                    paymentMethodToSelect.Selected = true;
            }

            return model;
        }
Ejemplo n.º 19
0
        public OrderDetailsModel PrepareOrderDetailsModel(Order order)
        {
            Guard.NotNull(order, nameof(order));

            var store    = _services.StoreService.GetStoreById(order.StoreId) ?? _services.StoreContext.CurrentStore;
            var language = _services.WorkContext.WorkingLanguage;

            var orderSettings        = _services.Settings.LoadSetting <OrderSettings>(store.Id);
            var catalogSettings      = _services.Settings.LoadSetting <CatalogSettings>(store.Id);
            var taxSettings          = _services.Settings.LoadSetting <TaxSettings>(store.Id);
            var pdfSettings          = _services.Settings.LoadSetting <PdfSettings>(store.Id);
            var addressSettings      = _services.Settings.LoadSetting <AddressSettings>(store.Id);
            var companyInfoSettings  = _services.Settings.LoadSetting <CompanyInformationSettings>(store.Id);
            var shoppingCartSettings = _services.Settings.LoadSetting <ShoppingCartSettings>(store.Id);
            var mediaSettings        = _services.Settings.LoadSetting <MediaSettings>(store.Id);

            var model = new OrderDetailsModel();

            model.MerchantCompanyInfo = companyInfoSettings;
            model.Id                     = order.Id;
            model.StoreId                = order.StoreId;
            model.CustomerLanguageId     = order.CustomerLanguageId;
            model.CustomerComment        = order.CustomerOrderComment;
            model.OrderNumber            = order.GetOrderNumber();
            model.CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);
            model.OrderStatus            = order.OrderStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            model.IsReOrderAllowed       = orderSettings.IsReOrderAllowed;
            model.IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order);
            model.DisplayPdfInvoice      = pdfSettings.Enabled;
            model.RenderOrderNotes       = pdfSettings.RenderOrderNotes;

            // Shipping info.
            model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_services.Localization, _services.WorkContext);
            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable = true;
                model.ShippingAddress.PrepareModel(order.ShippingAddress, false, addressSettings);
                model.ShippingMethod = order.ShippingMethod;


                // Shipments (only already shipped).
                var shipments = order.Shipments.Where(x => x.ShippedDateUtc.HasValue).OrderBy(x => x.CreatedOnUtc).ToList();
                foreach (var shipment in shipments)
                {
                    var shipmentModel = new OrderDetailsModel.ShipmentBriefModel
                    {
                        Id             = shipment.Id,
                        TrackingNumber = shipment.TrackingNumber,
                    };

                    if (shipment.ShippedDateUtc.HasValue)
                    {
                        shipmentModel.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }

                    model.Shipments.Add(shipmentModel);
                }
            }

            model.BillingAddress.PrepareModel(order.BillingAddress, false, addressSettings);
            model.VatNumber = order.VatNumber;

            // Payment method.
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);

            model.PaymentMethod = paymentMethod != null?_pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : order.PaymentMethodSystemName;

            model.CanRePostProcessPayment = _paymentService.CanRePostProcessPayment(order);

            // Purchase order number (we have to find a better to inject this information because it's related to a certain plugin).
            if (paymentMethod != null && paymentMethod.Metadata.SystemName.Equals("SmartStore.PurchaseOrderNumber", StringComparison.InvariantCultureIgnoreCase))
            {
                model.DisplayPurchaseOrderNumber = true;
                model.PurchaseOrderNumber        = order.PurchaseOrderNumber;
            }

            // Totals.
            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                // Order subtotal.
                var orderSubtotalExclTax = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalExclTax, true, order.CustomerCurrencyCode, language, false, false);

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountExclTax = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTax > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTax, true, order.CustomerCurrencyCode, language, false, false);
                }

                // Order shipping.
                var orderShippingExclTax = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingExclTax, true, order.CustomerCurrencyCode, language, false, false);

                // Payment method additional fee.
                var paymentMethodAdditionalFeeExclTax = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTax != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTax, true, order.CustomerCurrencyCode,
                                                                                                        language, false, false);
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                // Order subtotal.
                var orderSubtotalInclTax = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = _priceFormatter.FormatPrice(orderSubtotalInclTax, true, order.CustomerCurrencyCode, language, true, false);

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountInclTax = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTax > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTax, true, order.CustomerCurrencyCode, language, true, false);
                }

                // Order shipping.
                var orderShippingInclTax = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = _priceFormatter.FormatShippingPrice(orderShippingInclTax, true, order.CustomerCurrencyCode, language, true, false);

                // Payment method additional fee.
                var paymentMethodAdditionalFeeInclTax = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTax != decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTax, true, order.CustomerCurrencyCode,
                                                                                                        language, true, false);
                }
            }
            break;
            }

            // Tax.
            var displayTax      = true;
            var displayTaxRates = true;

            if (taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                displayTax      = false;
                displayTaxRates = false;
            }
            else
            {
                if (order.OrderTax == 0 && taxSettings.HideZeroTax)
                {
                    displayTax      = false;
                    displayTaxRates = false;
                }
                else
                {
                    displayTaxRates = taxSettings.DisplayTaxRates && order.TaxRatesDictionary.Count > 0;
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);

                    model.Tax = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        var rate = _priceFormatter.FormatTaxRate(tr.Key);
                        //var labelKey = "ShoppingCart.Totals.TaxRateLine" + (_services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "Incl" : "Excl");
                        var labelKey = (_services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "ShoppingCart.Totals.TaxRateLineIncl" : "ShoppingCart.Totals.TaxRateLineExcl");

                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate  = rate,
                            Label = T(labelKey).Text.FormatCurrent(rate),
                            Value = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, language),
                        });
                    }
                }
            }

            model.DisplayTaxRates = displayTaxRates;
            model.DisplayTax      = displayTax;


            // Discount (applied to order total).
            var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
            }

            // Gift cards.
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                var remainingAmountBase = gcuh.GiftCard.GetGiftCardRemainingAmount();
                var remainingAmount     = _currencyService.ConvertCurrency(remainingAmountBase, order.CurrencyRate);

                var gcModel = new OrderDetailsModel.GiftCard
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, language),
                    Remaining  = _priceFormatter.FormatPrice(remainingAmount, true, false)
                };

                model.GiftCards.Add(gcModel);
            }

            // Reward points         .
            if (order.RedeemedRewardPointsEntry != null)
            {
                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)),
                                                                               true, order.CustomerCurrencyCode, false, language);
            }

            // Credit balance.
            if (order.CreditBalance > decimal.Zero)
            {
                var convertedCreditBalance = _currencyService.ConvertCurrency(order.CreditBalance, order.CurrencyRate);
                model.CreditBalance = _priceFormatter.FormatPrice(-convertedCreditBalance, true, order.CustomerCurrencyCode, false, language);
            }

            // Total.
            var roundingAmount = decimal.Zero;
            var orderTotal     = order.GetOrderTotalInCustomerCurrency(_currencyService, _paymentService, out roundingAmount);

            model.OrderTotal = _priceFormatter.FormatPrice(orderTotal, true, order.CustomerCurrencyCode, false, language);

            if (roundingAmount != decimal.Zero)
            {
                model.OrderTotalRounding = _priceFormatter.FormatPrice(roundingAmount, true, order.CustomerCurrencyCode, false, language);
            }

            // Checkout attributes.
            model.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable(HtmlUtils.ConvertHtmlToPlainText(order.CheckoutAttributeDescription));

            // Order notes.
            foreach (var orderNote in order.OrderNotes
                     .Where(on => on.DisplayToCustomer)
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                var createdOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc);

                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Note              = orderNote.FormatOrderNoteText(),
                    CreatedOn         = createdOn,
                    FriendlyCreatedOn = createdOn.RelativeFormat(false, "f")
                });
            }

            // Purchased products.
            model.ShowSku                 = catalogSettings.ShowProductSku;
            model.ShowProductImages       = shoppingCartSettings.ShowProductImagesOnShoppingCart;
            model.ShowProductBundleImages = shoppingCartSettings.ShowProductBundleImagesOnShoppingCart;
            model.BundleThumbSize         = mediaSettings.CartThumbBundleItemPictureSize;

            var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null);

            foreach (var orderItem in orderItems)
            {
                var orderItemModel = PrepareOrderItemModel(
                    order,
                    orderItem,
                    catalogSettings,
                    shoppingCartSettings,
                    mediaSettings);

                model.Items.Add(orderItemModel);
            }

            return(model);
        }
Ejemplo n.º 20
0
        public ActionResult List(bool liveRates = false)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManageCurrencies))
            {
                return(AccessDeniedView());
            }

            var store  = _services.StoreContext.CurrentStore;
            var models = _currencyService.GetAllCurrencies(true).Select(x => x.ToModel()).ToList();

            foreach (var model in models)
            {
                model.IsPrimaryStoreCurrency        = (store.PrimaryStoreCurrencyId == model.Id);
                model.IsPrimaryExchangeRateCurrency = (store.PrimaryExchangeRateCurrencyId == model.Id);
            }

            //var allStores = _services.StoreService.GetAllStores();
            //foreach (var model in models)
            //{
            //	var storeNames = allStores.Where(x => x.PrimaryStoreCurrencyId == model.Id).Select(x => x.Name).ToList();

            //	model.IsPrimaryStoreCurrency = string.Join("<br />", storeNames);

            //	storeNames = allStores.Where(x => x.PrimaryExchangeRateCurrencyId == model.Id).Select(x => x.Name).ToList();

            //	model.IsPrimaryExchangeRateCurrency = string.Join("<br />", storeNames);
            //}

            if (liveRates)
            {
                try
                {
                    var primaryExchangeCurrency = _services.StoreContext.CurrentStore.PrimaryExchangeRateCurrency;
                    if (primaryExchangeCurrency == null)
                    {
                        throw new SmartException("Primary exchange rate currency is not set");
                    }

                    ViewBag.Rates = _currencyService.GetCurrencyLiveRates(primaryExchangeCurrency.CurrencyCode);
                }
                catch (Exception exc)
                {
                    NotifyError(exc, false);
                }
            }

            ViewBag.ExchangeRateProviders = new List <SelectListItem>();

            foreach (var erp in _currencyService.LoadAllExchangeRateProviders())
            {
                ViewBag.ExchangeRateProviders.Add(new SelectListItem
                {
                    Text     = _pluginMediator.GetLocalizedFriendlyName(erp.Metadata),
                    Value    = erp.Metadata.SystemName,
                    Selected = erp.Metadata.SystemName.Equals(_currencySettings.ActiveExchangeRateProviderSystemName, StringComparison.InvariantCultureIgnoreCase)
                });
            }

            ViewBag.AutoUpdateEnabled = _currencySettings.AutoUpdateEnabled;

            var gridModel = new GridModel <CurrencyModel>
            {
                Data  = models,
                Total = models.Count()
            };

            return(View(gridModel));
        }