示例#1
0
        private async Task <OrderItem> PrepareDefaultOrderItemFromProductAsync(Order order, Product product)
        {
            var customer = await CustomerService.GetCustomerByIdAsync(order.CustomerId);

            var presetQty = 1;
            var price     = await _priceCalculationService.GetFinalPriceAsync(product, customer, decimal.Zero, true, presetQty);

            var(priceInclTax, _) = await _taxService.GetProductPriceAsync(product, price.finalPrice, includingTax : true, customer);

            var(priceExclTax, _) = await _taxService.GetProductPriceAsync(product, price.finalPrice, includingTax : false, customer);

            var orderItem = new OrderItem
            {
                OrderItemGuid       = new Guid(),
                UnitPriceExclTax    = priceExclTax,
                UnitPriceInclTax    = priceInclTax,
                PriceInclTax        = priceInclTax,
                PriceExclTax        = priceExclTax,
                OriginalProductCost = await _priceCalculationService.GetProductCostAsync(product, null),
                Quantity            = presetQty,
                ProductId           = product.Id,
                OrderId             = order.Id
            };

            return(orderItem);
        }
示例#2
0
        /// <summary>
        ///		Write to the XmlWriter all needed element data for the prices.
        /// </summary>
        /// <param name="xml">
        ///		This XmlWriter should already be prepared.
        ///		This method is responsible for populating the price elements.
        /// </param>
        /// <param name="product">
        ///		This is product from which this exports data.
        /// </param>
        private async Task ExportPricesAsync(XmlWriter xml, Product product)
        {
            var searchCustomer = await _customerService.InsertGuestCustomerAsync();

            decimal price     = product.OldPrice;
            decimal salePrice = (await _priceCalculationService.GetFinalPriceAsync(
                                     product, searchCustomer, 0, true, 1)).finalPrice;

            WriteElementHelper(xml, _priceTag, price.ToString());
            WriteElementHelper(xml, _salePriceTag, salePrice.ToString());

            var cartProduct = _productCartPriceRepository.Table.Where(pcp => pcp.Product_Id == product.Id).FirstOrDefault();

            if (cartProduct != null)
            {
                WriteElementHelper(xml, "MAPPricing", true.ToString());
            }

            if (product.CallForPrice)
            {
                WriteElementHelper(xml, "Call_Price", true.ToString());
            }



            return;
        }
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the view component result
        /// </returns>
        public async Task <IViewComponentResult> InvokeAsync(string widgetZone, object additionalData)
        {
            var customer = await _workContext.GetCurrentCustomerAsync();

            var store = await _storeContext.GetCurrentStoreAsync();

            if (!await _paymentPluginManager.IsPluginActiveAsync(PayPalCommerceDefaults.SystemName, customer, store?.Id ?? 0))
            {
                return(Content(string.Empty));
            }

            if (!ServiceManager.IsConfigured(_settings))
            {
                return(Content(string.Empty));
            }

            if (!widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter))
            {
                return(Content(string.Empty));
            }

            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter))
            {
                if (!_settings.DisplayButtonsOnShoppingCart)
                {
                    return(Content(string.Empty));
                }

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

            if (widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !_settings.DisplayButtonsOnProductDetails)
            {
                return(Content(string.Empty));
            }

            var productId   = additionalData is ProductDetailsModel.AddToCartModel model ? model.ProductId : 0;
            var productCost = "0.00";

            if (productId > 0)
            {
                var product = await _productServise.GetProductByIdAsync(productId);

                var finalPrice = (await _priceCalculationService.GetFinalPriceAsync(product, customer)).finalPrice;
                productCost = finalPrice.ToString("0.00", CultureInfo.InvariantCulture);
            }
            return(View("~/Plugins/Payments.PayPalCommerce/Views/Buttons.cshtml", (widgetZone, productId, productCost)));
        }
