示例#1
0
        private PayPalPlusCheckoutModel.ThirdPartyPaymentMethod GetThirdPartyPaymentMethodModel(
            Provider <IPaymentMethod> provider,
            PayPalPlusPaymentSettings settings,
            Store store)
        {
            var model = new PayPalPlusCheckoutModel.ThirdPartyPaymentMethod();

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

            try
            {
                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)
                {
                    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);
        }
        public ActionResult GetUserAgreement(int productId, bool?asPlainText)
        {
            var product = _productService.GetProductById(productId);

            if (product == null)
            {
                return(Content(T("Products.NotFound", productId)));
            }

            if (!product.IsDownload || !product.HasUserAgreement || product.UserAgreementText.IsEmpty())
            {
                return(Content(T("DownloadableProducts.HasNoUserAgreement")));
            }

            if (asPlainText ?? false)
            {
                var agreement = HtmlUtils.ConvertHtmlToPlainText(product.UserAgreementText);
                agreement = HtmlUtils.StripTags(HttpUtility.HtmlDecode(agreement));

                return(Content(agreement));
            }

            return(Content(product.UserAgreementText));
        }
        public async Task <IActionResult> GetUserAgreement(int productId, bool?asPlainText)
        {
            var product = await _db.Products.FindByIdAsync(productId, false);

            if (product == null)
            {
                return(Content(T("Products.NotFound", productId)));
            }

            if (!product.IsDownload || !product.HasUserAgreement || product.UserAgreementText.IsEmpty())
            {
                return(Content(T("DownloadableProducts.HasNoUserAgreement")));
            }

            if (asPlainText ?? false)
            {
                var agreement = HtmlUtils.ConvertHtmlToPlainText(product.UserAgreementText);
                agreement = HtmlUtils.StripTags(HttpUtility.HtmlDecode(agreement));

                return(Content(agreement));
            }

            return(Content(product.UserAgreementText));
        }
示例#4
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);
        }
