Пример #1
0
        private async Task <decimal> GetSubtotalTaxTotalAsync(
            SortedDictionary <decimal, decimal> taxRates,
            TaxTotalRequest taxTotalRequest
            )
        {
            var(_, _, _, _, orderSubTotalTaxRates) = await _orderTotalCalculationService
                                                     .GetShoppingCartSubTotalAsync(taxTotalRequest.ShoppingCart, false);

            var subTotalTaxTotal = decimal.Zero;

            foreach (var kvp in orderSubTotalTaxRates)
            {
                var taxRate  = kvp.Key;
                var taxValue = kvp.Value;
                subTotalTaxTotal += taxValue;

                if (taxRate > decimal.Zero && taxValue > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, taxValue);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + taxValue;
                    }
                }
            }
            return(subTotalTaxTotal);
        }
        /// <summary>
        /// Returns the value indicating whether to payment method can be displayed in checkout
        /// </summary>
        /// <param name="cart">The shopping cart</param>
        /// <returns>The <see cref="Task"/> containing the value indicating whether to payment method can be displayed in checkout</returns>
        public virtual async Task <bool> CanDisplayPaymentMethodAsync(IList <ShoppingCartItem> cart)
        {
            if (cart is null)
            {
                throw new ArgumentNullException(nameof(cart));
            }

            if (!(await ValidateAsync()).IsValid)
            {
                return(false);
            }

            if (_openPayPaymentSettings.MinOrderTotal == 0 || _openPayPaymentSettings.MaxOrderTotal == 0)
            {
                return(false);
            }

            var cartTotal = await _orderTotalCalculationService.GetShoppingCartTotalAsync(cart);

            decimal shoppingCartTotal;

            if (cartTotal.shoppingCartTotal.HasValue)
            {
                shoppingCartTotal = cartTotal.shoppingCartTotal.Value;
            }
            else
            {
                var cartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, true);

                shoppingCartTotal = cartSubTotal.subTotalWithDiscount;
            }

            if (shoppingCartTotal < _openPayPaymentSettings.MinOrderTotal || shoppingCartTotal > _openPayPaymentSettings.MaxOrderTotal)
            {
                return(false);
            }

            if (!await _shoppingCartService.ShoppingCartRequiresShippingAsync(cart))
            {
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Gets tax total
        /// </summary>
        /// <param name="taxTotalRequest">Tax total request</param>
        /// <returns>Tax total</returns>
        public async Task <TaxTotalResult> GetTaxTotalAsync(TaxTotalRequest taxTotalRequest)
        {
            var taxRates = new SortedDictionary <decimal, decimal>();
            var cart     = taxTotalRequest.ShoppingCart;
            var customer = taxTotalRequest.Customer;
            var storeId  = taxTotalRequest.StoreId;
            var usePaymentMethodAdditionalFee = taxTotalRequest.UsePaymentMethodAdditionalFee;

            var paymentMethodSystemName = string.Empty;

            if (customer != null)
            {
                paymentMethodSystemName = await _genericAttributeService.GetAttributeAsync <string>(customer,
                                                                                                    NopCustomerDefaults.SelectedPaymentMethodAttribute, storeId);
            }

            //order sub total (items + checkout attributes)
            var subTotalTaxTotal = decimal.Zero;

            var(_, _, _, _, orderSubTotalTaxRates) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, false);

            foreach (var kvp in orderSubTotalTaxRates)
            {
                var taxRate  = kvp.Key;
                var taxValue = kvp.Value;
                subTotalTaxTotal += taxValue;

                if (taxRate <= decimal.Zero || taxValue <= decimal.Zero)
                {
                    continue;
                }

                if (!taxRates.ContainsKey(taxRate))
                {
                    taxRates.Add(taxRate, taxValue);
                }
                else
                {
                    taxRates[taxRate] = taxRates[taxRate] + taxValue;
                }
            }

            //shipping
            var shippingTax = decimal.Zero;

            if (_taxSettings.ShippingIsTaxable)
            {
                var(shippingExclTax, _, _) = await _orderTotalCalculationService.GetShoppingCartShippingTotalAsync(cart, false);

                var(shippingInclTax, taxRate, _) = await _orderTotalCalculationService.GetShoppingCartShippingTotalAsync(cart, true);

                if (shippingExclTax.HasValue && shippingInclTax.HasValue)
                {
                    shippingTax = shippingInclTax.Value - shippingExclTax.Value;
                    //ensure that tax is equal or greater than zero
                    if (shippingTax < decimal.Zero)
                    {
                        shippingTax = decimal.Zero;
                    }

                    //tax rates
                    if (taxRate > decimal.Zero && shippingTax > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(taxRate))
                        {
                            taxRates.Add(taxRate, shippingTax);
                        }
                        else
                        {
                            taxRates[taxRate] = taxRates[taxRate] + shippingTax;
                        }
                    }
                }
            }

            //payment method additional fee
            var paymentMethodAdditionalFeeTax = decimal.Zero;

            if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                var paymentMethodAdditionalFee = await _paymentService.GetAdditionalHandlingFeeAsync(cart, paymentMethodSystemName);

                var(paymentMethodAdditionalFeeExclTax, _) = await _taxService.GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, false, customer);

                var(paymentMethodAdditionalFeeInclTax, taxRate) = await _taxService.GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, true, customer);

                paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;
                //ensure that tax is equal or greater than zero
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                {
                    paymentMethodAdditionalFeeTax = decimal.Zero;
                }

                //tax rates
                if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }

            //add at least one tax rate (0%)
            if (!taxRates.Any())
            {
                taxRates.Add(decimal.Zero, decimal.Zero);
            }

            //summarize taxes
            var taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;

            //ensure that tax is equal or greater than zero
            if (taxTotal < decimal.Zero)
            {
                taxTotal = decimal.Zero;
            }

            return(new TaxTotalResult {
                TaxTotal = taxTotal, TaxRates = taxRates
            });
        }
        /// <summary>
        /// Handle shopping cart changed event
        /// </summary>
        /// <param name="cartItem">Shopping cart item</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task HandleShoppingCartChangedEventAsync(ShoppingCartItem cartItem)
        {
            //whether marketing automation is enabled
            if (!_sendinblueSettings.UseMarketingAutomation)
            {
                return;
            }

            var customer = await _customerService.GetCustomerByIdAsync(cartItem.CustomerId);

            try
            {
                //create API client
                var client = CreateMarketingAutomationClient();

                //first, try to identify current customer
                await client.IdentifyAsync(new Identify(customer.Email));

                //get shopping cart GUID
                var shoppingCartGuid = await _genericAttributeService
                                       .GetAttributeAsync <Guid?>(customer, SendinblueDefaults.ShoppingCartGuidAttribute);

                //create track event object
                var trackEvent = new TrackEvent(customer.Email, string.Empty);

                //get current customer's shopping cart
                var store = await _storeContext.GetCurrentStoreAsync();

                var cart = await _shoppingCartService
                           .GetShoppingCartAsync(customer, ShoppingCartType.ShoppingCart, store.Id);

                if (cart.Any())
                {
                    //get URL helper
                    var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                    //get shopping cart amounts
                    var(_, cartDiscount, _, cartSubtotal, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart,
                                                                                                                                await _workContext.GetTaxDisplayTypeAsync() == TaxDisplayType.IncludingTax);

                    var cartTax = await _orderTotalCalculationService.GetTaxTotalAsync(cart, false);

                    var cartShipping = await _orderTotalCalculationService.GetShoppingCartShippingTotalAsync(cart);

                    var(cartTotal, _, _, _, _, _) = await _orderTotalCalculationService.GetShoppingCartTotalAsync(cart, false, false);

                    //get products data by shopping cart items
                    var itemsData = await cart.Where(item => item.ProductId != 0).SelectAwait(async item =>
                    {
                        var product = await _productService.GetProductByIdAsync(item.ProductId);

                        //try to get product attribute combination
                        var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, item.AttributesXml);

                        //get default product picture
                        var picture = await _pictureService.GetProductPictureAsync(product, item.AttributesXml);

                        //get product SEO slug name
                        var seName = await _urlRecordService.GetSeNameAsync(product);

                        //create product data
                        return(new
                        {
                            id = product.Id,
                            name = product.Name,
                            variant_id = combination?.Id ?? product.Id,
                            variant_name = combination?.Sku ?? product.Name,
                            sku = combination?.Sku ?? product.Sku,
                            category = await(await _categoryService.GetProductCategoriesByProductIdAsync(item.ProductId)).AggregateAwaitAsync(",", async(all, pc) =>
                            {
                                var res = (await _categoryService.GetCategoryByIdAsync(pc.CategoryId)).Name;
                                res = all == "," ? res : all + ", " + res;
                                return res;
                            }),
                            url = urlHelper.RouteUrl("Product", new { SeName = seName }, _webHelper.GetCurrentRequestProtocol()),
                            image = (await _pictureService.GetPictureUrlAsync(picture)).Url,
                            quantity = item.Quantity,
                            price = (await _shoppingCartService.GetSubTotalAsync(item, true)).subTotal
                        });
                    }).ToArrayAsync();

                    //prepare cart data
                    var cartData = new
                    {
                        affiliation      = store.Name,
                        subtotal         = cartSubtotal,
                        shipping         = cartShipping ?? decimal.Zero,
                        total_before_tax = cartSubtotal + cartShipping ?? decimal.Zero,
                        tax      = cartTax,
                        discount = cartDiscount,
                        revenue  = cartTotal ?? decimal.Zero,
                        url      = urlHelper.RouteUrl("ShoppingCart", null, _webHelper.GetCurrentRequestProtocol()),
                        currency = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode,
                        //gift_wrapping = string.Empty, //currently we can't get this value
                        items = itemsData
                    };

                    //if there is a single item in the cart, so the cart is just created
                    if (cart.Count == 1)
                    {
                        shoppingCartGuid = Guid.NewGuid();
                    }
                    else
                    {
                        //otherwise cart is updated
                        shoppingCartGuid ??= Guid.NewGuid();
                    }
                    trackEvent.EventName = SendinblueDefaults.CartUpdatedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}", data = cartData };
                }
                else
                {
                    //there are no items in the cart, so the cart is deleted
                    shoppingCartGuid ??= Guid.NewGuid();
                    trackEvent.EventName = SendinblueDefaults.CartDeletedEventName;
                    trackEvent.EventData = new { id = $"cart:{shoppingCartGuid}" };
                }

                //track event
                await client.TrackEventAsync(trackEvent);

                //update GUID for the current customer's shopping cart
                await _genericAttributeService.SaveAttributeAsync(customer, SendinblueDefaults.ShoppingCartGuidAttribute, shoppingCartGuid);
            }
            catch (Exception exception)
            {
                //log full error
                await _logger.ErrorAsync($"Sendinblue Marketing Automation error: {exception.Message}.", exception, customer);
            }
        }
        /// <summary>
        /// Gets tax total
        /// </summary>
        /// <param name="taxTotalRequest">Tax total request</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the ax total
        /// </returns>
        public async Task <TaxTotalResult> GetTaxTotalAsync(TaxTotalRequest taxTotalRequest)
        {
            if (_httpContextAccessor.HttpContext.Items.TryGetValue("nop.TaxTotal", out var result) &&
                result is (TaxTotalResult taxTotalResult, decimal paymentTax))
            {
                //short-circuit to avoid circular reference when calculating payment method additional fee during the checkout process
                if (!taxTotalRequest.UsePaymentMethodAdditionalFee)
                {
                    return new TaxTotalResult {
                               TaxTotal = taxTotalResult.TaxTotal - paymentTax
                    }
                }
                ;

                return(taxTotalResult);
            }

            var taxRates = new SortedDictionary <decimal, decimal>();
            var taxTotal = decimal.Zero;

            //order sub total (items + checkout attributes)
            var(_, _, _, _, orderSubTotalTaxRates) = await _orderTotalCalculationService
                                                     .GetShoppingCartSubTotalAsync(taxTotalRequest.ShoppingCart, false);

            var subTotalTaxTotal = decimal.Zero;

            foreach (var kvp in orderSubTotalTaxRates)
            {
                var taxRate  = kvp.Key;
                var taxValue = kvp.Value;
                subTotalTaxTotal += taxValue;

                if (taxRate > decimal.Zero && taxValue > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, taxValue);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + taxValue;
                    }
                }
            }
            taxTotal += subTotalTaxTotal;

            //shipping
            var shippingTax = decimal.Zero;

            if (_taxSettings.ShippingIsTaxable)
            {
                var(shippingExclTax, _, _) = await _orderTotalCalculationService
                                             .GetShoppingCartShippingTotalAsync(taxTotalRequest.ShoppingCart, false);

                var(shippingInclTax, taxRate, _) = await _orderTotalCalculationService
                                                   .GetShoppingCartShippingTotalAsync(taxTotalRequest.ShoppingCart, true);

                if (shippingExclTax.HasValue && shippingInclTax.HasValue)
                {
                    shippingTax = shippingInclTax.Value - shippingExclTax.Value;

                    if (shippingTax < decimal.Zero)
                    {
                        shippingTax = decimal.Zero;
                    }

                    if (taxRate > decimal.Zero && shippingTax > decimal.Zero)
                    {
                        if (!taxRates.ContainsKey(taxRate))
                        {
                            taxRates.Add(taxRate, shippingTax);
                        }
                        else
                        {
                            taxRates[taxRate] = taxRates[taxRate] + shippingTax;
                        }
                    }
                }
            }
            taxTotal += shippingTax;

            //short-circuit to avoid circular reference when calculating payment method additional fee during the checkout process
            if (!taxTotalRequest.UsePaymentMethodAdditionalFee)
            {
                return new TaxTotalResult {
                           TaxTotal = taxTotal
                }
            }
            ;

            //payment method additional fee
            var paymentMethodAdditionalFeeTax = decimal.Zero;

            if (_taxSettings.PaymentMethodAdditionalFeeIsTaxable)
            {
                var paymentMethodSystemName = taxTotalRequest.Customer != null
                    ? await _genericAttributeService
                                              .GetAttributeAsync <string>(taxTotalRequest.Customer, NopCustomerDefaults.SelectedPaymentMethodAttribute, taxTotalRequest.StoreId)
                    : string.Empty;

                var paymentMethodAdditionalFee = await _paymentService
                                                 .GetAdditionalHandlingFeeAsync(taxTotalRequest.ShoppingCart, paymentMethodSystemName);

                var(paymentMethodAdditionalFeeExclTax, _) = await _taxService
                                                            .GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, false, taxTotalRequest.Customer);

                var(paymentMethodAdditionalFeeInclTax, taxRate) = await _taxService
                                                                  .GetPaymentMethodAdditionalFeeAsync(paymentMethodAdditionalFee, true, taxTotalRequest.Customer);

                paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;
                if (paymentMethodAdditionalFeeTax < decimal.Zero)
                {
                    paymentMethodAdditionalFeeTax = decimal.Zero;
                }

                if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
                {
                    if (!taxRates.ContainsKey(taxRate))
                    {
                        taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
                    }
                    else
                    {
                        taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;
                    }
                }
            }
            taxTotal += paymentMethodAdditionalFeeTax;

            //add at least one tax rate (0%)
            if (!taxRates.Any())
            {
                taxRates.Add(decimal.Zero, decimal.Zero);
            }

            if (taxTotal < decimal.Zero)
            {
                taxTotal = decimal.Zero;
            }

            taxTotalResult = new TaxTotalResult {
                TaxTotal = taxTotal, TaxRates = taxRates,
            };

            //store values within the scope of the request to avoid duplicate calculations
            _httpContextAccessor.HttpContext.Items.TryAdd("nop.TaxTotal", (taxTotalResult, paymentMethodAdditionalFeeTax));

            return(taxTotalResult);
        }
