Skip to content

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

Include specific products voucher in checkout discount (#12191)

Iga Karbowiak1d8af456141a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 847e0d865f..5263699188 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,9 @@ All notable, unreleased changes to this project will be documented in this file.
E.g. if you had an order for $13 and applied a 12.5% discount, you would get $11.38 with a $1.62 discount, but now it will be calculated as $11.37 with $1.63 discount.
- Media and image fields now default to returning 4K thumbnails instead of original uploads - #11996 by @patrys
+- Include specific products voucher in checkout discount - #12191 by @IKarbowiak
+ - Make the `specific product` and `apply once per order` voucher discounts visible on `checkout.discount` field.
+ Previously, the discount amount for these vouchers was shown as 0.
### GraphQL API
- Added support for all attributes types in `BulkAttributeValueInput` - #12095 by @SzymJ
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 4445e91846..5229855951 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -25,7 +25,12 @@ def calculate_base_line_unit_price(
channel: "Channel",
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
- """Calculate line unit price including discounts and vouchers."""
+ """Calculate line unit price including discounts and vouchers.
+
+ The price includes sales, specific product and applied once per order
+ voucher discounts.
+ The price does not include the entire order discount.
+ """
total_line_price = calculate_base_line_total_price(
line_info=line_info, channel=channel, discounts=discounts
)
@@ -39,7 +44,12 @@ def calculate_base_line_total_price(
channel: "Channel",
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
- """Calculate line total price including discounts and vouchers."""
+ """Calculate line total price including discounts and vouchers.
+
+ The price includes sales, specific product and applied once per order
+ voucher discounts.
+ The price does not include the entire order discount.
+ """
unit_price = _calculate_base_line_unit_price(
line_info=line_info, channel=channel, discounts=discounts
)
@@ -66,7 +76,11 @@ def _calculate_base_line_unit_price(
channel: "Channel",
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
- """Calculate base line unit price including discounts and vouchers."""
+ """Calculate base line unit price including discounts and vouchers.
+
+ The price includes sales, specific product voucher discounts.
+ The price does not include the entire order discount.
+ """
variant = line_info.variant
variant_price = variant.get_price(
line_info.product,
@@ -192,7 +206,12 @@ def base_checkout_total(
discounts: Iterable[DiscountInfo],
lines: Iterable["CheckoutLineInfo"],
) -> Money:
- """Return the total cost of the checkout."""
+ """Return the total cost of the checkout.
+
+ The price includes sales, shipping, specific product and applied once per order
+ voucher discounts.
+ The price does not include the entire order discount.
+ """
currency = checkout_info.checkout.currency
line_totals = [
calculate_base_line_total_price(
@@ -205,17 +224,7 @@ def base_checkout_total(
subtotal = sum(line_totals, zero_money(currency))
shipping_price = base_checkout_delivery_price(checkout_info, lines)
- discount = checkout_info.checkout.discount
- is_shipping_voucher = (
- checkout_info.voucher.type == VoucherType.SHIPPING
- if checkout_info.voucher
- else False
- )
- # Discount is subtracted from both gross and net values, which may cause negative
- # net value if we are having a discount that covers whole price.
- if not is_shipping_voucher:
- subtotal = max(zero_money(currency), subtotal - discount)
return subtotal + shipping_price
@@ -225,6 +234,12 @@ def base_checkout_subtotal(
currency: str,
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
+ """Return the checkout subtotal value.
+
+ The price includes sales, specific product and applied once per order
+ voucher discounts.
+ The price does not include the entire order discount.
+ """
line_totals = [
calculate_base_line_total_price(
line,
@@ -237,12 +252,50 @@ def base_checkout_subtotal(
return sum(line_totals, zero_money(currency))
+def checkout_total(
+ checkout_info: "CheckoutInfo",
+ discounts: Iterable[DiscountInfo],
+ lines: Iterable["CheckoutLineInfo"],
+) -> Money:
+ """Return the total cost of the checkout including discounts and vouchers.
+
+ It should be used as a based value when no flat rate/tax plugin/tax app is active.
+ """
+ currency = checkout_info.checkout.currency
+ line_totals = [
+ calculate_base_line_total_price(
+ line_info,
+ checkout_info.channel,
+ discounts,
+ )
+ for line_info in lines
+ ]
+ subtotal = sum(line_totals, zero_money(currency))
+
+ shipping_price = base_checkout_delivery_price(checkout_info, lines)
+ discount = checkout_info.checkout.discount
+
+ # only entire_order discount with apply_once_per_order set to False is not
+ # already included in the total price
+ discount_not_included = (
+ checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
+ and not checkout_info.voucher.apply_once_per_order
+ if checkout_info.voucher
+ else False
+ )
+ # Discount is subtracted from both gross and net values, which may cause negative
+ # net value if we are having a discount that covers whole price.
+ if discount_not_included:
+ subtotal = max(zero_money(currency), subtotal - discount)
+ return subtotal + shipping_price
+
+
def apply_checkout_discount_on_checkout_line(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
discounts: Iterable["DiscountInfo"],
- line_unit_price: Money,
+ line_total_price: Money,
):
"""Calculate the checkout line price with discounts.
@@ -256,11 +309,10 @@ def apply_checkout_discount_on_checkout_line(
or voucher.apply_once_per_order
or voucher.type in [VoucherType.SHIPPING, VoucherType.SPECIFIC_PRODUCT]
):
- return line_unit_price
+ return line_total_price
- line_quantity = checkout_line_info.line.quantity
total_discount_amount = checkout_info.checkout.discount_amount
- line_total_price = line_unit_price * line_quantity
+ line_total_price = line_total_price
currency = checkout_info.checkout.currency
lines = list(lines)
@@ -269,19 +321,18 @@ def apply_checkout_discount_on_checkout_line(
# to this line
if len(lines) == 1:
return max(
- (line_total_price - Money(total_discount_amount, currency)) / line_quantity,
+ (line_total_price - Money(total_discount_amount, currency)),
zero_money(currency),
)
# if the checkout has more lines we need to propagate the discount amount
# proportionally to total prices of items
lines_total_prices = [
- calculate_base_line_unit_price(
+ calculate_base_line_total_price(
line_info,
checkout_info.channel,
discounts,
).amount
- * line_info.line.quantity
for line_info in lines
if line_info.line.id != checkout_line_info.line.id
]
@@ -296,7 +347,7 @@ def apply_checkout_discount_on_checkout_line(
else:
discount_amount = line_total_price.amount / total_price * total_discount_amount
return max(
- (line_total_price - Money(discount_amount, currency)) / line_quantity,
+ (line_total_price - Money(discount_amount, currency)),
zero_money(currency),
)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 6eb3fa42d5..88a5b0206c 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -487,10 +487,10 @@ def _get_checkout_base_prices(
unit_price = base_calculations.calculate_base_line_unit_price(
line_info, checkout_info.channel, discounts
)
- unit_price = base_calculations.apply_checkout_discount_on_checkout_line(
- checkout_info, lines, line_info, discounts, unit_price
+ total_price = base_calculations.apply_checkout_discount_on_checkout_line(
+ checkout_info, lines, line_info, discounts, unit_price * quantity
)
- line_total_price = quantize_price(unit_price * quantity, currency)
+ line_total_price = quantize_price(total_price, currency)
subtotal += line_total_price
line.total_price = TaxedMoney(net=line_total_price, gross=line_total_price)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 6a517a4728..50b9eeedda 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -205,7 +205,8 @@ def _create_line_for_order(
if translated_variant_name == variant_name:
translated_variant_name = ""
- # the price with sale discount - base price that is used for total price calculation
+ # the price with sale and discounts applied - base price that is used for
+ # total price calculation
base_unit_price = calculate_base_line_unit_price(
line_info=checkout_line_info, channel=checkout_info.channel, discounts=discounts
)
@@ -423,8 +424,6 @@ def _prepare_order_data(
address=address,
discounts=discounts,
)
- # checkout.discount contains only discounts applied on entire order
- undiscounted_total = taxed_total + checkout.discount
base_shipping_price = base_checkout_delivery_price(checkout_info, lines)
shipping_total = calculations.checkout_shipping_price(
@@ -455,15 +454,13 @@ def _prepare_order_data(
discounts,
prices_entered_with_tax,
)
- # Calculate the discount that was applied for each lines - the sales and voucher
- # discounts on specific products are included on the line level and are not included
- # in the checkout.discount amount.
- line_discounts = zero_taxed_money(checkout.currency)
- for line in order_data["lines"]:
- line_discounts += line.line.undiscounted_total_price - line.line.total_price
-
- # include discounts applied on lines, in order undiscounted total price
- undiscounted_total += line_discounts
+ undiscounted_total = (
+ sum(
+ [line.line.undiscounted_total_price for line in order_data["lines"]],
+ start=zero_taxed_money(taxed_total.currency),
+ )
+ + shipping_total
+ )
order_data.update(
{
diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.py
index 51459a18cb..5a49898879 100644
--- a/saleor/checkout/tests/test_base_calculations.py
+++ b/saleor/checkout/tests/test_base_calculations.py
@@ -749,11 +749,15 @@ def test_base_checkout_total(checkout_with_item, shipping_method, voucher_percen
manager = get_plugins_manager()
channel = checkout_with_item.channel
currency = checkout_with_item.currency
- discount_amount = Money(5, currency)
+
checkout_with_item.shipping_method = shipping_method
+ # only line vouchers are applied on based price so this discount won't be included
+ # in base price
+ discount_amount = Money(5, currency)
checkout_with_item.voucher_code = voucher_percentage.code
checkout_with_item.discount = discount_amount
checkout_with_item.save()
+
checkout_lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, [], manager)
@@ -768,23 +772,30 @@ def test_base_checkout_total(checkout_with_item, shipping_method, voucher_percen
expected_price = (
net * checkout_with_item.lines.first().quantity
+ shipping_channel_listings.price
- - discount_amount
)
assert total == expected_price
-def test_base_checkout_total_high_discount_on_entire_order(
+def test_base_checkout_total_high_discount_on_entire_order_apply_once_per_order(
checkout_with_item, shipping_method, voucher_percentage
):
# given
+ voucher_percentage.apply_once_per_order = True
+ voucher_percentage.save(update_fields=["apply_once_per_order"])
+
+ voucher_channel_listing = voucher_percentage.channel_listings.first()
+ voucher_channel_listing.discount_value = 100
+ voucher_channel_listing.save(update_fields=["discount_value"])
+
manager = get_plugins_manager()
- currency = checkout_with_item.currency
- discount_amount = Money(100, currency)
checkout_with_item.shipping_method = shipping_method
checkout_with_item.voucher_code = voucher_percentage.code
- checkout_with_item.discount = discount_amount
- checkout_with_item.save()
+ checkout_with_item.save(update_fields=["shipping_method", "voucher_code"])
+
+ line = checkout_with_item.lines.first()
+ line.quantity = 1
+ line.save(update_fields=["quantity"])
shipping_price = shipping_method.channel_listings.get(
channel=checkout_with_item.channel
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 932c0e34c1..141ca86506 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -166,6 +166,8 @@ def test_fetch_checkout_prices_if_expired_plugins(
for tax_line in tax_data.lines:
total_price = get_taxed_money(tax_line, "total", currency)
subtotal = subtotal + total_price
+
+ plugins_manager.calculate_checkout_subtotal = Mock(return_value=subtotal)
plugins_manager.calculate_checkout_total = Mock(
return_value=shipping_price + subtotal
)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index bfb2647080..d2b08ccc4b 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -256,19 +256,24 @@ def test_last_change_update_foreign_key(checkout, shipping_method):
@pytest.mark.parametrize(
- "total, min_spent_amount, min_checkout_items_quantity, "
+ "total, min_spent_amount, min_checkout_items_quantity, once_per_order, "
"discount_value, discount_value_type, expected_value",
[
- (20, 20, 2, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
- (20, None, None, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
- (20, 20, 2, 5, DiscountValueType.FIXED, Decimal("5.00")),
- (20, None, None, 5, DiscountValueType.FIXED, Decimal("5.00")),
+ (20, 20, 2, False, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
+ (20, None, None, False, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
+ (20, 20, 2, False, 5, DiscountValueType.FIXED, Decimal("5.00")),
+ (20, None, None, False, 5, DiscountValueType.FIXED, Decimal("5.00")),
+ (20, 20, 2, True, 50, DiscountValueType.PERCENTAGE, Decimal("5.00")),
+ (20, None, None, True, 50, DiscountValueType.PERCENTAGE, Decimal("5.00")),
+ (20, 20, 2, True, 5, DiscountValueType.FIXED, Decimal("5.00")),
+ (20, None, None, True, 5, DiscountValueType.FIXED, Decimal("5.00")),
],
)
-def test_get_discount_for_checkout_value_voucher(
+def test_get_discount_for_checkout_value_entire_order_voucher(
total,
min_spent_amount,
min_checkout_items_quantity,
+ once_per_order,
discount_value,
discount_value_type,
expected_value,
@@ -276,11 +281,13 @@ def test_get_discount_for_checkout_value_voucher(
channel_USD,
checkout_with_items,
):
+ # given
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=discount_value_type,
min_checkout_items_quantity=min_checkout_items_quantity,
+ apply_once_per_order=once_per_order,
)
VoucherChannelListing.objects.create(
voucher=voucher,
@@ -308,7 +315,7 @@ def test_get_discount_for_checkout_value_voucher(
lines = [
CheckoutLineInfo(
line=line,
- channel_listing=line.variant.product.channel_listings.first(),
+ channel_listing=line.variant.channel_listings.first(),
collections=[],
product=line.variant.product,
variant=line.variant,
@@ -317,9 +324,163 @@ def test_get_discount_for_checkout_value_voucher(
for line in checkout_with_items.lines.all()
]
manager = get_plugins_manager()
+
+ # when
discount = get_voucher_discount_for_checkout(
manager, voucher, checkout_info, lines, None, []
)
+
+ # then
+ assert discount == Money(expected_value, "USD")
+
+
+ "prices, min_spent_amount, min_checkout_items_quantity, once_per_order, "
+ "discount_value, discount_value_type, expected_value",
+ [
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ 20,
+ 2,
+ False,
+ 50,
+ DiscountValueType.PERCENTAGE,
+ Decimal("15.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ None,
+ None,
+ False,
+ 50,
+ DiscountValueType.PERCENTAGE,
+ Decimal("15.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ 20,
+ 2,
+ False,
+ 5,
+ DiscountValueType.FIXED,
+ Decimal("10.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ None,
+ None,
+ False,
+ 5,
+ DiscountValueType.FIXED,
+ Decimal("10.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ 20,
+ 2,
+ True,
+ 50,
+ DiscountValueType.PERCENTAGE,
+ Decimal("5.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ None,
+ None,
+ True,
+ 50,
+ DiscountValueType.PERCENTAGE,
+ Decimal("5.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ 20,
+ 2,
+ True,
+ 5,
+ DiscountValueType.FIXED,
+ Decimal("5.00"),
+ ),
+ (
+ [Money(10, "USD"), Money(20, "USD")],
+ None,
+ None,
+ True,
+ 5,
+ DiscountValueType.FIXED,
+ Decimal("5.00"),
+ ),
+ ],
+)
+def test_get_discount_for_checkout_value_specific_product_voucher(
+ prices,
+ min_spent_amount,
+ min_checkout_items_quantity,
+ once_per_order,
+ discount_value,
+ discount_value_type,
+ expected_value,
+ monkeypatch,
+ channel_USD,
+ checkout_with_items,
+):
+ # given
+ voucher = Voucher.objects.create(
+ code="unique",
+ type=VoucherType.SPECIFIC_PRODUCT,
+ discount_value_type=discount_value_type,
+ min_checkout_items_quantity=min_checkout_items_quantity,
+ apply_once_per_order=once_per_order,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
+ variants = [line.variant for line in checkout_with_items.lines.all()]
+ voucher.variants.add(*variants)
+
+ checkout = Mock(spec=checkout_with_items, channel=channel_USD)
+ monkeypatch.setattr(
+ "saleor.checkout.utils.get_base_lines_prices",
+ Mock(return_value=prices),
+ )
+ subtotal = sum(prices, start=Money(0, "USD"))
+ monkeypatch.setattr(
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
+ )
+ checkout_info = CheckoutInfo(
+ checkout=checkout,
+ shipping_address=None,
+ billing_address=None,
+ channel=channel_USD,
+ user=None,
+ tax_configuration=channel_USD.tax_configuration,
+ valid_pick_up_points=[],
+ delivery_method_info=get_delivery_method_info(None, None),
+ all_shipping_methods=[],
+ )
+ lines = [
+ CheckoutLineInfo(
+ line=line,
+ channel_listing=line.variant.channel_listings.first(),
+ collections=[],
+ product=line.variant.product,
+ variant=line.variant,
+ product_type=line.variant.product.product_type,
+ )
+ for line in checkout_with_items.lines.all()
+ ]
+ manager = get_plugins_manager()
+
+ # when
+ discount = get_voucher_discount_for_checkout(
+ manager, voucher, checkout_info, lines, None, []
+ )
+
+ # then
assert discount == Money(expected_value, "USD")
@@ -327,13 +488,18 @@ def test_get_discount_for_checkout_value_voucher(
def test_get_voucher_discount_for_checkout_voucher_validation(
mock_validate_voucher, voucher, checkout_with_voucher
):
+ # given
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout_with_voucher)
quantity = calculate_checkout_quantity(lines)
checkout_info = fetch_checkout_info(checkout_with_voucher, lines, [], manager)
manager = get_plugins_manager()
address = checkout_with_voucher.shipping_address
+
+ # when
get_voucher_discount_for_checkout(manager, voucher, checkout_info, lines, address)
+
+ # then
subtotal = base_calculations.base_checkout_subtotal(
lines, checkout_info.channel, checkout_with_voucher.currency, []
)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 27d5e26439..b6c5aa4711 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -9,7 +9,7 @@ from prices import Money
from ..account.models import User
from ..core.exceptions import ProductNotPublished
-from ..core.taxes import zero_money, zero_taxed_money
+from ..core.taxes import zero_taxed_money
from ..core.utils.promo_code import (
InvalidPromoCode,
promo_code_is_gift_card,
@@ -18,7 +18,10 @@ from ..core.utils.promo_code import (
from ..discount import DiscountInfo, VoucherType
from ..discount.interface import VoucherInfo, fetch_voucher_info
from ..discount.models import NotApplicable, Voucher
-from ..discount.utils import validate_voucher_for_checkout
+from ..discount.utils import (
+ get_products_voucher_discount,
+ validate_voucher_for_checkout,
+)
from ..giftcard.utils import (
add_gift_card_code_to_checkout,
remove_gift_card_code_from_checkout,
@@ -442,22 +445,33 @@ def get_prices_of_discounted_specific_product(
Product must be assigned directly to the discounted category, assigning
product to child category won't work.
"""
- line_prices = []
voucher_info = fetch_voucher_info(voucher)
discounted_lines: Iterable["CheckoutLineInfo"] = get_discounted_lines(
lines, voucher_info
)
- discounts = discounts or []
+ line_prices = get_base_lines_prices(checkout_info, discounted_lines, discounts)
+
+ return line_prices
+
- for line_info in discounted_lines:
+def get_base_lines_prices(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Optional[Iterable[DiscountInfo]],
+):
+ """Get base total price of checkout lines without voucher discount applied."""
+ line_prices = []
+ for line_info in lines:
line = line_info.line
- line_unit_price = base_calculations.calculate_base_line_unit_price(
- line_info,
+ line_unit_price = line.variant.get_price(
+ line_info.product,
+ line_info.collections,
checkout_info.channel,
- discounts,
+ line_info.channel_listing,
+ discounts or [],
+ line_info.line.price_override,
)
line_prices.extend([line_unit_price] * line.quantity)
-
return line_prices
@@ -475,6 +489,9 @@ def get_voucher_discount_for_checkout(
"""
validate_voucher_for_checkout(manager, voucher, checkout_info, lines, discounts)
if voucher.type == VoucherType.ENTIRE_ORDER:
+ if voucher.apply_once_per_order:
+ prices = get_base_lines_prices(checkout_info, lines, discounts)
+ return voucher.get_discount_amount_for(min(prices), checkout_info.channel)
subtotal = base_calculations.base_checkout_subtotal(
lines,
checkout_info.channel,
@@ -490,11 +507,31 @@ def get_voucher_discount_for_checkout(
address,
)
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- # The specific product voucher is propagated on specific line's prices
- return zero_money(checkout_info.checkout.currency)
+ return _get_products_voucher_discount(
+ manager, checkout_info, lines, voucher, discounts
+ )
raise NotImplementedError("Unknown discount type")
+def _get_products_voucher_discount(
+ manager: PluginsManager,
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ voucher,
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+):
+ """Calculate products discount value for a voucher, depending on its type."""
+ prices = None
+ if voucher.type == VoucherType.SPECIFIC_PRODUCT:
+ prices = get_prices_of_discounted_specific_product(
+ manager, checkout_info, lines, voucher, discounts
+ )
+ if not prices:
+ msg = "This offer is only valid for selected items."
+ raise NotApplicable(msg)
+ return get_products_voucher_discount(voucher, prices, checkout_info.channel)
+
+
def get_voucher_for_checkout(
checkout: "Checkout",
channel_slug: str,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index ea45f085de..5154b4ff2b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -371,7 +371,7 @@ def test_checkout_add_specific_product_voucher_code_checkout_with_sale(
expected_discount, "USD"
)
assert checkout.voucher_code == voucher.code
- assert checkout.discount_amount == Decimal(0)
+ assert checkout.discount_amount == expected_discount
def test_checkout_add_products_voucher_code_checkout_with_sale(
@@ -428,7 +428,7 @@ def test_checkout_add_products_voucher_code_checkout_with_sale(
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + expected_discount
assert checkout.voucher_code == voucher.code
- assert checkout.discount_amount == Decimal(0)
+ assert checkout.discount_amount == expected_discount.amount
def test_checkout_add_collection_voucher_code_checkout_with_sale(
@@ -485,7 +485,7 @@ def test_checkout_add_collection_voucher_code_checkout_with_sale(
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + expected_voucher_discount
assert checkout.voucher_code == voucher.code
- assert checkout.discount_amount == Decimal(0)
+ assert checkout.discount_amount == expected_voucher_discount.amount
def test_checkout_add_category_code_checkout_with_sale(
@@ -541,7 +541,7 @@ def test_checkout_add_category_code_checkout_with_sale(
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + expected_discount
assert checkout.voucher_code == voucher.code
- assert checkout.discount_amount == Decimal(0)
+ assert checkout.discount_amount == expected_discount.amount
def test_checkout_add_voucher_code_not_applicable_voucher(
@@ -1037,5 +1037,5 @@ def test_checkout_add_voucher_code_invalidates_price(
# then
assert not data["errors"]
assert data["checkout"]["voucherCode"] == voucher.code
- assert data["checkout"]["subtotalPrice"]["gross"]["amount"] == subtotal.amount
+ assert data["checkout"]["subtotalPrice"]["gross"]["amount"] == expected_total
assert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index b6fc34f64c..3e3f1313e5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -845,6 +845,7 @@ def test_checkout_with_voucher_complete(
address,
shipping_method,
):
+ # given
voucher_used_count = voucher_percentage.used
voucher_percentage.usage_limit = voucher_used_count + 1
voucher_percentage.save(update_fields=["usage_limit"])
@@ -887,8 +888,11 @@ def test_checkout_with_voucher_complete(
"id": to_global_id_or_none(checkout),
"redirectUrl": "https://www.example.com",
}
+
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ # then
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
assert not data["errors"]
@@ -949,8 +953,6 @@ def test_checkout_with_voucher_complete_product_on_sale(
checkout.save()
checkout.metadata_storage.save()
- discount_amount = checkout.discount
-
checkout_line = checkout.lines.first()
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
@@ -1003,7 +1005,7 @@ def test_checkout_with_voucher_complete_product_on_sale(
order_line = order.lines.first()
assert order.total == total
- assert order.undiscounted_total == total + discount_amount + (
+ assert order.undiscounted_total == total + (
order_line.undiscounted_total_price - order_line.total_price
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index e68ce424b5..bb440c8e63 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -1539,9 +1539,8 @@ def test_checkout_prices_with_sales(user_api_client, checkout_with_item, discoun
checkout_line_info=line_info,
discounts=[discount_info],
)
- assert (
- data["lines"][0]["unitPrice"]["gross"]["amount"]
- == line_total_price.gross.amount / line_info.line.quantity
+ assert data["lines"][0]["unitPrice"]["gross"]["amount"] == round(
+ line_total_price.gross.amount / line_info.line.quantity, 2
)
assert (
data["lines"][0]["totalPrice"]["gross"]["amount"]
@@ -1644,9 +1643,8 @@ def test_checkout_prices_with_specific_voucher(
lines=lines,
checkout_line_info=line_info,
)
- assert (
- data["lines"][0]["unitPrice"]["gross"]["amount"]
- == line_total_price.gross.amount / line_info.line.quantity
+ assert data["lines"][0]["unitPrice"]["gross"]["amount"] == round(
+ line_total_price.gross.amount / line_info.line.quantity, 2
)
assert (
data["lines"][0]["totalPrice"]["gross"]["amount"]
@@ -1738,6 +1736,72 @@ def test_checkout_prices_with_voucher_once_per_order(
)
+def test_checkout_prices_with_voucher(user_api_client, checkout_with_item_and_voucher):
+ # given
+ checkout = checkout_with_item_and_voucher
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
+ line_info = lines[0]
+ assert line_info.line.quantity > 0
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ assert data["lines"][0]["unitPrice"]["gross"]["amount"] == float(
+ quantize_price(
+ line_total_price.gross.amount / line_info.line.quantity, checkout.currency
+ )
+ )
+ assert (
+ data["lines"][0]["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ undiscounted_unit_price = line_info.variant.get_price(
+ line_info.product,
+ line_info.collections,
+ checkout_info.channel,
+ line_info.channel_listing,
+ [],
+ line_info.line.price_override,
+ )
+ assert (
+ data["lines"][0]["undiscountedUnitPrice"]["amount"]
+ == undiscounted_unit_price.amount
+ )
+ assert (
+ data["lines"][0]["undiscountedTotalPrice"]["amount"]
+ == undiscounted_unit_price.amount * line_info.line.quantity
+ )
+
+
def test_query_checkouts(
checkout_with_item, staff_api_client, permission_manage_checkouts
):
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3493-4297-3.0-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3495-4297-3.0-True].yaml
similarity index 65%
rename from saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3493-4297-3.0-True].yaml
rename to saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3495-4297-3.0-True].yaml
index 3f39955184..970842e052 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3493-4297-3.0-True].yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[False-3495-4297-3.0-True].yaml
@@ -5,7 +5,7 @@ interactions:
true, "itemCode": "123", "discounted": true, "description": "Test product",
"ref1": "123"}, {"quantity": 1, "amount": "700.000", "taxCode": "FR000000",
"taxIncluded": true, "itemCode": "Shipping", "discounted": false, "description":
- null}], "code": "46c5c966-7f2d-46c6-af09-95691a4ab415", "date": "2023-02-28",
+ null}], "code": "8650f1ed-c286-46a5-a509-2e87c72c890d", "date": "2023-03-02",
"customerCode": 0, "discount": "3.0", "addresses": {"shipFrom": {"line1": "Teczowa
7", "line2": "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
"53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
@@ -28,9 +28,9 @@ interactions:
uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
response:
body:
- string: '{"id":0,"code":"46c5c966-7f2d-46c6-af09-95691a4ab415","companyId":7799660,"date":"2023-02-28","paymentDate":"2023-02-28","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"JPY","exchangeRateCurrencyCode":"JPY","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":3495.61,"totalExempt":-0.39,"totalDiscount":3.0,"totalTax":804.0,"totalTaxable":3493.0,"totalTaxCalculated":804.0,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2023-02-28","exchangeRate":1.0,"modifiedDate":"2023-02-28T14:21:36.7475482Z","modifiedUserId":6479978,"taxDate":"2023-02-28","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
- product","discountAmount":3.0,"exemptAmount":-0.39,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":2927.0,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2023-02-28","tax":673.0,"taxableAmount":2924.0,"taxCalculated":673.0,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2023-02-28","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":672.61,"taxableAmount":2924.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
- Rate","taxAuthorityTypeId":45,"taxCalculated":672.61,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":2924.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":672.61,"reportingTaxCalculated":672.61,"avtUserBIN":"","liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":569.0,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2023-02-28","tax":131.0,"taxableAmount":569.0,"taxCalculated":131.0,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2023-02-28","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":130.89,"taxableAmount":569.11,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ string: '{"id":0,"code":"8650f1ed-c286-46a5-a509-2e87c72c890d","companyId":7799660,"date":"2023-03-02","paymentDate":"2023-03-02","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"JPY","exchangeRateCurrencyCode":"JPY","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":3497.11,"totalExempt":0.61,"totalDiscount":3.0,"totalTax":802.0,"totalTaxable":3493.5,"totalTaxCalculated":802.0,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2023-03-02","exchangeRate":1.0,"modifiedDate":"2023-03-02T13:54:43.1768477Z","modifiedUserId":6479978,"taxDate":"2023-03-02","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":3.0,"exemptAmount":0.61,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":2928.0000,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2023-03-02","tax":672.0,"taxableAmount":2924.39,"taxCalculated":672.0,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2023-03-02","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":672.61,"taxableAmount":2924.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":672.61,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":2924.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":672.61,"reportingTaxCalculated":672.61,"avtUserBIN":"","liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":569.1100,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2023-03-02","tax":130.0,"taxableAmount":569.11,"taxCalculated":130.0,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2023-03-02","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":130.89,"taxableAmount":569.11,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
Rate","taxAuthorityTypeId":45,"taxCalculated":130.89,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":569.11,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":130.89,"reportingTaxCalculated":130.89,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska
10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
@@ -41,11 +41,11 @@ interactions:
Content-Type:
- application/json; charset=utf-8
Date:
- - Tue, 28 Feb 2023 14:21:36 GMT
+ - Thu, 02 Mar 2023 13:54:43 GMT
Location:
- /api/v2/companies/7799660/transactions/0
ServerDuration:
- - '00:00:00.0214852'
+ - '00:00:00.0206453'
Transfer-Encoding:
- chunked
X-Content-Type-Options:
@@ -59,9 +59,9 @@ interactions:
strict-transport-security:
- max-age=31536000; includeSubdomains
x-avalara-uid:
- - 3e77ca9d-45d3-462e-b785-92008ccd7be9
+ - f1e83bef-1e4b-465b-a0d1-33bf547ee99d
x-correlation-id:
- - 3e77ca9d-45d3-462e-b785-92008ccd7be9
+ - f1e83bef-1e4b-465b-a0d1-33bf547ee99d
x-frame-options:
- sameorigin
x-permitted-cross-domain-policies:
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3484-4285-0.0-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3485-4285-0.0-True].yaml
similarity index 67%
rename from saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3484-4285-0.0-True].yaml
rename to saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3485-4285-0.0-True].yaml
index 07dadf3a55..4ce67b8c5d 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3484-4285-0.0-True].yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_for_JPY[True-3485-4285-0.0-True].yaml
@@ -5,7 +5,7 @@ interactions:
true, "itemCode": "123", "discounted": true, "description": "Test product",
"ref1": "123"}, {"quantity": 1, "amount": "700.000", "taxCode": "FR000000",
"taxIncluded": true, "itemCode": "Shipping", "discounted": false, "description":
- null}], "code": "fb6e705c-80bc-4e00-83db-1914a7e94933", "date": "2023-02-28",
+ null}], "code": "78f1921e-e305-46e8-8363-8f0103b55b01", "date": "2023-03-02",
"customerCode": 0, "discount": null, "addresses": {"shipFrom": {"line1": "Teczowa
7", "line2": "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
"53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
@@ -28,9 +28,9 @@ interactions:
uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
response:
body:
- string: '{"id":0,"code":"fb6e705c-80bc-4e00-83db-1914a7e94933","companyId":7799660,"date":"2023-02-28","paymentDate":"2023-02-28","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"JPY","exchangeRateCurrencyCode":"JPY","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":3484.37,"totalExempt":0.37,"totalDiscount":0.0,"totalTax":801.0,"totalTaxable":3484.0,"totalTaxCalculated":801.0,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2023-02-28","exchangeRate":1.0,"modifiedDate":"2023-02-28T14:21:32.5552891Z","modifiedUserId":6479978,"taxDate":"2023-02-28","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
- product","discountAmount":0.0,"exemptAmount":0.37,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":2915.0,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2023-02-28","tax":670.0,"taxableAmount":2915.0,"taxCalculated":670.0,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2023-02-28","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":670.37,"taxableAmount":2914.63,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
- Rate","taxAuthorityTypeId":45,"taxCalculated":670.37,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":2914.63,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":670.37,"reportingTaxCalculated":670.37,"avtUserBIN":"","liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":569.0,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2023-02-28","tax":131.0,"taxableAmount":569.0,"taxCalculated":131.0,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2023-02-28","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":130.89,"taxableAmount":569.11,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ string: '{"id":0,"code":"78f1921e-e305-46e8-8363-8f0103b55b01","companyId":7799660,"date":"2023-03-02","paymentDate":"2023-03-02","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"JPY","exchangeRateCurrencyCode":"JPY","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":3484.11,"totalExempt":0.37,"totalDiscount":0.0,"totalTax":800.0,"totalTaxable":3483.74,"totalTaxCalculated":800.0,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2023-03-02","exchangeRate":1.0,"modifiedDate":"2023-03-02T13:54:32.7163085Z","modifiedUserId":6479978,"taxDate":"2023-03-02","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":0.0,"exemptAmount":0.37,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":2915.0000,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2023-03-02","tax":670.0,"taxableAmount":2914.63,"taxCalculated":670.0,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2023-03-02","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":670.37,"taxableAmount":2914.63,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":670.37,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":2914.63,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":670.37,"reportingTaxCalculated":670.37,"avtUserBIN":"","liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":569.1100,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2023-03-02","tax":130.0,"taxableAmount":569.11,"taxCalculated":130.0,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2023-03-02","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":130.89,"taxableAmount":569.11,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
Rate","taxAuthorityTypeId":45,"taxCalculated":130.89,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":569.11,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":130.89,"reportingTaxCalculated":130.89,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska
10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa
7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
@@ -41,11 +41,11 @@ interactions:
Content-Type:
- application/json; charset=utf-8
Date:
- - Tue, 28 Feb 2023 14:21:32 GMT
+ - Thu, 02 Mar 2023 13:54:32 GMT
Location:
- /api/v2/companies/7799660/transactions/0
ServerDuration:
- - '00:00:00.0206591'
+ - '00:00:00.0220406'
Transfer-Encoding:
- chunked
X-Content-Type-Options:
@@ -59,9 +59,9 @@ interactions:
strict-transport-security:
- max-age=31536000; includeSubdomains
x-avalara-uid:
- - 08e3dff6-4465-42ca-95c1-7b0e3ea1e1b8
+ - 7e77a622-661f-44f2-8e36-8535bdf6e5f1
x-correlation-id:
- - 08e3dff6-4465-42ca-95c1-7b0e3ea1e1b8
+ - 7e77a622-661f-44f2-8e36-8535bdf6e5f1
x-frame-options:
- sameorigin
x-permitted-cross-domain-policies:
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 8fdecf7206..78600c1371 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -1150,10 +1150,10 @@ def test_calculate_checkout_total(
"prices_entered_with_tax"
),
[
- (True, "3484", "4285", "0.0", True),
+ (True, "3485", "4285", "0.0", True),
(True, "4280", "5264", "5.0", False),
(False, "4300", "5289", "0.0", False),
- (False, "3493", "4297", "3.0", True),
+ (False, "3495", "4297", "3.0", True),
],
)
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 4115dc76c6..35642c714f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -232,7 +232,7 @@ class PluginsManager(PaymentInterface):
) -> TaxedMoney:
currency = checkout_info.checkout.currency
- default_value = base_calculations.base_checkout_total(
+ default_value = base_calculations.checkout_total(
checkout_info,
discounts,
lines,
@@ -386,6 +386,15 @@ class PluginsManager(PaymentInterface):
checkout_info.channel,
discounts,
)
+ # apply entire order discount
+ default_value = base_calculations.apply_checkout_discount_on_checkout_line(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ discounts,
+ default_value,
+ )
+ default_value = quantize_price(default_value, checkout_info.checkout.currency)
default_taxed_value = TaxedMoney(net=default_value, gross=default_value)
line_total = self.__run_method_on_plugins(
"calculate_checkout_line_total",
@@ -436,10 +445,21 @@ class PluginsManager(PaymentInterface):
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
) -> TaxedMoney:
+ quantity = checkout_line_info.line.quantity
default_value = base_calculations.calculate_base_line_unit_price(
checkout_line_info, checkout_info.channel, discounts
)
- default_taxed_value = TaxedMoney(net=default_value, gross=default_value)
+ # apply entire order discount
+ total_value = base_calculations.apply_checkout_discount_on_checkout_line(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ discounts,
+ default_value * quantity,
+ )
+ default_taxed_value = TaxedMoney(
+ net=total_value / quantity, gross=default_value
+ )
unit_price = self.__run_method_on_plugins(
"calculate_checkout_line_unit_price",
default_taxed_value,
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 5c71f0bc11..9298c9e6b7 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1121,7 +1121,7 @@ def test_manager_delivery_retry(event_delivery):
@mock.patch(
"saleor.plugins.manager.PluginsManager._PluginsManager__run_method_on_single_plugin"
)
[email protected]("saleor.plugins.manager.base_calculations.base_checkout_total")
[email protected]("saleor.plugins.manager.base_calculations.checkout_total")
def test_calculate_checkout_total_zero_default_value(
mocked_base_checkout_total,
mocked_run_method,
diff --git a/saleor/tax/calculations/checkout.py b/saleor/tax/calculations/checkout.py
index cd91f999d6..88b200818e 100644
--- a/saleor/tax/calculations/checkout.py
+++ b/saleor/tax/calculations/checkout.py
@@ -129,16 +129,18 @@ def _calculate_checkout_line_unit_price(
tax_rate: Decimal,
prices_entered_with_tax: bool,
):
+ quantity = checkout_line_info.line.quantity
unit_price = base_calculations.calculate_base_line_unit_price(
checkout_line_info,
channel,
discounts,
)
- unit_price = base_calculations.apply_checkout_discount_on_checkout_line(
+ total_price = base_calculations.apply_checkout_discount_on_checkout_line(
checkout_info,
lines,
checkout_line_info,
discounts,
- unit_price,
+ unit_price * quantity,
)
+ unit_price = total_price / quantity
return calculate_flat_rate_tax(unit_price, tax_rate, prices_entered_with_tax)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 85d2b39f54..1f45c268cd 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -352,6 +352,16 @@ def checkout_with_item_and_voucher_once_per_order(checkout_with_item, voucher):
return checkout_with_item
+def checkout_with_item_and_voucher(checkout_with_item, voucher):
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ add_voucher_to_checkout(manager, checkout_info, lines, voucher)
+ checkout_with_item.refresh_from_db()
+ return checkout_with_item
+
+
@pytest.fixture
def checkout_line(checkout_with_item):
return checkout_with_item.lines.first()
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 245d189877..865b5f09eb 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -1270,8 +1270,12 @@ def generate_checkout_payload_for_tax_calculation(
user_public_metadata = user.metadata
# Prepare discount data
- is_shipping_voucher = (
- checkout_info.voucher.type == VoucherType.SHIPPING
+ # total_amount include the specific product and apply once per order discounts,
+ # so we need to attach only entire order discount here with once per order flag
+ # set to False
+ discount_not_included = (
+ checkout_info.voucher.type == VoucherType.ENTIRE_ORDER
+ and checkout_info.voucher.apply_once_per_order is False
if checkout_info.voucher
else False
)
@@ -1279,7 +1283,7 @@ def generate_checkout_payload_for_tax_calculation(
discount_name = checkout.discount_name
discounts = (
[{"name": discount_name, "amount": discount_amount}]
- if discount_amount and not is_shipping_voucher
+ if discount_amount and discount_not_included
else []
)
@@ -1292,6 +1296,11 @@ def generate_checkout_payload_for_tax_calculation(
base_calculations.base_checkout_delivery_price(checkout_info, lines).amount,
checkout.currency,
)
+ is_shipping_voucher = (
+ checkout_info.voucher.type == VoucherType.SHIPPING
+ if checkout_info.voucher
+ else False
+ )
if is_shipping_voucher:
shipping_method_amount = max(
shipping_method_amount - discount_amount, Decimal("0.0")
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 97244d27d5..53075ab170 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -1628,15 +1628,128 @@ def test_generate_sale_toggle_payload(sale):
@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
@pytest.mark.parametrize("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation(
+def test_generate_checkout_payload_for_tax_calculation_entire_order_voucher(
mocked_serialize_checkout_lines_for_tax_calculation,
mocked_fetch_checkout,
checkout_with_prices,
prices_entered_with_tax,
+ voucher,
+):
+ checkout = checkout_with_prices
+ currency = checkout.currency
+
+ voucher.name = "Voucher 5 USD"
+ voucher.save(update_fields=["name"])
+
+ discount_amount = Decimal("5.00")
+ checkout.voucher_code = voucher.code
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = voucher.name
+ checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
+
+ discounts_info = fetch_active_discounts()
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager()
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, discounts, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ shipping_price = str(
+ quantize_price(
+ checkout.shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price.amount,
+ currency,
+ )
+ )
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [{"amount": str(discount_amount), "name": voucher.name}],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.shipping_method.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(
+ checkout_info, discounts_info, lines
+ ).amount,
+ currency,
+ )
+ ),
+ "shipping_amount": shipping_price,
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ discounts_info,
+ )
+
+
+@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ voucher_specific_product_type,
):
checkout = checkout_with_prices
currency = checkout.currency
+ voucher = voucher_specific_product_type
+ voucher.name = "Voucher 5 USD"
+ voucher.save(update_fields=["name"])
+
+ discount_amount = Decimal("5.00")
+ checkout.voucher_code = voucher.code
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = voucher.name
+ checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
+
discounts_info = fetch_active_discounts()
tax_configuration = checkout.channel.tax_configuration
@@ -1693,7 +1806,7 @@ def test_generate_checkout_payload_for_tax_calculation(
"slug": checkout.channel.slug,
},
"currency": currency,
- "discounts": [{"amount": "5.00", "name": "Voucher 5 USD"}],
+ "discounts": [],
"included_taxes_in_prices": prices_entered_with_tax,
"lines": mocked_serialized_checkout_lines,
"metadata": {"meta_key": "meta_value"},