示例#4
0
        public async Task <List <ProductDetailsModel.TierPriceModel> > CreateTierPriceModelAsync(Product product, decimal adjustment = decimal.Zero)
        {
            var model = await product.TierPrices
                        .OrderBy(x => x.Quantity)
                        .FilterByStore(_services.StoreContext.CurrentStore.Id)
                        .FilterForCustomer(_services.WorkContext.CurrentCustomer)
                        .ToList()
                        .RemoveDuplicatedQuantities()
                        .SelectAsync(async(tierPrice) =>
            {
                var m = new ProductDetailsModel.TierPriceModel
                {
                    Quantity = tierPrice.Quantity,
                };

                if (adjustment != 0 && tierPrice.CalculationMethod == TierPriceCalculationMethod.Percental && _catalogSettings.ApplyTierPricePercentageToAttributePriceAdjustments)
                {
                    adjustment -= (adjustment / 100 * tierPrice.Price);
                }
                else
                {
                    adjustment = decimal.Zero;
                }

                var adjustmentAmount = adjustment == 0 ? (Money?)null : new Money(adjustment, _currencyService.PrimaryCurrency);
                var priceBase        = default(Money);
                var taxRate          = decimal.Zero;
                var finalPriceBase   = await _priceCalculationService.GetFinalPriceAsync(product,
                                                                                         adjustmentAmount,
                                                                                         _services.WorkContext.CurrentCustomer,
                                                                                         _catalogSettings.DisplayTierPricesWithDiscounts,
                                                                                         tierPrice.Quantity, null, null, true);

                (priceBase, taxRate) = await _taxService.GetProductPriceAsync(product, finalPriceBase);
                m.Price = _currencyService.ConvertToWorkingCurrency(priceBase);

                return(m);
            })
                        .AsyncToList();

            return(model);
        }
        public async Task CanGetFinalProductPrice()
        {
            var product = await _productService.GetProductBySkuAsync("BP_20_WSP");

            //customer
            var customer = new Customer();

            var(finalPriceWithoutDiscounts, finalPrice, _, _) = await _priceCalcService.GetFinalPriceAsync(product, customer, 0, false);

            finalPrice.Should().Be(79.99M);
            finalPrice.Should().Be(finalPriceWithoutDiscounts);

            (finalPriceWithoutDiscounts, finalPrice, _, _) = await _priceCalcService.GetFinalPriceAsync(product, customer, 0, false, 2);

            finalPrice.Should().Be(19M);
            finalPriceWithoutDiscounts.Should().Be(finalPriceWithoutDiscounts);
        }
示例#6
0
        public async override Task <(decimal unitPrice, decimal discountAmount, List <Discount> appliedDiscounts)> GetUnitPriceAsync(
            Product product,
            Customer customer,
            ShoppingCartType shoppingCartType,
            int quantity,
            string attributesXml,
            decimal customerEnteredPrice,
            DateTime?rentalStartDate, DateTime?rentalEndDate,
            bool includeDiscounts)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var discountAmount   = decimal.Zero;
            var appliedDiscounts = new List <Discount>();

            decimal finalPrice;

            var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, attributesXml);

            if (combination?.OverriddenPrice.HasValue ?? false)
            {
                (_, finalPrice, discountAmount, appliedDiscounts) = await _priceCalculationService.GetFinalPriceAsync(product,
                                                                                                                      customer,
                                                                                                                      combination.OverriddenPrice.Value,
                                                                                                                      decimal.Zero,
                                                                                                                      includeDiscounts,
                                                                                                                      quantity,
                                                                                                                      product.IsRental?rentalStartDate : null,
                                                                                                                      product.IsRental?rentalEndDate : null);
            }
            else
            {
                // custom
                // summarize price of all attributes except warranties (warranties processed separately)
                decimal warrantyPrice = decimal.Zero;
                ProductAttributeMapping warrantyPam = await _attributeUtilities.GetWarrantyAttributeMappingAsync(attributesXml);

                //summarize price of all attributes
                var attributesTotalPrice = decimal.Zero;
                var attributeValues      = await _productAttributeParser.ParseProductAttributeValuesAsync(attributesXml);

                // custom - considers warranties
                if (attributeValues != null)
                {
                    foreach (var attributeValue in attributeValues)
                    {
                        if (warrantyPam != null && attributeValue.ProductAttributeMappingId == warrantyPam.Id)
                        {
                            warrantyPrice =
                                await _priceCalculationService.GetProductAttributeValuePriceAdjustmentAsync(
                                    product,
                                    attributeValue,
                                    customer,
                                    product.CustomerEntersPrice?(decimal?)customerEnteredPrice : null
                                    );
                        }
                        else
                        {
                            attributesTotalPrice += await _priceCalculationService.GetProductAttributeValuePriceAdjustmentAsync(
                                product,
                                attributeValue,
                                customer,
                                product.CustomerEntersPrice?(decimal?)customerEnteredPrice : null
                                );
                        }
                    }
                }

                //get price of a product (with previously calculated price of all attributes)
                if (product.CustomerEntersPrice)
                {
                    finalPrice = customerEnteredPrice;
                }
                else
                {
                    int qty;
                    if (_shoppingCartSettings.GroupTierPricesForDistinctShoppingCartItems)
                    {
                        //the same products with distinct product attributes could be stored as distinct "ShoppingCartItem" records
                        //so let's find how many of the current products are in the cart
                        qty = (await GetShoppingCartAsync(customer, shoppingCartType: shoppingCartType, productId: product.Id))
                              .Sum(x => x.Quantity);

                        if (qty == 0)
                        {
                            qty = quantity;
                        }
                    }
                    else
                    {
                        qty = quantity;
                    }

                    (_, finalPrice, discountAmount, appliedDiscounts) = await _priceCalculationService.GetFinalPriceAsync(product,
                                                                                                                          customer,
                                                                                                                          attributesTotalPrice,
                                                                                                                          includeDiscounts,
                                                                                                                          qty,
                                                                                                                          product.IsRental?rentalStartDate : null,
                                                                                                                          product.IsRental?rentalEndDate : null);

                    finalPrice += warrantyPrice;
                }
            }

            //rounding
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
            {
                finalPrice = await _priceCalculationService.RoundPriceAsync(finalPrice);
            }

            return(finalPrice, discountAmount, appliedDiscounts);
        }