示例#5
0
        protected virtual async Task <object> CreateModelPartAsync(Order part, MessageContext messageContext)
        {
            Guard.NotNull(messageContext, nameof(messageContext));
            Guard.NotNull(part, nameof(part));

            var allow = new HashSet <string>
            {
                nameof(part.Id),
                nameof(part.OrderNumber),
                nameof(part.OrderGuid),
                nameof(part.StoreId),
                nameof(part.OrderStatus),
                nameof(part.PaymentStatus),
                nameof(part.ShippingStatus),
                nameof(part.CustomerTaxDisplayType),
                nameof(part.TaxRatesDictionary),
                nameof(part.VatNumber),
                nameof(part.AffiliateId),
                nameof(part.CustomerIp),
                nameof(part.CardType),
                nameof(part.CardName),
                nameof(part.MaskedCreditCardNumber),
                nameof(part.DirectDebitAccountHolder),
                nameof(part.DirectDebitBankCode), // TODO: (mc) Liquid > Bank data (?)
                nameof(part.PurchaseOrderNumber),
                nameof(part.ShippingMethod),
                nameof(part.PaymentMethodSystemName),
                nameof(part.ShippingRateComputationMethodSystemName)
                // TODO: (mc) Liquid > More whitelisting?
            };

            var m = new HybridExpando(part, allow, MemberOptMethod.Allow);
            var d = m as dynamic;

            d.ID      = part.Id;
            d.Billing = await CreateModelPartAsync(part.BillingAddress, messageContext);

            if (part.ShippingAddress != null)
            {
                d.Shipping = part.ShippingAddress == part.BillingAddress ? null : await CreateModelPartAsync(part.ShippingAddress, messageContext);
            }
            d.CustomerEmail   = part.BillingAddress.Email.NullEmpty();
            d.CustomerComment = part.CustomerOrderComment.NullEmpty();
            d.Disclaimer      = GetTopicAsync("Disclaimer", messageContext);
            d.ConditionsOfUse = GetTopicAsync("ConditionsOfUse", messageContext);
            d.Status          = part.OrderStatus.GetLocalizedEnum(messageContext.Language.Id);
            d.CreatedOn       = ToUserDate(part.CreatedOnUtc, messageContext);
            d.PaidOn          = ToUserDate(part.PaidDateUtc, messageContext);

            // TODO: (mh) (core) Uncomment when available.
            // Payment method
            var paymentMethodName = part.PaymentMethodSystemName;

            //var paymentMethod = _services.Resolve<IProviderManager>().GetProvider<IPaymentMethod>(part.PaymentMethodSystemName);
            //if (paymentMethod != null)
            //{
            //    paymentMethodName = GetLocalizedValue(messageContext, paymentMethod.Metadata, nameof(paymentMethod.Metadata.FriendlyName), x => x.FriendlyName);
            //}
            d.PaymentMethod = paymentMethodName.NullEmpty();

            d.Url = part.Customer != null && !part.Customer.IsGuest()
                ? BuildActionUrl("Details", "Order", new { id = part.Id, area = "" }, messageContext)
                : null;

            // Overrides
            // TODO: (mh) (core) Uncomment when available.
            //m.Properties["OrderNumber"] = part.GetOrderNumber().NullEmpty();
            m.Properties["AcceptThirdPartyEmailHandOver"] = GetBoolResource(part.AcceptThirdPartyEmailHandOver, messageContext);

            // Items, Totals & Co.
            d.Items  = part.OrderItems.Where(x => x.Product != null).Select(async x => await CreateModelPartAsync(x, messageContext)).ToList();
            d.Totals = await CreateOrderTotalsPartAsync(part, messageContext);

            // Checkout Attributes
            if (part.CheckoutAttributeDescription.HasValue())
            {
                d.CheckoutAttributes = HtmlUtils.ConvertPlainTextToTable(HtmlUtils.ConvertHtmlToPlainText(part.CheckoutAttributeDescription)).NullEmpty();
            }

            await PublishModelPartCreatedEventAsync(part, m);

            return(m);
        }
        public string BuildProductDescription(string productName, string shortDescription, string fullDescription, string manufacturer, Func <string, string> updateResult = null)
        {
            if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual(NotSpecified))
            {
                return("");
            }

            string description = "";

            if (BaseSettings.BuildDescription.IsEmpty())
            {
                description = fullDescription;

                if (description.IsEmpty())
                {
                    description = shortDescription;
                }
                if (description.IsEmpty())
                {
                    description = productName;
                }
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("short"))
            {
                description = shortDescription;
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("long"))
            {
                description = fullDescription;
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("titleAndShort"))
            {
                description = productName.Grow(shortDescription, " ");
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("titleAndLong"))
            {
                description = productName.Grow(fullDescription, " ");
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("manuAndTitleAndShort"))
            {
                description = manufacturer.Grow(productName, " ");
                description = description.Grow(shortDescription, " ");
            }
            else if (BaseSettings.BuildDescription.IsCaseInsensitiveEqual("manuAndTitleAndLong"))
            {
                description = manufacturer.Grow(productName, " ");
                description = description.Grow(fullDescription, " ");
            }

            if (updateResult != null)
            {
                description = updateResult(description);
            }

            try
            {
                if (BaseSettings.DescriptionToPlainText)
                {
                    //Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
                    //description = HttpUtility.HtmlDecode(reg.Replace(description, ""));

                    description = HtmlUtils.ConvertHtmlToPlainText(description);
                    description = HtmlUtils.StripTags(HttpUtility.HtmlDecode(description));

                    description = RemoveInvalidFeedChars(description, false);
                }
                else
                {
                    description = RemoveInvalidFeedChars(description, true);
                }
            }
            catch (Exception exc)
            {
                exc.Dump();
            }

            return(description);
        }
示例#7
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);
        }
