Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix wrong calculation of voucher discount for checkout and order

Maciej Korycinskifeabcf3c68e3
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 51be829e38..a69414fa91 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -101,38 +101,40 @@ def remove_unavailable_variants(checkout):
add_variant_to_checkout(checkout, line.variant, quantity, replace=True)
-def get_variant_prices_from_lines(lines):
- """Get's price of each individual item within the lines."""
- return [line.variant.get_price() for line in lines for item in range(line.quantity)]
-
-
-def get_prices_of_discounted_products(lines, discounted_products):
+def get_prices_of_discounted_products(checkout, discounted_products):
"""Get prices of variants belonging to the discounted products."""
# If there's no discounted_products,
# it means that all products are discounted
+ line_prices = []
if discounted_products:
- lines = (line for line in lines if line.variant.product in discounted_products)
- return get_variant_prices_from_lines(lines)
+ for line in checkout:
+ if line.variant.product in discounted_products:
+ line_unit_price = (
+ calculate_checkout_line_total(line, []).gross / line.quantity
+ )
+ line_prices.extend([line_unit_price] * line.quantity)
+ return line_prices
-def get_prices_of_products_in_discounted_collections(lines, discounted_collections):
+def get_prices_of_products_in_discounted_collections(checkout, discounted_collections):
"""Get prices of variants belonging to the discounted collections."""
# If there's no discounted collections,
# it means that all of them are discounted
+ line_prices = []
if discounted_collections:
- discounted_collections = set(discounted_collections)
- lines = (
- line
- for line in lines
- if line.variant
- and set(line.variant.product.collections.all()).intersection(
- discounted_collections
- )
- )
- return get_variant_prices_from_lines(lines)
-
-
-def get_prices_of_products_in_discounted_categories(lines, discounted_categories):
+ for line in checkout:
+ if not line.variant:
+ continue
+ product_collections = line.variant.product.collections.all()
+ if set(product_collections).intersection(discounted_collections):
+ line_unit_price = (
+ calculate_checkout_line_total(line, []).gross / line.quantity
+ )
+ line_prices.extend([line_unit_price] * line.quantity)
+ return line_prices
+
+
+def get_prices_of_products_in_discounted_categories(checkout, discounted_categories):
"""Get prices of variants belonging to the discounted categories.
Product must be assigned directly to the discounted category, assigning
@@ -140,14 +142,19 @@ def get_prices_of_products_in_discounted_categories(lines, discounted_categories
"""
# If there's no discounted collections,
# it means that all of them are discounted
+ line_prices = []
if discounted_categories:
discounted_categories = set(discounted_categories)
- lines = (
- line
- for line in lines
- if line.variant and line.variant.product.category in discounted_categories
- )
- return get_variant_prices_from_lines(lines)
+ for line in checkout:
+ if not line.variant:
+ continue
+ product_category = line.variant.product.category
+ if product_category in discounted_categories:
+ line_unit_price = (
+ calculate_checkout_line_total(line, []).gross / line.quantity
+ )
+ line_prices.extend([line_unit_price] * line.quantity)
+ return line_prices
def check_product_availability_and_warn(request, checkout):
@@ -721,21 +728,19 @@ def _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts=Non
)
-def _get_products_voucher_discount(order_or_checkout, voucher):
+def _get_products_voucher_discount(checkout, voucher):
"""Calculate products discount value for a voucher, depending on its type.
"""
prices = None
if voucher.type == VoucherType.PRODUCT:
- prices = get_prices_of_discounted_products(
- order_or_checkout.lines.all(), voucher.products.all()
- )
+ prices = get_prices_of_discounted_products(checkout, voucher.products.all())
elif voucher.type == VoucherType.COLLECTION:
prices = get_prices_of_products_in_discounted_collections(
- order_or_checkout.lines.all(), voucher.collections.all()
+ checkout, voucher.collections.all()
)
elif voucher.type == VoucherType.CATEGORY:
prices = get_prices_of_products_in_discounted_categories(
- order_or_checkout.lines.all(), voucher.categories.all()
+ checkout, voucher.categories.all()
)
if not prices:
msg = pgettext(
@@ -1070,7 +1075,7 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) ->
- checkout.discount_amount
).gross
- preprocess_order_creation(checkout)
+ preprocess_order_creation(checkout, discounts)
return order_data
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
index 9195a8acd4..9f669a3690 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -1,5 +1,4 @@
import logging
-from datetime import date
from decimal import Decimal
from typing import TYPE_CHECKING, List, Union
from urllib.parse import urljoin
@@ -8,7 +7,6 @@ from django.conf import settings
from prices import Money, TaxedMoney
from ....checkout import models as checkout_models
-from ....discount.models import Sale
from .. import ZERO_TAXED_MONEY, TaxType
from ..errors import TaxError
from . import (
@@ -104,13 +102,10 @@ def calculate_checkout_shipping(
return TaxedMoney(net=shipping_net, gross=shipping_gross)
-def preprocess_order_creation(checkout: "Checkout"):
+def preprocess_order_creation(checkout: "Checkout", discounts: List["DiscountInfo"]):
"""Confirm that all data is correct and we can proceed with creation of order.
Raise error when can't receive taxes"""
- discounts = Sale.objects.active(date.today()).prefetch_related(
- "products", "categories", "collections"
- )
data = generate_request_data_from_checkout(
checkout,
transaction_token=str(checkout.token),
@@ -147,6 +142,9 @@ def calculate_checkout_line_total(
checkout_line: "checkout_models.CheckoutLine", discounts: List["DiscountInfo"]
):
checkout = checkout_line.checkout
+ total = checkout_line.get_total(discounts)
+ if not validate_checkout(checkout):
+ return TaxedMoney(net=total, gross=total)
taxes_data = get_checkout_tax_data(checkout, discounts)
currency = taxes_data.get("currencyCode")
for line in taxes_data.get("lines", []):
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index dd6e963810..2a615e2924 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -152,9 +152,9 @@ def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):
return TaxedMoneyRange(start=start, stop=stop)
-def preprocess_order_creation(checkout: "Checkout"):
+def preprocess_order_creation(checkout: "Checkout", discounts: List["DiscountInfo"]):
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.preprocess_order_creation(checkout)
+ return avatax_interface.preprocess_order_creation(checkout, discounts)
# FIXME this should be converted to the plugin action after we introduce plugin
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index 30bdb42ccc..69ffbf4edf 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -2,12 +2,17 @@ from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import get_template
+from django.utils.translation import pgettext
from ...checkout import AddressType
-from ...checkout.utils import _get_products_voucher_discount
from ...core.taxes import ZERO_MONEY
from ...discount import VoucherType
-from ...discount.utils import get_shipping_voucher_discount, get_value_voucher_discount
+from ...discount.models import NotApplicable
+from ...discount.utils import (
+ get_products_voucher_discount,
+ get_shipping_voucher_discount,
+ get_value_voucher_discount,
+)
INVOICE_TEMPLATE = "dashboard/order/pdf/invoice.html"
PACKING_SLIP_TEMPLATE = "dashboard/order/pdf/packing_slip.html"
@@ -73,6 +78,71 @@ def update_order_with_user_addresses(order):
order.save(update_fields=["billing_address", "shipping_address"])
+def get_prices_of_discounted_products(order, discounted_products):
+ """Get prices of variants belonging to the discounted products."""
+ line_prices = []
+ if discounted_products:
+ for line in order:
+ if line.variant.product in discounted_products:
+ line_prices.extend([line.unit_price_gross] * line.quantity)
+ return line_prices
+
+
+def get_prices_of_products_in_discounted_collections(order, discounted_collections):
+ """Get prices of variants belonging to the discounted collections."""
+ line_prices = []
+ if discounted_collections:
+ for line in order:
+ if not line.variant:
+ continue
+ product_collections = line.variant.product.collections.all()
+ if set(product_collections).intersection(discounted_collections):
+ line_prices.extend([line.unit_price_gross] * line.quantity)
+ return line_prices
+
+
+def get_prices_of_products_in_discounted_categories(order, discounted_categories):
+ """Get prices of variants belonging to the discounted categories.
+
+ Product must be assigned directly to the discounted category, assigning
+ product to child category won't work.
+ """
+ # If there's no discounted collections,
+ # it means that all of them are discounted
+ line_prices = []
+ if discounted_categories:
+ discounted_categories = set(discounted_categories)
+ for line in order:
+ if not line.variant:
+ continue
+ product_category = line.variant.product.category
+ if product_category in discounted_categories:
+ line_prices.extend([line.unit_price_gross] * line.quantity)
+ return line_prices
+
+
+def get_products_voucher_discount_for_order(order, voucher):
+ """Calculate products discount value for a voucher, depending on its type.
+ """
+ prices = None
+ if voucher.type == VoucherType.PRODUCT:
+ prices = get_prices_of_discounted_products(order, voucher.products.all())
+ elif voucher.type == VoucherType.COLLECTION:
+ prices = get_prices_of_products_in_discounted_collections(
+ order, voucher.collections.all()
+ )
+ elif voucher.type == VoucherType.CATEGORY:
+ prices = get_prices_of_products_in_discounted_categories(
+ order, voucher.categories.all()
+ )
+ if not prices:
+ msg = pgettext(
+ "Voucher not applicable", "This offer is only valid for selected items."
+ )
+ raise NotApplicable(msg)
+ return get_products_voucher_discount(voucher, prices)
+
+
def get_voucher_discount_for_order(order):
"""Calculate discount value depending on voucher and discount types.
@@ -92,7 +162,7 @@ def get_voucher_discount_for_order(order):
VoucherType.COLLECTION,
VoucherType.CATEGORY,
):
- return _get_products_voucher_discount(order, order.voucher)
+ return get_products_voucher_discount_for_order(order, order.voucher)
raise NotImplementedError("Unknown discount type")
diff --git a/tests/taxes/test_avatax.py b/tests/taxes/test_avatax.py
index f32e16e740..6682806423 100644
--- a/tests/taxes/test_avatax.py
+++ b/tests/taxes/test_avatax.py
@@ -26,12 +26,14 @@ def test_calculate_checkout_line_total(
address_usa,
site_settings,
monkeypatch,
+ shipping_zone,
):
monkeypatch.setattr(
"saleor.core.taxes.avatax.interface.get_cached_tax_codes_or_fetch",
lambda: {"PC040156": "desc"},
)
checkout_with_item.shipping_address = address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.save()
site_settings.company_address = address_usa
site_settings.include_taxes_in_prices = taxes_in_prices
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 50cd8520d4..611415ca78 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -1332,17 +1332,18 @@ def test_change_address_in_checkout_from_user_address_to_other(
assert Address.objects.filter(id=address_id).exists()
-def test_get_prices_of_products_in_discounted_categories(checkout_with_item):
+def test_get_prices_of_products_in_discounted_categories(checkout_with_item, category):
lines = checkout_with_item.lines.all()
- # There's no discounted categories, therefore all of them are discoutned
- discounted_lines = get_prices_of_products_in_discounted_categories(lines, [])
+ discounted_lines = get_prices_of_products_in_discounted_categories(
+ checkout_with_item, [category]
+ )
assert [
line.variant.get_price() for line in lines for item in range(line.quantity)
] == discounted_lines
discounted_category = Category.objects.create(name="discounted", slug="discounted")
discounted_lines = get_prices_of_products_in_discounted_categories(
- lines, [discounted_category]
+ checkout_with_item, [discounted_category]
)
# None of the lines are belongs to the discounted category
assert not discounted_lines