Пример #6
0
        /// <summary>
        /// Create packages (total dimensions of shopping cart items determines number of packages)
        /// </summary>
        /// <param name="shippingOptionRequest">shipping option request</param>
        /// <returns>Packages</returns>
        private async Task <IEnumerable <UPSRate.PackageType> > GetPackagesByDimensionsAsync(GetShippingOptionRequest shippingOptionRequest)
        {
            //get dimensions and weight of the whole package
            var(width, length, height) = await GetDimensionsAsync(shippingOptionRequest.Items);

            var weight = await GetWeightAsync(shippingOptionRequest);

            //whether the package doesn't exceed the weight and size limits
            var weightLimit = await GetWeightLimitAsync();

            var sizeLimit = await GetSizeLimitAsync();

            if (weight <= weightLimit && GetPackageSize(width, length, height) <= sizeLimit)
            {
                var insuranceAmount = 0;
                if (_upsSettings.InsurePackage)
                {
                    //The maximum declared amount per package: 50000 USD.
                    //use subTotalWithoutDiscount as insured value
                    var cart = shippingOptionRequest.Items.Select(item =>
                    {
                        var shoppingCartItem      = item.ShoppingCartItem;
                        shoppingCartItem.Quantity = item.GetQuantity();
                        return(shoppingCartItem);
                    }).ToList();
                    var(_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, false);

                    insuranceAmount = Convert.ToInt32(subTotalWithoutDiscount);
                }

                return(new[] { await CreatePackageAsync(width, length, height, weight, insuranceAmount) });
            }

            //get total packages number according to package limits
            var totalPackagesByWeightLimit = weight > weightLimit
                ? Convert.ToInt32(Math.Ceiling(weight / weightLimit))
                : 1;

            var totalPackagesBySizeLimit = GetPackageSize(width, length, height) > sizeLimit
                ? Convert.ToInt32(Math.Ceiling(GetPackageSize(width, length, height) / await GetLengthLimitAsync()))
                : 1;

            var totalPackages = Math.Max(Math.Max(totalPackagesBySizeLimit, totalPackagesByWeightLimit), 1);

            width  = Math.Max(width / totalPackages, 1);
            length = Math.Max(length / totalPackages, 1);
            height = Math.Max(height / totalPackages, 1);
            weight = Math.Max(weight / totalPackages, 1);

            var insuranceAmountPerPackage = 0;

            if (_upsSettings.InsurePackage)
            {
                //The maximum declared amount per package: 50000 USD.
                //use subTotalWithoutDiscount as insured value
                var cart = shippingOptionRequest.Items.Select(item =>
                {
                    var shoppingCartItem      = item.ShoppingCartItem;
                    shoppingCartItem.Quantity = item.GetQuantity();
                    return(shoppingCartItem);
                }).ToList();
                var(_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, false);

                insuranceAmountPerPackage = Convert.ToInt32(subTotalWithoutDiscount / totalPackages);
            }

            //create packages according to calculated value
            var package = await CreatePackageAsync(width, length, height, weight, insuranceAmountPerPackage);

            return(Enumerable.Repeat(package, totalPackages));
        }
        public async Task CanGetShoppingCartSubTotalExcludingTax()
        {
            //10% - default tax rate
            var(discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates) = await _orderTotalCalcService.GetShoppingCartSubTotalAsync(await GetShoppingCartAsync(), false);

            discountAmount.Should().Be(0);
            appliedDiscounts.Count.Should().Be(0);
            subTotalWithoutDiscount.Should().Be(207M);
            subTotalWithDiscount.Should().Be(207M);
            taxRates.Count.Should().Be(1);
            taxRates.ContainsKey(10).Should().BeTrue();
            taxRates[10].Should().Be(20.7M);
        }
        /// <summary>
        /// Create request details to get shipping rates
        /// </summary>
        /// <param name="shippingOptionRequest">Shipping option request</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the rate request details
        /// </returns>
        private async Task <(RateRequest rateRequest, Currency requestedShipmentCurrency)> CreateRateRequestAsync(GetShippingOptionRequest shippingOptionRequest)
        {
            // Build the RateRequest
            var request = new RateRequest
            {
                WebAuthenticationDetail = new WebAuthenticationDetail
                {
                    UserCredential = new WebAuthenticationCredential
                    {
                        Key      = _fedexSettings.Key,
                        Password = _fedexSettings.Password
                    }
                },

                ClientDetail = new ClientDetail
                {
                    AccountNumber = _fedexSettings.AccountNumber,
                    MeterNumber   = _fedexSettings.MeterNumber
                },

                TransactionDetail = new TransactionDetail
                {
                    CustomerTransactionId = "***Rate Available Services v16 Request - nopCommerce***" // This is a reference field for the customer.  Any value can be used and will be provided in the response.
                },

                Version = new VersionId(), // WSDL version information, value is automatically set from wsdl

                ReturnTransitAndCommit          = true,
                ReturnTransitAndCommitSpecified = true,
                // Insert the Carriers you would like to see the rates for
                CarrierCodes = new[] {
                    CarrierCodeType.FDXE,
                    CarrierCodeType.FDXG
                }
            };

            //TODO we should use getShippingOptionRequest.Items.GetQuantity() method to get subtotal
            var(_, _, _, subTotalWithDiscountBase, _) = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(
                shippingOptionRequest.Items.Select(x => x.ShoppingCartItem).ToList(),
                false);

            request.RequestedShipment = new RequestedShipment();

            SetOrigin(request, shippingOptionRequest);
            await SetDestinationAsync(request, shippingOptionRequest);

            var requestedShipmentCurrency = await GetRequestedShipmentCurrencyAsync(
                request.RequestedShipment.Shipper.Address.CountryCode,    // origin
                request.RequestedShipment.Recipient.Address.CountryCode); // destination

            decimal subTotalShipmentCurrency;
            var     primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId);

            if (requestedShipmentCurrency.CurrencyCode == primaryStoreCurrency.CurrencyCode)
            {
                subTotalShipmentCurrency = subTotalWithDiscountBase;
            }
            else
            {
                subTotalShipmentCurrency = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(subTotalWithDiscountBase, requestedShipmentCurrency);
            }

            Debug.WriteLine($"SubTotal (Primary Currency) : {subTotalWithDiscountBase} ({primaryStoreCurrency.CurrencyCode})");
            Debug.WriteLine($"SubTotal (Shipment Currency): {subTotalShipmentCurrency} ({requestedShipmentCurrency.CurrencyCode})");

            SetShipmentDetails(request, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode);
            SetPayment(request);

            //set packages details
            switch (_fedexSettings.PackingType)
            {
            case PackingType.PackByOneItemPerPackage:
                await SetIndividualPackageLineItemsOneItemPerPackageAsync(request, shippingOptionRequest, requestedShipmentCurrency.CurrencyCode);

                break;

            case PackingType.PackByVolume:
                await SetIndividualPackageLineItemsCubicRootDimensionsAsync(request, shippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode);

                break;

            case PackingType.PackByDimensions:
            default:
                await SetIndividualPackageLineItemsAsync(request, shippingOptionRequest, subTotalShipmentCurrency, requestedShipmentCurrency.CurrencyCode);

                break;
            }
            return(request, requestedShipmentCurrency);
        }