示例#8
0
        public async Task <OrderDetailsModel> PrepareOrderDetailsModelAsync(Order order)
        {
            Guard.NotNull(order, nameof(order));

            var settingFactory = _services.SettingFactory;
            var store          = await _db.Stores.FindByIdAsync(order.StoreId, false) ?? _services.StoreContext.CurrentStore;

            var language = _services.WorkContext.WorkingLanguage;

            var orderSettings = await settingFactory.LoadSettingsAsync <OrderSettings>(store.Id);

            var catalogSettings = await settingFactory.LoadSettingsAsync <CatalogSettings>(store.Id);

            var taxSettings = await settingFactory.LoadSettingsAsync <TaxSettings>(store.Id);

            var pdfSettings = await settingFactory.LoadSettingsAsync <PdfSettings>(store.Id);

            var addressSettings = await settingFactory.LoadSettingsAsync <AddressSettings>(store.Id);

            var companyInfoSettings = await settingFactory.LoadSettingsAsync <CompanyInformationSettings>(store.Id);

            var shoppingCartSettings = await settingFactory.LoadSettingsAsync <ShoppingCartSettings>(store.Id);

            var mediaSettings = await settingFactory.LoadSettingsAsync <MediaSettings>(store.Id);

            var model = new OrderDetailsModel
            {
                Id                     = order.Id,
                StoreId                = order.StoreId,
                CustomerLanguageId     = order.CustomerLanguageId,
                CustomerComment        = order.CustomerOrderComment,
                OrderNumber            = order.GetOrderNumber(),
                CreatedOn              = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc),
                OrderStatus            = await _services.Localization.GetLocalizedEnumAsync(order.OrderStatus),
                IsReOrderAllowed       = orderSettings.IsReOrderAllowed,
                IsReturnRequestAllowed = _orderProcessingService.IsReturnRequestAllowed(order),
                DisplayPdfInvoice      = pdfSettings.Enabled,
                RenderOrderNotes       = pdfSettings.RenderOrderNotes,
                // Shipping info.
                ShippingStatus = await _services.Localization.GetLocalizedEnumAsync(order.ShippingStatus)
            };

            // TODO: refactor modelling for multi-order processing.
            var companyCountry = await _db.Countries.FindByIdAsync(companyInfoSettings.CountryId, false);

            model.MerchantCompanyInfo        = companyInfoSettings;
            model.MerchantCompanyCountryName = companyCountry?.GetLocalized(x => x.Name);

            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable = true;
                await MapperFactory.MapAsync(order.ShippingAddress, model.ShippingAddress);

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

            await MapperFactory.MapAsync(order.BillingAddress, model.BillingAddress);

            model.VatNumber = order.VatNumber;

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

            model.PaymentMethodSystemName = order.PaymentMethodSystemName;
            // TODO: (mh) (core)
            //model.PaymentMethod = paymentMethod != null ? _pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : order.PaymentMethodSystemName;
            model.PaymentMethod           = order.PaymentMethodSystemName;
            model.CanRePostProcessPayment = await _paymentService.CanRePostProcessPaymentAsync(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;
            }

            if (order.AllowStoringCreditCardNumber)
            {
                model.CardNumber             = _encryptor.DecryptText(order.CardNumber);
                model.MaskedCreditCardNumber = _encryptor.DecryptText(order.MaskedCreditCardNumber);
                model.CardCvv2            = _encryptor.DecryptText(order.CardCvv2);
                model.CardExpirationMonth = _encryptor.DecryptText(order.CardExpirationMonth);
                model.CardExpirationYear  = _encryptor.DecryptText(order.CardExpirationYear);
            }

            if (order.AllowStoringDirectDebit)
            {
                model.DirectDebitAccountHolder = _encryptor.DecryptText(order.DirectDebitAccountHolder);
                model.DirectDebitAccountNumber = _encryptor.DecryptText(order.DirectDebitAccountNumber);
                model.DirectDebitBankCode      = _encryptor.DecryptText(order.DirectDebitBankCode);
                model.DirectDebitBankName      = _encryptor.DecryptText(order.DirectDebitBankName);
                model.DirectDebitBIC           = _encryptor.DecryptText(order.DirectDebitBIC);
                model.DirectDebitCountry       = _encryptor.DecryptText(order.DirectDebitCountry);
                model.DirectDebitIban          = _encryptor.DecryptText(order.DirectDebitIban);
            }

            // TODO: (mh) (core) Reimplement when pricing is ready.
            // Totals.
            var customerCurrency = await _db.Currencies
                                   .AsNoTracking()
                                   .Where(x => x.CurrencyCode == order.CustomerCurrencyCode)
                                   .FirstOrDefaultAsync();

            switch (order.CustomerTaxDisplayType)
            {
            case TaxDisplayType.ExcludingTax:
            {
                // Order subtotal.
                var orderSubtotalExclTax = _currencyService.ConvertToExchangeRate(order.OrderSubtotalExclTax, order.CurrencyRate, customerCurrency);
                model.OrderSubtotal = orderSubtotalExclTax.ToString();

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountExclTax = _currencyService.ConvertToExchangeRate(order.OrderSubTotalDiscountExclTax, order.CurrencyRate, customerCurrency);
                if (orderSubTotalDiscountExclTax > 0)
                {
                    model.OrderSubTotalDiscount = (orderSubTotalDiscountExclTax * -1).ToString();
                }

                // Order shipping.
                var orderShippingExclTax = _currencyService.ConvertToExchangeRate(order.OrderShippingExclTax, order.CurrencyRate, customerCurrency);
                model.OrderShipping = orderShippingExclTax.ToString();

                // Payment method additional fee.
                var paymentMethodAdditionalFeeExclTax = _currencyService.ConvertToExchangeRate(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate, customerCurrency);
                if (paymentMethodAdditionalFeeExclTax != 0)
                {
                    model.PaymentMethodAdditionalFee = paymentMethodAdditionalFeeExclTax.ToString();
                }
            }
            break;

            case TaxDisplayType.IncludingTax:
            {
                // Order subtotal.
                var orderSubtotalInclTax = _currencyService.ConvertToExchangeRate(order.OrderSubtotalInclTax, order.CurrencyRate, customerCurrency);
                model.OrderSubtotal = orderSubtotalInclTax.ToString();

                // Discount (applied to order subtotal).
                var orderSubTotalDiscountInclTax = _currencyService.ConvertToExchangeRate(order.OrderSubTotalDiscountInclTax, order.CurrencyRate, customerCurrency);
                if (orderSubTotalDiscountInclTax > 0)
                {
                    model.OrderSubTotalDiscount = (orderSubTotalDiscountInclTax * -1).ToString();
                }

                // Order shipping.
                var orderShippingInclTax = _currencyService.ConvertToExchangeRate(order.OrderShippingInclTax, order.CurrencyRate, customerCurrency);
                model.OrderShipping = orderShippingInclTax.ToString();

                // Payment method additional fee.
                var paymentMethodAdditionalFeeInclTax = _currencyService.ConvertToExchangeRate(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate, customerCurrency);
                if (paymentMethodAdditionalFeeInclTax != 0)
                {
                    model.PaymentMethodAdditionalFee = paymentMethodAdditionalFeeInclTax.ToString();
                }
            }
            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.ConvertToExchangeRate(order.OrderTax, order.CurrencyRate, customerCurrency);
                    model.Tax = orderTaxInCustomerCurrency.ToString();

                    foreach (var tr in order.TaxRatesDictionary)
                    {
                        var rate     = _taxService.FormatTaxRate(tr.Key);
                        var labelKey = _services.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax ? "ShoppingCart.Totals.TaxRateLineIncl" : "ShoppingCart.Totals.TaxRateLineExcl";

                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate  = rate,
                            Label = T(labelKey, rate),
                            Value = _currencyService.ConvertToExchangeRate(tr.Value, order.CurrencyRate, customerCurrency).ToString()
                        });
                    }
                }
            }

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

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

            if (orderDiscountInCustomerCurrency > 0)
            {
                model.OrderTotalDiscount = (orderDiscountInCustomerCurrency * -1).ToString();
            }

            // Gift cards.
            foreach (var gcuh in order.GiftCardUsageHistory)
            {
                var remainingAmountBase = _giftCardService.GetRemainingAmount(gcuh.GiftCard);
                var remainingAmount     = _currencyService.ConvertToExchangeRate(remainingAmountBase.Amount, order.CurrencyRate, customerCurrency);
                var usedAmount          = _currencyService.ConvertToExchangeRate(gcuh.UsedValue, order.CurrencyRate, customerCurrency);

                var gcModel = new OrderDetailsModel.GiftCard
                {
                    CouponCode = gcuh.GiftCard.GiftCardCouponCode,
                    Amount     = (usedAmount * -1).ToString(),
                    Remaining  = remainingAmount.ToString()
                };

                model.GiftCards.Add(gcModel);
            }

            // Reward points         .
            if (order.RedeemedRewardPointsEntry != null)
            {
                var usedAmount = _currencyService.ConvertToExchangeRate(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate, customerCurrency);

                model.RedeemedRewardPoints       = -order.RedeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = (usedAmount * -1).ToString();
            }

            // Credit balance.
            if (order.CreditBalance > 0)
            {
                var convertedCreditBalance = _currencyService.ConvertToExchangeRate(order.CreditBalance, order.CurrencyRate, customerCurrency);
                model.CreditBalance = (convertedCreditBalance * -1).ToString();
            }

            // Total.
            (var orderTotal, var roundingAmount) = await _orderService.GetOrderTotalInCustomerCurrencyAsync(order, customerCurrency);

            model.OrderTotal = orderTotal.ToString();

            if (roundingAmount != 0)
            {
                model.OrderTotalRounding = roundingAmount.ToString();
            }

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

            // Order notes.
            await _db.LoadCollectionAsync(order, x => x.OrderNotes);

            var orderNotes = order.OrderNotes
                             .Where(x => x.DisplayToCustomer)
                             .OrderByDescending(x => x.CreatedOnUtc)
                             .ToList();

            foreach (var orderNote in orderNotes)
            {
                var createdOn = _dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc);

                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Note              = orderNote.FormatOrderNoteText(),
                    CreatedOn         = createdOn,
                    FriendlyCreatedOn = orderNote.CreatedOnUtc.Humanize()
                });
            }

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

            await _db.LoadCollectionAsync(order, x => x.OrderItems, false, q => q.Include(x => x.Product));

            foreach (var orderItem in order.OrderItems)
            {
                var orderItemModel = await PrepareOrderItemModelAsync(order, orderItem, catalogSettings, shoppingCartSettings, mediaSettings, customerCurrency);

                model.Items.Add(orderItemModel);
            }

            return(model);
        }
