/// <summary>
        /// Prepare billing address model
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <param name="selectedCountryId">Selected country identifier</param>
        /// <param name="prePopulateNewAddressWithCustomerFields">Pre populate new address with customer fields</param>
        /// <param name="overrideAttributesXml">Override attributes xml</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the billing address model
        /// </returns>
        public virtual async Task <CheckoutBillingAddressModel> PrepareBillingAddressModelAsync(IList <ShoppingCartItem> cart,
                                                                                                int?selectedCountryId = null,
                                                                                                bool prePopulateNewAddressWithCustomerFields = false,
                                                                                                string overrideAttributesXml = "")
        {
            var model = new CheckoutBillingAddressModel
            {
                ShipToSameAddressAllowed = _shippingSettings.ShipToSameAddress && await _shoppingCartService.ShoppingCartRequiresShippingAsync(cart),
                //allow customers to enter (choose) a shipping address if "Disable Billing address step" setting is enabled
                ShipToSameAddress = !_orderSettings.DisableBillingAddressCheckoutStep
            };

            //existing addresses
            var customer = await _workContext.GetCurrentCustomerAsync();

            var addresses = await(await _customerService.GetAddressesByCustomerIdAsync(customer.Id))
                            .WhereAwait(async a => !a.CountryId.HasValue || await _countryService.GetCountryByAddressAsync(a) is Country country &&
                                        (//published
                                            country.Published &&
                                            //allow billing
                                            country.AllowsBilling &&
                                            //enabled for the current store
                                            await _storeMappingService.AuthorizeAsync(country)))
                            .ToListAsync();

            foreach (var address in addresses)
            {
                var addressModel = new AddressModel();
                await _addressModelFactory.PrepareAddressModelAsync(addressModel,
                                                                    address : address,
                                                                    excludeProperties : false,
                                                                    addressSettings : _addressSettings);

                if (await _addressService.IsAddressValidAsync(address))
                {
                    model.ExistingAddresses.Add(addressModel);
                }
                else
                {
                    model.InvalidExistingAddresses.Add(addressModel);
                }
            }

            //new address
            model.BillingNewAddress.CountryId = selectedCountryId;
            await _addressModelFactory.PrepareAddressModelAsync(model.BillingNewAddress,
                                                                address : null,
                                                                excludeProperties : false,
                                                                addressSettings : _addressSettings,
                                                                loadCountries : async() => await _countryService.GetAllCountriesForBillingAsync((await _workContext.GetWorkingLanguageAsync()).Id),
                                                                prePopulateWithCustomerFields : prePopulateNewAddressWithCustomerFields,
                                                                customer : customer,
                                                                overrideAttributesXml : overrideAttributesXml);

            return(model);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Prepare warehouse model
        /// </summary>
        /// <param name="model">Warehouse model</param>
        /// <param name="warehouse">Warehouse</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the warehouse model
        /// </returns>
        public virtual async Task <WarehouseModel> PrepareWarehouseModelAsync(WarehouseModel model, Warehouse warehouse, bool excludeProperties = false)
        {
            if (warehouse != null)
            {
                //fill in model values from the entity
                if (model == null)
                {
                    model = warehouse.ToModel <WarehouseModel>();
                }
            }

            //prepare address model
            var address = await _addressService.GetAddressByIdAsync(warehouse?.AddressId ?? 0);

            if (!excludeProperties && address != null)
            {
                model.Address = address.ToModel(model.Address);
            }
            await _addressModelFactory.PrepareAddressModelAsync(model.Address, address);

            model.Address.CountryRequired       = true;
            model.Address.ZipPostalCodeRequired = true;

            return(model);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Prepare affiliate model
        /// </summary>
        /// <param name="model">Affiliate model</param>
        /// <param name="affiliate">Affiliate</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the affiliate model
        /// </returns>
        public virtual async Task <AffiliateModel> PrepareAffiliateModelAsync(AffiliateModel model, Affiliate affiliate, bool excludeProperties = false)
        {
            //fill in model values from the entity
            if (affiliate != null)
            {
                model ??= affiliate.ToModel <AffiliateModel>();
                model.Url = await _affiliateService.GenerateUrlAsync(affiliate);

                //prepare nested search models
                await PrepareAffiliatedOrderSearchModelAsync(model.AffiliatedOrderSearchModel, affiliate);

                PrepareAffiliatedCustomerSearchModel(model.AffiliatedCustomerSearchModel, affiliate);

                //whether to fill in some of properties
                if (!excludeProperties)
                {
                    model.AdminComment    = affiliate.AdminComment;
                    model.FriendlyUrlName = affiliate.FriendlyUrlName;
                    model.Active          = affiliate.Active;
                }
            }

            //prepare address model
            var address = await _addressService.GetAddressByIdAsync(affiliate?.AddressId ?? 0);

            if (!excludeProperties && address != null)
            {
                model.Address = address.ToModel(model.Address);
            }
            await _addressModelFactory.PrepareAddressModelAsync(model.Address, address);

            model.Address.FirstNameRequired     = true;
            model.Address.LastNameRequired      = true;
            model.Address.EmailRequired         = true;
            model.Address.CountryRequired       = true;
            model.Address.CountyRequired        = true;
            model.Address.CityRequired          = true;
            model.Address.StreetAddressRequired = true;
            model.Address.ZipPostalCodeRequired = true;
            model.Address.PhoneRequired         = true;

            return(model);
        }
Exemplo n.º 4
0
        public virtual async Task <CustomerAddressModel> PrepareCompanyCustomerAddressModelAsync(CustomerAddressModel model,
                                                                                                 Company company, Address address, bool excludeProperties = false)
        {
            if (company == null)
            {
                throw new ArgumentNullException(nameof(company));
            }

            if (address != null)
            {
                //fill in model values from the entity
                model ??= new CustomerAddressModel();

                //whether to fill in some of properties
                if (!excludeProperties)
                {
                    model.Address = address.ToModel(model.Address);
                }
            }

            model.CustomerId = company.Id;

            //prepare address model
            await _addressModelFactory.PrepareAddressModelAsync(model.Address, address);

            model.Address.FirstNameRequired      = true;
            model.Address.LastNameRequired       = true;
            model.Address.EmailRequired          = true;
            model.Address.CompanyRequired        = _addressSettings.CompanyRequired;
            model.Address.CityRequired           = _addressSettings.CityRequired;
            model.Address.CountyRequired         = _addressSettings.CountyRequired;
            model.Address.StreetAddressRequired  = _addressSettings.StreetAddressRequired;
            model.Address.StreetAddress2Required = _addressSettings.StreetAddress2Required;
            model.Address.ZipPostalCodeRequired  = _addressSettings.ZipPostalCodeRequired;
            model.Address.PhoneRequired          = _addressSettings.PhoneRequired;
            model.Address.FaxRequired            = _addressSettings.FaxRequired;

            return(model);
        }
        public async Task PrepareAddressModelShouldPopulatingPropertiesFromEntity()
        {
            var model = new AddressModel();
            await _addressModelFactory.PrepareAddressModelAsync(model, _address, false, _addressSettings);

            model.Id.Should().Be(_address.Id);
            model.FirstName.Should().Be(_address.FirstName);
            model.LastName.Should().Be(_address.LastName);
            model.Email.Should().Be(_address.Email);
            model.Company.Should().Be(_address.Company);
            model.CountryId.Should().Be(_address.CountryId);
            model.StateProvinceId.Should().Be(_address.StateProvinceId);
            model.County.Should().Be(_address.County);
            model.City.Should().Be(_address.City);
            model.Address1.Should().Be(_address.Address1);
            model.Address2.Should().Be(_address.Address2);
            model.ZipPostalCode.Should().Be(_address.ZipPostalCode);
            model.PhoneNumber.Should().Be(_address.PhoneNumber);
            model.FaxNumber.Should().Be(_address.FaxNumber);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Prepare vendor model
        /// </summary>
        /// <param name="model">Vendor model</param>
        /// <param name="vendor">Vendor</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the vendor model
        /// </returns>
        public virtual async Task <VendorModel> PrepareVendorModelAsync(VendorModel model, Vendor vendor, bool excludeProperties = false)
        {
            Action <VendorLocalizedModel, int> localizedModelConfiguration = null;

            if (vendor != null)
            {
                //fill in model values from the entity
                if (model == null)
                {
                    model        = vendor.ToModel <VendorModel>();
                    model.SeName = await _urlRecordService.GetSeNameAsync(vendor, 0, true, false);
                }

                //define localized model configuration action
                localizedModelConfiguration = async(locale, languageId) =>
                {
                    locale.Name = await _localizationService.GetLocalizedAsync(vendor, entity => entity.Name, languageId, false, false);

                    locale.Description = await _localizationService.GetLocalizedAsync(vendor, entity => entity.Description, languageId, false, false);

                    locale.MetaKeywords = await _localizationService.GetLocalizedAsync(vendor, entity => entity.MetaKeywords, languageId, false, false);

                    locale.MetaDescription = await _localizationService.GetLocalizedAsync(vendor, entity => entity.MetaDescription, languageId, false, false);

                    locale.MetaTitle = await _localizationService.GetLocalizedAsync(vendor, entity => entity.MetaTitle, languageId, false, false);

                    locale.SeName = await _urlRecordService.GetSeNameAsync(vendor, languageId, false, false);
                };

                //prepare associated customers
                await PrepareAssociatedCustomerModelsAsync(model.AssociatedCustomers, vendor);

                //prepare nested search models
                PrepareVendorNoteSearchModel(model.VendorNoteSearchModel, vendor);
            }

            //set default values for the new model
            if (vendor == null)
            {
                model.PageSize = 6;
                model.Active   = true;
                model.AllowCustomersToSelectPageSize = true;
                model.PageSizeOptions     = _vendorSettings.DefaultVendorPageSizeOptions;
                model.PriceRangeFiltering = true;
                model.ManuallyPriceRange  = true;
                model.PriceFrom           = NopCatalogDefaults.DefaultPriceRangeFrom;
                model.PriceTo             = NopCatalogDefaults.DefaultPriceRangeTo;
            }

            model.PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode;

            //prepare localized models
            if (!excludeProperties)
            {
                model.Locales = await _localizedModelFactory.PrepareLocalizedModelsAsync(localizedModelConfiguration);
            }

            //prepare model vendor attributes
            await PrepareVendorAttributeModelsAsync(model.VendorAttributes, vendor);

            //prepare address model
            var address = await _addressService.GetAddressByIdAsync(vendor?.AddressId ?? 0);

            if (!excludeProperties && address != null)
            {
                model.Address = address.ToModel(model.Address);
            }
            await _addressModelFactory.PrepareAddressModelAsync(model.Address, address);

            return(model);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Prepare the order details model
        /// </summary>
        /// <param name="order">Order</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the order details model
        /// </returns>
        public virtual async Task <OrderDetailsModel> PrepareOrderDetailsModelAsync(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }
            var model = new OrderDetailsModel
            {
                Id                     = order.Id,
                CreatedOn              = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc),
                OrderStatus            = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus),
                IsReOrderAllowed       = _orderSettings.IsReOrderAllowed,
                IsReturnRequestAllowed = await _orderProcessingService.IsReturnRequestAllowedAsync(order),
                PdfInvoiceDisabled     = _pdfSettings.DisablePdfInvoicesForPendingOrders && order.OrderStatus == OrderStatus.Pending,
                CustomOrderNumber      = order.CustomOrderNumber,

                //shipping info
                ShippingStatus = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus)
            };

            if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                model.IsShippable   = true;
                model.PickupInStore = order.PickupInStore;
                if (!order.PickupInStore)
                {
                    var shippingAddress = await _addressService.GetAddressByIdAsync(order.ShippingAddressId ?? 0);

                    await _addressModelFactory.PrepareAddressModelAsync(model.ShippingAddress,
                                                                        address : shippingAddress,
                                                                        excludeProperties : false,
                                                                        addressSettings : _addressSettings);
                }
                else if (order.PickupAddressId.HasValue && await _addressService.GetAddressByIdAsync(order.PickupAddressId.Value) is Address pickupAddress)
                {
                    model.PickupAddress = new AddressModel
                    {
                        Address1          = pickupAddress.Address1,
                        City              = pickupAddress.City,
                        County            = pickupAddress.County,
                        StateProvinceName = await _stateProvinceService.GetStateProvinceByAddressAsync(pickupAddress) is StateProvince stateProvince
                            ? await _localizationService.GetLocalizedAsync(stateProvince, entity => entity.Name)
                            : string.Empty,
                        CountryName = await _countryService.GetCountryByAddressAsync(pickupAddress) is Country country
                            ? await _localizationService.GetLocalizedAsync(country, entity => entity.Name)
                            : string.Empty,
                        ZipPostalCode = pickupAddress.ZipPostalCode
                    };
                }

                model.ShippingMethod = order.ShippingMethod;

                //shipments (only already shipped or ready for pickup)
                var shipments = (await _shipmentService.GetShipmentsByOrderIdAsync(order.Id, !order.PickupInStore, order.PickupInStore)).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 = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.ReadyForPickupDateUtc.HasValue)
                    {
                        shipmentModel.ReadyForPickupDate = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.ReadyForPickupDateUtc.Value, DateTimeKind.Utc);
                    }
                    if (shipment.DeliveryDateUtc.HasValue)
                    {
                        shipmentModel.DeliveryDate = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
                    }
                    model.Shipments.Add(shipmentModel);
                }
            }

            var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId);

            //billing info
            await _addressModelFactory.PrepareAddressModelAsync(model.BillingAddress,
                                                                address : billingAddress,
                                                                excludeProperties : false,
                                                                addressSettings : _addressSettings);

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

            var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;

            //payment method
            var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);

            var paymentMethod = await _paymentPluginManager
                                .LoadPluginBySystemNameAsync(order.PaymentMethodSystemName, customer, order.StoreId);

            model.PaymentMethod = paymentMethod != null ? await _localizationService.GetLocalizedFriendlyNameAsync(paymentMethod, languageId) : order.PaymentMethodSystemName;

            model.PaymentMethodStatus = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus);

            model.CanRePostProcessPayment = await _paymentService.CanRePostProcessPaymentAsync(order);

            //custom values
            model.CustomValues = _paymentService.DeserializeCustomValues(order);

            //order subtotal
            if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal)
            {
                //including tax

                //order subtotal
                var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                model.OrderSubtotal = await _priceFormatter.FormatPriceAsync(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                model.OrderSubtotalValue = orderSubtotalInclTaxInCustomerCurrency;
                //discount (applied to order subtotal)
                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                if (orderSubTotalDiscountInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = await _priceFormatter.FormatPriceAsync(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                    model.OrderSubTotalDiscountValue = orderSubTotalDiscountInclTaxInCustomerCurrency;
                }
            }
            else
            {
                //excluding tax

                //order subtotal
                var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                model.OrderSubtotal = await _priceFormatter.FormatPriceAsync(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                model.OrderSubtotalValue = orderSubtotalExclTaxInCustomerCurrency;
                //discount (applied to order subtotal)
                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                if (orderSubTotalDiscountExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.OrderSubTotalDiscount = await _priceFormatter.FormatPriceAsync(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                    model.OrderSubTotalDiscountValue = orderSubTotalDiscountExclTaxInCustomerCurrency;
                }
            }

            if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                //including tax

                //order shipping
                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                model.OrderShipping = await _priceFormatter.FormatShippingPriceAsync(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                model.OrderShippingValue = orderShippingInclTaxInCustomerCurrency;
                //payment method additional fee
                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeInclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = await _priceFormatter.FormatPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                    model.PaymentMethodAdditionalFeeValue = paymentMethodAdditionalFeeInclTaxInCustomerCurrency;
                }
            }
            else
            {
                //excluding tax

                //order shipping
                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                model.OrderShipping = await _priceFormatter.FormatShippingPriceAsync(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                model.OrderShippingValue = orderShippingExclTaxInCustomerCurrency;
                //payment method additional fee
                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                if (paymentMethodAdditionalFeeExclTaxInCustomerCurrency > decimal.Zero)
                {
                    model.PaymentMethodAdditionalFee = await _priceFormatter.FormatPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                    model.PaymentMethodAdditionalFeeValue = paymentMethodAdditionalFeeExclTaxInCustomerCurrency;
                }
            }

            //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
                {
                    var taxRates = _orderService.ParseTaxRates(order, order.TaxRates);
                    displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Any();
                    displayTax      = !displayTaxRates;

                    var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
                    model.Tax = await _priceFormatter.FormatPriceAsync(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, languageId);

                    foreach (var tr in taxRates)
                    {
                        model.TaxRates.Add(new OrderDetailsModel.TaxRate
                        {
                            Rate  = _priceFormatter.FormatTaxRate(tr.Key),
                            Value = await _priceFormatter.FormatPriceAsync(_currencyService.ConvertCurrency(tr.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, languageId),
                        });
                    }
                }
            }
            model.DisplayTaxRates        = displayTaxRates;
            model.DisplayTax             = displayTax;
            model.DisplayTaxShippingInfo = _catalogSettings.DisplayTaxShippingInfoOrderDetailsPage;
            model.PricesIncludeTax       = order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax;

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

            if (orderDiscountInCustomerCurrency > decimal.Zero)
            {
                model.OrderTotalDiscount = await _priceFormatter.FormatPriceAsync(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, languageId);

                model.OrderTotalDiscountValue = orderDiscountInCustomerCurrency;
            }

            //gift cards
            foreach (var gcuh in await _giftCardService.GetGiftCardUsageHistoryAsync(order))
            {
                model.GiftCards.Add(new OrderDetailsModel.GiftCard
                {
                    CouponCode = (await _giftCardService.GetGiftCardByIdAsync(gcuh.GiftCardId)).GiftCardCouponCode,
                    Amount     = await _priceFormatter.FormatPriceAsync(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, languageId),
                });
            }

            //reward points
            if (order.RedeemedRewardPointsEntryId.HasValue && await _rewardPointService.GetRewardPointsHistoryEntryByIdAsync(order.RedeemedRewardPointsEntryId.Value) is RewardPointsHistory redeemedRewardPointsEntry)
            {
                model.RedeemedRewardPoints       = -redeemedRewardPointsEntry.Points;
                model.RedeemedRewardPointsAmount = await _priceFormatter.FormatPriceAsync(-(_currencyService.ConvertCurrency(redeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, languageId);
            }

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

            model.OrderTotal = await _priceFormatter.FormatPriceAsync(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, languageId);

            model.OrderTotalValue = orderTotalInCustomerCurrency;

            //checkout attributes
            model.CheckoutAttributeInfo = order.CheckoutAttributeDescription;

            //order notes
            foreach (var orderNote in (await _orderService.GetOrderNotesByOrderIdAsync(order.Id, true))
                     .OrderByDescending(on => on.CreatedOnUtc)
                     .ToList())
            {
                model.OrderNotes.Add(new OrderDetailsModel.OrderNote
                {
                    Id          = orderNote.Id,
                    HasDownload = orderNote.DownloadId > 0,
                    Note        = _orderService.FormatOrderNoteText(orderNote),
                    CreatedOn   = await _dateTimeHelper.ConvertToUserTimeAsync(orderNote.CreatedOnUtc, DateTimeKind.Utc)
                });
            }

            //purchased products
            model.ShowSku        = _catalogSettings.ShowSkuOnProductDetailsPage;
            model.ShowVendorName = _vendorSettings.ShowVendorOnOrderDetailsPage;

            var orderItems = await _orderService.GetOrderItemsAsync(order.Id);

            foreach (var orderItem in orderItems)
            {
                var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                var orderItemModel = new OrderDetailsModel.OrderItemModel
                {
                    Id            = orderItem.Id,
                    OrderItemGuid = orderItem.OrderItemGuid,
                    Sku           = await _productService.FormatSkuAsync(product, orderItem.AttributesXml),
                    VendorName    = (await _vendorService.GetVendorByIdAsync(product.VendorId))?.Name ?? string.Empty,
                    ProductId     = product.Id,
                    ProductName   = await _localizationService.GetLocalizedAsync(product, x => x.Name),
                    ProductSeName = await _urlRecordService.GetSeNameAsync(product),
                    Quantity      = orderItem.Quantity,
                    AttributeInfo = orderItem.AttributeDescription,
                };
                //rental info
                if (product.IsRental)
                {
                    var rentalStartDate = orderItem.RentalStartDateUtc.HasValue
                        ? _productService.FormatRentalDate(product, orderItem.RentalStartDateUtc.Value) : "";
                    var rentalEndDate = orderItem.RentalEndDateUtc.HasValue
                        ? _productService.FormatRentalDate(product, orderItem.RentalEndDateUtc.Value) : "";
                    orderItemModel.RentalInfo = string.Format(await _localizationService.GetResourceAsync("Order.Rental.FormattedDate"),
                                                              rentalStartDate, rentalEndDate);
                }
                model.Items.Add(orderItemModel);

                //unit price, subtotal
                if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                {
                    //including tax
                    var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                    orderItemModel.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                    orderItemModel.UnitPriceValue = unitPriceInclTaxInCustomerCurrency;

                    var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate);
                    orderItemModel.SubTotal = await _priceFormatter.FormatPriceAsync(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);

                    orderItemModel.SubTotalValue = priceInclTaxInCustomerCurrency;
                }
                else
                {
                    //excluding tax
                    var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                    orderItemModel.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                    orderItemModel.UnitPriceValue = unitPriceExclTaxInCustomerCurrency;

                    var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate);
                    orderItemModel.SubTotal = await _priceFormatter.FormatPriceAsync(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);

                    orderItemModel.SubTotalValue = priceExclTaxInCustomerCurrency;
                }

                //downloadable products
                if (await _orderService.IsDownloadAllowedAsync(orderItem))
                {
                    orderItemModel.DownloadId = product.DownloadId;
                }
                if (await _orderService.IsLicenseDownloadAllowedAsync(orderItem))
                {
                    orderItemModel.LicenseId = orderItem.LicenseDownloadId ?? 0;
                }
            }

            return(model);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Prepare pickup model
        /// </summary>
        /// <param name="model">Pickup model</param>
        /// <param name="shipment">Shipment; pass null if it's a pickup for the batch</param>
        /// <param name="batch">Batch; pass null if it's a pickup for the shipment</param>
        /// <param name="addressId">Address id</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the pickup model
        /// </returns>
        public async Task <PickupModel> PreparePickupModelAsync(PickupModel model, Shipment shipment, EasyPostBatch batch, int?addressId)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var pickupId = shipment is not null
                ? await _genericAttributeService.GetAttributeAsync <string>(shipment, EasyPostDefaults.PickupIdAttribute)
                : batch?.PickupId;

            model.PickupId   = pickupId;
            model.ShipmentId = shipment?.Id;
            model.BatchId    = batch?.Id;

            if (!string.IsNullOrEmpty(pickupId))
            {
                var(pickup, _) = await _easyPostService.GetPickupAsync(pickupId);

                model.Created   = pickup is not null;
                model.Status    = pickup?.status ?? "not found";
                model.Purchased = string.Equals(pickup?.status, "scheduled", StringComparison.InvariantCultureIgnoreCase);
                if (model.Created && !model.Purchased)
                {
                    var(pickupRates, _) = await _easyPostService.GetPickupRatesAsync(pickup);

                    if (pickupRates?.Any() ?? false)
                    {
                        model.AvailablePickupRates = await pickupRates.OrderBy(rate => rate.Rate).SelectAwait(async rate =>
                        {
                            var rateName = $"{rate.Carrier} {rate.Service}".TrimEnd(' ');
                            var text     = $"{await _priceFormatter.FormatShippingPriceAsync(rate.Rate, true)} {rateName}";
                            return(new SelectListItem(text, rate.Id));
                        }).ToListAsync();
                    }
                    else
                    {
                        var locale = await _localizationService.GetResourceAsync("Plugins.Shipping.EasyPost.Pickup.Rate.None");

                        model.AvailablePickupRates.Add(new SelectListItem(locale, string.Empty));
                    }
                }
            }

            if (!model.Created)
            {
                var address = await _addressService.GetAddressByIdAsync(addressId ?? 0);

                if (address is not null)
                {
                    model.PickupAddress = address.ToModel(model.PickupAddress);
                }
                await _addressModelFactory.PrepareAddressModelAsync(model.PickupAddress, address);

                model.PickupAddress.CustomAddressAttributes.Clear();

                model.MinDate = DateTime.UtcNow.AddDays(1).Date;
                model.MaxDate = DateTime.UtcNow.AddDays(7).Date;
            }

            return(model);
        }