Пример #9
0
        /// <summary>
        /// Invokes the view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>The <see cref="Task"/> containing the <see cref="IViewComponentResult"/></returns>
        public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData)
        {
            if (!await _openPayService.CanDisplayWidgetAsync())
            {
                return(Content(string.Empty));
            }

            if (widgetZone == PublicWidgetZones.BodyEndHtmlTagBefore)
            {
                if (!_openPayPaymentSettings.DisplayLandingPageWidget)
                {
                    return(Content(string.Empty));
                }

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/LandingPageLink.cshtml"));
            }

            var region = Defaults.OpenPay.AvailableRegions.FirstOrDefault(
                region => region.IsSandbox == _openPayPaymentSettings.UseSandbox && region.TwoLetterIsoCode == _openPayPaymentSettings.RegionTwoLetterIsoCode);

            var workingCurrency = await _workContext.GetWorkingCurrencyAsync();

            Task <decimal> toWorkingCurrencyAsync(decimal price) => _currencyService.ConvertFromPrimaryStoreCurrencyAsync(price, workingCurrency);

            var model = new WidgetModel
            {
                WidgetCode         = region.WidgetCode,
                RegionCode         = region.TwoLetterIsoCode,
                CurrencyCode       = workingCurrency.CurrencyCode,
                CurrencyFormatting = workingCurrency.CustomFormatting,
                PlanTiers          = _openPayPaymentSettings.PlanTiers.Split(',').Select(x => int.Parse(x)).ToArray(),
                MinEligibleAmount  = await toWorkingCurrencyAsync(_openPayPaymentSettings.MinOrderTotal),
                MaxEligibleAmount  = await toWorkingCurrencyAsync(_openPayPaymentSettings.MaxOrderTotal),
                Type = "Online"
            };

            if (widgetZone == PublicWidgetZones.ProductDetailsBottom && additionalData is ProductDetailsModel productDetailsModel)
            {
                if (!_openPayPaymentSettings.DisplayProductPageWidget)
                {
                    return(Content(string.Empty));
                }

                var product = await _productService.GetProductByIdAsync(productDetailsModel.Id);

                if (product == null || product.Deleted || product.IsDownload || !product.IsShipEnabled)
                {
                    return(Content(string.Empty));
                }

                model.Logo         = _openPayPaymentSettings.ProductPageWidgetLogo;
                model.LogoPosition = _openPayPaymentSettings.ProductPageWidgetLogoPosition;
                model.Amount       = productDetailsModel.ProductPrice.PriceValue;

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/ProductPage.cshtml", model));
            }

            if (widgetZone == PublicWidgetZones.ProductBoxAddinfoMiddle && additionalData is ProductOverviewModel productOverviewModel)
            {
                if (!_openPayPaymentSettings.DisplayProductListingWidget)
                {
                    return(Content(string.Empty));
                }

                var product = await _productService.GetProductByIdAsync(productOverviewModel.Id);

                if (product == null || product.Deleted || product.IsDownload || !product.IsShipEnabled)
                {
                    return(Content(string.Empty));
                }

                model.Logo     = _openPayPaymentSettings.ProductListingWidgetLogo;
                model.HideLogo = _openPayPaymentSettings.ProductListingHideLogo;
                model.Amount   = productOverviewModel.ProductPrice.PriceValue ?? decimal.Zero;

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/ProductListing.cshtml", model));
            }

            if (widgetZone == PublicWidgetZones.OrderSummaryContentAfter)
            {
                if (!_openPayPaymentSettings.DisplayCartWidget)
                {
                    return(Content(string.Empty));
                }

                var routeName = HttpContext.GetEndpoint()?.Metadata.GetMetadata <RouteNameMetadata>()?.RouteName;
                if (routeName != Defaults.ShoppingCartRouteName)
                {
                    return(Content(string.Empty));
                }

                var customer = await _workContext.GetCurrentCustomerAsync();

                var store = await _storeContext.GetCurrentStoreAsync();

                var cart = await _shoppingCartService.GetShoppingCartAsync(customer, ShoppingCartType.ShoppingCart, store.Id);

                if (cart == null || !cart.Any())
                {
                    return(Content(string.Empty));
                }

                if (!await _shoppingCartService.ShoppingCartRequiresShippingAsync(cart))
                {
                    return(Content(string.Empty));
                }

                var shoppingCartTotal = decimal.Zero;

                var cartTotal = await _orderTotalCalculationService.GetShoppingCartTotalAsync(cart);

                if (cartTotal.shoppingCartTotal.HasValue)
                {
                    shoppingCartTotal = cartTotal.shoppingCartTotal.Value;
                }
                else
                {
                    var cartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotalAsync(cart, true);

                    shoppingCartTotal = cartSubTotal.subTotalWithDiscount;
                }

                model.Logo   = _openPayPaymentSettings.CartWidgetLogo;
                model.Amount = await toWorkingCurrencyAsync(shoppingCartTotal);

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/Cart.cshtml", model));
            }

            if (widgetZone == PublicWidgetZones.BodyStartHtmlTagAfter)
            {
                if (!_openPayPaymentSettings.DisplayInfoBeltWidget)
                {
                    return(Content(string.Empty));
                }

                model.Color = _openPayPaymentSettings.InfoBeltWidgetColor;

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/InfoBelt.cshtml", model));
            }

            if (widgetZone == "OpenPayLandingPage")
            {
                if (!_openPayPaymentSettings.DisplayLandingPageWidget)
                {
                    return(Content(string.Empty));
                }

                return(View("~/Plugins/Payments.OpenPay/Views/Widget/LandingPage.cshtml", model));
            }

            return(Content(string.Empty));
        }