示例#9
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);
        }
示例#10
0
        /// <summary>
        /// Applies the product description to an expando object.
        /// Projection settings controls in detail how the product description is to be exported here.
        /// </summary>
        private static async Task ApplyProductDescription(dynamic dynObject, Product product, DataExporterContext ctx)
        {
            try
            {
                var    languageId  = ctx.LanguageId;
                string description = "";

                // Description merging.
                if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.None)
                {
                    // Export empty description.
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ShortDescriptionOrNameIfEmpty)
                {
                    description = dynObject.FullDescription;

                    if (description.IsEmpty())
                    {
                        description = dynObject.ShortDescription;
                    }
                    if (description.IsEmpty())
                    {
                        description = dynObject.Name;
                    }
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ShortDescription)
                {
                    description = dynObject.ShortDescription;
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.Description)
                {
                    description = dynObject.FullDescription;
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.NameAndShortDescription)
                {
                    description = ((string)dynObject.Name).Grow((string)dynObject.ShortDescription, " ");
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.NameAndDescription)
                {
                    description = ((string)dynObject.Name).Grow((string)dynObject.FullDescription, " ");
                }
                else if (ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndShortDescription ||
                         ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndDescription)
                {
                    var productManus = await ctx.ProductBatchContext.ProductManufacturers.GetOrLoadAsync(product.Id);

                    if (productManus != null && productManus.Any())
                    {
                        var manufacturer = productManus.First().Manufacturer;
                        description = ctx.GetTranslation(manufacturer, nameof(manufacturer.Name), manufacturer.Name);
                    }

                    description = description.Grow((string)dynObject.Name, " ");
                    description = ctx.Projection.DescriptionMerging == ExportDescriptionMerging.ManufacturerAndNameAndShortDescription
                        ? description.Grow((string)dynObject.ShortDescription, " ")
                        : description.Grow((string)dynObject.FullDescription, " ");
                }

                // Append text.
                if (ctx.Projection.AppendDescriptionText.HasValue() && ((string)dynObject.ShortDescription).IsEmpty() && ((string)dynObject.FullDescription).IsEmpty())
                {
                    var appendText = ctx.Projection.AppendDescriptionText.SplitSafe(",").ToArray();
                    if (appendText.Any())
                    {
                        var rnd = CommonHelper.GenerateRandomInteger(0, appendText.Length - 1);
                        description = description.Grow(appendText.ElementAtOrDefault(rnd), " ");
                    }
                }

                // Remove critical characters.
                if (description.HasValue() && ctx.Projection.RemoveCriticalCharacters)
                {
                    foreach (var str in ctx.Projection.CriticalCharacters.SplitSafe(","))
                    {
                        description = description.Replace(str, "");
                    }
                }

                // Convert to plain text.
                if (description.HasValue() && ctx.Projection.DescriptionToPlainText)
                {
                    //Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
                    //description = HttpUtility.HtmlDecode(reg.Replace(description, ""));

                    description = HtmlUtils.ConvertHtmlToPlainText(description);
                    description = HtmlUtils.StripTags(HttpUtility.HtmlDecode(description));
                }

                dynObject.FullDescription = description.TrimSafe();
            }
            catch { }
        }
        public override async Task MapAsync(IEnumerable <OrganizedShoppingCartItem> from, ShoppingCartModel to, dynamic parameters = null)
        {
            Guard.NotNull(from, nameof(from));
            Guard.NotNull(to, nameof(to));

            if (!from.Any())
            {
                return;
            }

            await base.MapAsync(from, to, null);

            var store    = _services.StoreContext.CurrentStore;
            var customer = _services.WorkContext.CurrentCustomer;
            var currency = _services.WorkContext.WorkingCurrency;

            var isEditable = parameters?.IsEditable == true;
            var validateCheckoutAttributes        = parameters?.ValidateCheckoutAttributes == true;
            var prepareEstimateShippingIfEnabled  = parameters?.PrepareEstimateShippingIfEnabled == true;
            var setEstimateShippingDefaultAddress = parameters?.SetEstimateShippingDefaultAddress == true;
            var prepareAndDisplayOrderReviewData  = parameters?.PrepareAndDisplayOrderReviewData == true;

            #region Simple properties

            to.MediaDimensions             = _mediaSettings.CartThumbPictureSize;
            to.DeliveryTimesPresentation   = _shoppingCartSettings.DeliveryTimesInShoppingCart;
            to.DisplayBasePrice            = _shoppingCartSettings.ShowBasePrice;
            to.DisplayWeight               = _shoppingCartSettings.ShowWeight;
            to.DisplayMoveToWishlistButton = await _services.Permissions.AuthorizeAsync(Permissions.Cart.AccessWishlist);

            to.TermsOfServiceEnabled         = _orderSettings.TermsOfServiceEnabled;
            to.DisplayCommentBox             = _shoppingCartSettings.ShowCommentBox;
            to.DisplayEsdRevocationWaiverBox = _shoppingCartSettings.ShowEsdRevocationWaiverBox;
            to.IsEditable = isEditable;

            var measure = await _db.MeasureWeights.FindByIdAsync(_measureSettings.BaseWeightId, false);

            if (measure != null)
            {
                to.MeasureUnitName = measure.GetLocalized(x => x.Name);
            }

            to.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable(
                HtmlUtils.ConvertHtmlToPlainText(
                    await _checkoutAttributeFormatter.FormatAttributesAsync(customer.GenericAttributes.CheckoutAttributes, customer)));

            // Gift card and gift card boxes.
            to.DiscountBox.Display = _shoppingCartSettings.ShowDiscountBox;
            var discountCouponCode = customer.GenericAttributes.DiscountCouponCode;
            var discount           = await _db.Discounts
                                     .AsNoTracking()
                                     .Where(x => x.CouponCode == discountCouponCode)
                                     .FirstOrDefaultAsync();

            if (discount != null &&
                discount.RequiresCouponCode &&
                await _discountService.IsDiscountValidAsync(discount, customer))
            {
                to.DiscountBox.CurrentCode = discount.CouponCode;
            }

            to.GiftCardBox.Display = _shoppingCartSettings.ShowGiftCardBox;

            // Reward points.
            if (_rewardPointsSettings.Enabled && !from.IncludesMatchingItems(x => x.IsRecurring) && !customer.IsGuest())
            {
                var rewardPointsBalance    = customer.GetRewardPointsBalance();
                var rewardPointsAmountBase = _orderCalculationService.ConvertRewardPointsToAmount(rewardPointsBalance);
                var rewardPointsAmount     = _currencyService.ConvertFromPrimaryCurrency(rewardPointsAmountBase.Amount, currency);

                if (rewardPointsAmount > decimal.Zero)
                {
                    to.RewardPoints.DisplayRewardPoints = true;
                    to.RewardPoints.RewardPointsAmount  = rewardPointsAmount.ToString(true);
                    to.RewardPoints.RewardPointsBalance = rewardPointsBalance;
                    to.RewardPoints.UseRewardPoints     = customer.GenericAttributes.UseRewardPointsDuringCheckout;
                }
            }

            // Cart warnings.
            var warnings    = new List <string>();
            var cartIsValid = await _shoppingCartValidator.ValidateCartItemsAsync(from, warnings, validateCheckoutAttributes, customer.GenericAttributes.CheckoutAttributes);

            if (!cartIsValid)
            {
                to.Warnings.AddRange(warnings);
            }

            #endregion

            #region Checkout attributes

            var checkoutAttributes = await _checkoutAttributeMaterializer.GetValidCheckoutAttributesAsync(from);

            foreach (var attribute in checkoutAttributes)
            {
                var caModel = new ShoppingCartModel.CheckoutAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = attribute.GetLocalized(x => x.Name),
                    TextPrompt           = attribute.GetLocalized(x => x.TextPrompt),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType
                };

                if (attribute.IsListTypeAttribute)
                {
                    var taxFormat = _currencyService.GetTaxFormat(null, null, PricingTarget.Product);
                    var caValues  = await _db.CheckoutAttributeValues
                                    .AsNoTracking()
                                    .Where(x => x.CheckoutAttributeId == attribute.Id)
                                    .ToListAsync();

                    // Prepare each attribute with image and price
                    foreach (var caValue in caValues)
                    {
                        var pvaValueModel = new ShoppingCartModel.CheckoutAttributeValueModel
                        {
                            Id            = caValue.Id,
                            Name          = caValue.GetLocalized(x => x.Name),
                            IsPreSelected = caValue.IsPreSelected,
                            Color         = caValue.Color
                        };

                        if (caValue.MediaFileId.HasValue && caValue.MediaFile != null)
                        {
                            pvaValueModel.ImageUrl = _mediaService.GetUrl(caValue.MediaFile, _mediaSettings.VariantValueThumbPictureSize, null, false);
                        }

                        caModel.Values.Add(pvaValueModel);

                        // Display price if allowed.
                        if (await _services.Permissions.AuthorizeAsync(Permissions.Catalog.DisplayPrice))
                        {
                            var priceAdjustmentBase = await _taxCalculator.CalculateCheckoutAttributeTaxAsync(caValue);

                            var priceAdjustment = _currencyService.ConvertFromPrimaryCurrency(priceAdjustmentBase.Price, currency);

                            if (priceAdjustment > 0)
                            {
                                pvaValueModel.PriceAdjustment = "+" + priceAdjustment.WithPostFormat(taxFormat).ToString();
                            }
                            else if (priceAdjustment < 0)
                            {
                                pvaValueModel.PriceAdjustment = "-" + (priceAdjustment * -1).WithPostFormat(taxFormat).ToString();
                            }
                        }
                    }
                }

                // Set already selected attributes.
                var selectedCheckoutAttributes = customer.GenericAttributes.CheckoutAttributes;
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Boxes:
                case AttributeControlType.Checkboxes:
                    if (selectedCheckoutAttributes.AttributesMap.Any())
                    {
                        // Clear default selection.
                        foreach (var item in caModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        // Select new values.
                        var selectedCaValues = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributeValuesAsync(selectedCheckoutAttributes);

                        foreach (var caValue in selectedCaValues)
                        {
                            foreach (var item in caModel.Values)
                            {
                                if (caValue.Id == item.Id)
                                {
                                    item.IsPreSelected = true;
                                }
                            }
                        }
                    }
                    break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                    if (selectedCheckoutAttributes.AttributesMap.Any())
                    {
                        var enteredText = selectedCheckoutAttributes.GetAttributeValues(attribute.Id)?
                                          .Select(x => x.ToString())
                                          .FirstOrDefault();

                        if (enteredText.HasValue())
                        {
                            caModel.TextValue = enteredText;
                        }
                    }
                    break;

                case AttributeControlType.Datepicker:
                {
                    // Keep in mind my that the code below works only in the current culture.
                    var enteredDate = selectedCheckoutAttributes.AttributesMap
                                      .Where(x => x.Key == attribute.Id)
                                      .SelectMany(x => x.Value)
                                      .FirstOrDefault()
                                      .ToString();

                    if (enteredDate.HasValue() &&
                        DateTime.TryParseExact(enteredDate, "D", CultureInfo.CurrentCulture, DateTimeStyles.None, out var selectedDate))
                    {
                        caModel.SelectedDay   = selectedDate.Day;
                        caModel.SelectedMonth = selectedDate.Month;
                        caModel.SelectedYear  = selectedDate.Year;
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                    if (selectedCheckoutAttributes.AttributesMap.Any())
                    {
                        var FileValue = selectedCheckoutAttributes.AttributesMap
                                        .Where(x => x.Key == attribute.Id)
                                        .Select(x => x.Value.ToString())
                                        .FirstOrDefault();

                        if (FileValue.HasValue() && caModel.UploadedFileGuid.HasValue() && Guid.TryParse(caModel.UploadedFileGuid, out var guid))
                        {
                            var download = await _db.Downloads
                                           .Include(x => x.MediaFile)
                                           .FirstOrDefaultAsync(x => x.DownloadGuid == guid);

                            if (download != null && !download.UseDownloadUrl && download.MediaFile != null)
                            {
                                caModel.UploadedFileName = download.MediaFile.Name;
                            }
                        }
                    }
                    break;

                default:
                    break;
                }

                to.CheckoutAttributes.Add(caModel);
            }

            #endregion

            #region Estimate shipping

            if (prepareEstimateShippingIfEnabled)
            {
                to.EstimateShipping.Enabled = _shippingSettings.EstimateShippingEnabled &&
                                              from.Any() &&
                                              from.IncludesMatchingItems(x => x.IsShippingEnabled);

                if (to.EstimateShipping.Enabled)
                {
                    // Countries.
                    var defaultEstimateCountryId = setEstimateShippingDefaultAddress && customer.ShippingAddress != null
                        ? customer.ShippingAddress.CountryId
                        : to.EstimateShipping.CountryId;

                    var countriesForShipping = await _db.Countries
                                               .AsNoTracking()
                                               .ApplyStoreFilter(store.Id)
                                               .Where(x => x.AllowsShipping)
                                               .ToListAsync();

                    foreach (var countries in countriesForShipping)
                    {
                        to.EstimateShipping.AvailableCountries.Add(new SelectListItem
                        {
                            Text     = countries.GetLocalized(x => x.Name),
                            Value    = countries.Id.ToString(),
                            Selected = countries.Id == defaultEstimateCountryId
                        });
                    }

                    // States.
                    var states = defaultEstimateCountryId.HasValue
                        ? await _db.StateProvinces.AsNoTracking().ApplyCountryFilter(defaultEstimateCountryId.Value).ToListAsync()
                        : new();

                    if (states.Any())
                    {
                        var defaultEstimateStateId = setEstimateShippingDefaultAddress && customer.ShippingAddress != null
                            ? customer.ShippingAddress.StateProvinceId
                            : to.EstimateShipping.StateProvinceId;

                        foreach (var s in states)
                        {
                            to.EstimateShipping.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = s.Id == defaultEstimateStateId
                            });
                        }
                    }
                    else
                    {
                        to.EstimateShipping.AvailableStates.Add(new SelectListItem {
                            Text = T("Address.OtherNonUS"), Value = "0"
                        });
                    }

                    if (setEstimateShippingDefaultAddress && customer.ShippingAddress != null)
                    {
                        to.EstimateShipping.ZipPostalCode = customer.ShippingAddress.ZipPostalCode;
                    }
                }
            }

            #endregion

            #region Cart items

            var allProducts = from
                              .Select(x => x.Item.Product)
                              .Union(from.Select(x => x.ChildItems).SelectMany(child => child.Select(x => x.Item.Product)))
                              .ToArray();

            var batchContext = _productService.CreateProductBatchContext(allProducts, null, customer, false);
            var subtotal     = await _orderCalculationService.GetShoppingCartSubtotalAsync(from.ToList(), null, batchContext);

            dynamic itemParameters = new ExpandoObject();
            itemParameters.TaxFormat    = _currencyService.GetTaxFormat();
            itemParameters.BatchContext = batchContext;
            itemParameters.CartSubtotal = subtotal;

            foreach (var cartItem in from)
            {
                var model = new ShoppingCartModel.ShoppingCartItemModel();

                await cartItem.MapAsync(model, (object)itemParameters);

                to.AddItems(model);
            }

            #endregion

            #region Order review data

            if (prepareAndDisplayOrderReviewData)
            {
                var checkoutState = _httpContextAccessor.HttpContext?.GetCheckoutState();

                to.OrderReviewData.Display = true;

                // Billing info.
                var billingAddress = customer.BillingAddress;
                if (billingAddress != null)
                {
                    await MapperFactory.MapAsync(billingAddress, to.OrderReviewData.BillingAddress);
                }

                // Shipping info.
                if (from.IsShippingRequired())
                {
                    to.OrderReviewData.IsShippable = true;

                    var shippingAddress = customer.ShippingAddress;
                    if (shippingAddress != null)
                    {
                        await MapperFactory.MapAsync(shippingAddress, to.OrderReviewData.ShippingAddress);
                    }

                    // Selected shipping method.
                    var shippingOption = customer.GenericAttributes.SelectedShippingOption;
                    if (shippingOption != null)
                    {
                        to.OrderReviewData.ShippingMethod = shippingOption.Name;
                    }

                    if (checkoutState != null && checkoutState.CustomProperties.ContainsKey("HasOnlyOneActiveShippingMethod"))
                    {
                        to.OrderReviewData.DisplayShippingMethodChangeOption = !(bool)checkoutState.CustomProperties.Get("HasOnlyOneActiveShippingMethod");
                    }
                }

                if (checkoutState != null && checkoutState.CustomProperties.ContainsKey("HasOnlyOneActivePaymentMethod"))
                {
                    to.OrderReviewData.DisplayPaymentMethodChangeOption = !(bool)checkoutState.CustomProperties.Get("HasOnlyOneActivePaymentMethod");
                }

                var selectedPaymentMethodSystemName = customer.GenericAttributes.SelectedPaymentMethod;
                var paymentMethod = await _paymentService.LoadPaymentMethodBySystemNameAsync(selectedPaymentMethodSystemName);

                // TODO: (ms) (core) Wait for PluginMediator.GetLocalizedFriendlyName implementation
                //model.OrderReviewData.PaymentMethod = paymentMethod != null ? _pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : "";
                to.OrderReviewData.PaymentSummary            = checkoutState.PaymentSummary;
                to.OrderReviewData.IsPaymentSelectionSkipped = checkoutState.IsPaymentSelectionSkipped;
            }

            #endregion

            var paymentTypes        = new PaymentMethodType[] { PaymentMethodType.Button, PaymentMethodType.StandardAndButton };
            var boundPaymentMethods = await _paymentService.LoadActivePaymentMethodsAsync(
                customer,
                from.ToList(),
                store.Id,
                paymentTypes,
                false);

            var bpmModel = new ButtonPaymentMethodModel();

            foreach (var boundPaymentMethod in boundPaymentMethods)
            {
                if (from.IncludesMatchingItems(x => x.IsRecurring) && boundPaymentMethod.Value.RecurringPaymentType == RecurringPaymentType.NotSupported)
                {
                    continue;
                }

                var widgetInvoker = boundPaymentMethod.Value.GetPaymentInfoWidget();
                bpmModel.Items.Add(widgetInvoker);
            }

            to.ButtonPaymentMethods = bpmModel;
        }