Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Clean up order discounts (#16116) (#16164)
Iga Karbowiakc12e83aac8f6
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex 6d193dc704..137489cd8a 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -247,6 +247,8 @@ def checkout_total(It should be used as a based value when no flat rate/tax plugin/tax app is active."""+ from ..discount.utils import is_order_level_voucher+currency = checkout_info.checkout.currencysubtotal = base_checkout_subtotal(lines, checkout_info.channel, currency)shipping_price = base_checkout_delivery_price(checkout_info, lines)@@ -255,10 +257,8 @@ def checkout_total(# order promotion discount and entire_order voucher discount with# apply_once_per_order set to False are not included in the total price yetdiscounted_object_promotion = bool(checkout_info.discounts)- discount_not_included = discounted_object_promotion or (+ discount_not_included = discounted_object_promotion or is_order_level_voucher(checkout_info.voucher- and checkout_info.voucher.type == VoucherType.ENTIRE_ORDER- and not checkout_info.voucher.apply_once_per_order)# 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.diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex 9e5707dff9..53906b28ab 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -23,6 +23,7 @@ from ..utils import (get_discount_name,get_discount_translated_name,increase_voucher_code_usage_value,+ is_order_level_voucher,remove_voucher_usage_by_customer,validate_voucher,)@@ -588,3 +589,51 @@ def test_get_discount_translated_name_no_translations(rule_info):# thenassert translated_name is None+++def test_is_order_level_voucher(voucher):+ # given+ voucher.type = VoucherType.ENTIRE_ORDER+ voucher.save(update_fields=["type"])++ # when+ result = is_order_level_voucher(voucher)++ # then+ assert result is True+++def test_is_order_level_voucher_apply_once_per_order(voucher):+ # given+ voucher.type = VoucherType.ENTIRE_ORDER+ voucher.apply_once_per_order = True+ voucher.save(update_fields=["type", "apply_once_per_order"])++ # when+ result = is_order_level_voucher(voucher)++ # then+ assert result is False+++def test_is_order_level_voucher_no_voucher(voucher):+ # when+ result = is_order_level_voucher(None)++ # then+ assert result is False+++ "voucher_type", [VoucherType.SPECIFIC_PRODUCT, VoucherType.SHIPPING]+)+def test_is_order_level_voucher_another_type(voucher_type, voucher):+ # given+ voucher.type = voucher_type+ voucher.save(update_fields=["type"])++ # when+ result = is_order_level_voucher(voucher)++ # then+ assert result is Falsediff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 8b3da4dc0b..b893b1c5bd 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -25,6 +25,7 @@ from ..core.db.connection import allow_writerfrom ..core.exceptions import InsufficientStockfrom ..core.taxes import zero_moneyfrom ..core.utils.promo_code import InvalidPromoCode+from ..discount.models import VoucherTypefrom ..order.fetch import DraftOrderLineInfofrom ..order.models import Order, OrderLinefrom ..product.models import (@@ -57,6 +58,7 @@ from .models import (if TYPE_CHECKING:from ..account.models import User+ from ..discount.models import Voucherfrom ..plugins.manager import PluginsManagerfrom ..product.managers import ProductVariantQuerysetfrom ..product.models import VariantChannelListingPromotionRule@@ -65,6 +67,14 @@ CatalogueInfo = defaultdict[str, set[Union[int, str]]]CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]+def is_order_level_voucher(voucher: Optional[Voucher]):+ return bool(+ voucher+ and voucher.type == VoucherType.ENTIRE_ORDER+ and not voucher.apply_once_per_order+ )++def increase_voucher_usage(voucher: "Voucher",code: "VoucherCode",diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.pyindex 55a0d67693..23084fbc7e 100644--- a/saleor/graphql/core/types/taxes.py+++ b/saleor/graphql/core/types/taxes.py@@ -7,7 +7,8 @@ from promise import Promisefrom ....checkout import base_calculationsfrom ....checkout.models import Checkout, CheckoutLinefrom ....core.prices import quantize_price-from ....discount import VoucherType+from ....discount import DiscountType, VoucherType+from ....discount.utils import is_order_level_voucherfrom ....order.models import Order, OrderLinefrom ....order.utils import get_order_countryfrom ....tax.utils import get_charge_taxes@@ -74,10 +75,24 @@ class TaxableObjectLine(BaseObjectType):product_sku = graphene.String(description="The product sku.")unit_price = graphene.Field(- Money, description="Price of the single item in the order line.", required=True+ Money,+ description=(+ "Price of the single item in the order line. "+ "The price includes catalogue promotions, specific product "+ "and applied once per order voucher discounts. "+ "The price does not include the entire order discount."+ ),+ required=True,)total_price = graphene.Field(- Money, description="Price of the order line.", required=True+ Money,+ description=(+ "Price of the order line. "+ "The price includes catalogue promotions, specific product "+ "and applied once per order voucher discounts. "+ "The price does not include the entire order discount."+ ),+ required=True,)class Meta:@@ -294,7 +309,12 @@ class TaxableObject(BaseObjectType):)currency = graphene.String(required=True, description="The currency of the object.")shipping_price = graphene.Field(- Money, required=True, description="The price of shipping method."+ Money,+ required=True,+ description=(+ "The price of shipping method, includes shipping voucher discount "+ "if applied."+ ),)address = graphene.Field("saleor.graphql.account.types.Address",@@ -368,7 +388,20 @@ class TaxableObject(BaseObjectType):]).then(calculate_shipping_price)- return root.base_shipping_price+ # TODO (SHOPX-875): after adding `undiscounted_base_shipping_price` to+ # Order model, the `root.base_shipping_price` should be used+ def shipping_price_with_discount(tax_config):+ return (+ root.shipping_price_gross+ if tax_config.prices_entered_with_tax+ else root.shipping_price_net+ )++ return (+ TaxConfigurationByChannelId(info.context)+ .load(root.channel_id)+ .then(shipping_price_with_discount)+ )@staticmethoddef resolve_discounts(root: Union[Checkout, Order], info: ResolveInfo):@@ -380,11 +413,7 @@ class TaxableObject(BaseObjectType):return ([{"name": discount_name, "amount": checkout.discount}]if checkout.discount- and (- checkout_info.voucher- and checkout_info.voucher.type == VoucherType.ENTIRE_ORDER- and not checkout_info.voucher.apply_once_per_order- )+ and is_order_level_voucher(checkout_info.voucher)else [])@@ -398,6 +427,16 @@ class TaxableObject(BaseObjectType):return [{"name": discount.name, "amount": discount.amount}for discount in discounts+ if (+ discount.type == DiscountType.MANUAL+ # TODO (SHOPX-873): apply_once_per_order voucher are included+ # for now, as the discount for such vouchers is currently not+ # propagated to the draft order lines+ or (+ discount.voucher+ and discount.voucher.type == VoucherType.ENTIRE_ORDER+ )+ )]return (diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.pyindex e33cdcbca4..4950e1b440 100644--- a/saleor/graphql/order/tests/mutations/test_order_discount.py+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py@@ -986,6 +986,10 @@ def test_update_order_line_discount(order = draft_order_with_fixed_discount_orderorder.status = statusorder.save(update_fields=["status"])++ undiscounted_shipping_price = order.shipping_method.channel_listings.get(+ channel=order.channel+ ).priceline_to_discount = order.lines.first()unit_price = Money(Decimal(7.3), currency="USD")line_to_discount.unit_price = TaxedMoney(unit_price, unit_price)@@ -1030,11 +1034,11 @@ def test_update_order_line_discount(line_to_discount.refresh_from_db()second_line = order.lines.last()order.refresh_from_db()+order_discount = order.discounts.get()order_discount_amount = order_discount.amount- base_shipping = order.base_shipping_pricediscount_applied_to_lines = order_discount_amount - (- base_shipping - order.shipping_price.gross+ undiscounted_shipping_price - order.shipping_price.gross)discount_applied_to_discounted_line = (discount_applied_to_lines@@ -1069,6 +1073,10 @@ def test_update_order_line_discount(lines = parameters.get("lines", {})assert len(lines) == 1+ line_to_discount.refresh_from_db()+ assert line_to_discount.unit_discount_amount == value+ assert line_to_discount.unit_discount_type == DiscountValueType.FIXED+line_data = lines[0]assert line_data.get("line_pk") == str(line_to_discount.pk)discount_data = line_data.get("discount")diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9da51a949a..8a5dc7a02e 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -36163,7 +36163,9 @@ type TaxableObject @doc(category: "Taxes") {"""The currency of the object."""currency: String!- """The price of shipping method."""+ """+ The price of shipping method, includes shipping voucher discount if applied.+ """shippingPrice: Money!"""The address data."""@@ -36205,10 +36207,14 @@ type TaxableObjectLine @doc(category: "Taxes") {"""The product sku."""productSku: String- """Price of the single item in the order line."""+ """+ Price of the single item in the order line. The price includes catalogue promotions, specific product and applied once per order voucher discounts. The price does not include the entire order discount.+ """unitPrice: Money!- """Price of the order line."""+ """+ Price of the order line. The price includes catalogue promotions, specific product and applied once per order voucher discounts. The price does not include the entire order discount.+ """totalPrice: Money!}diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.pyindex 522d240028..91bb48f51d 100644--- a/saleor/order/base_calculations.py+++ b/saleor/order/base_calculations.py@@ -92,12 +92,15 @@ def propagate_order_discount_on_order_prices(discount."""base_subtotal = base_order_subtotal(order, lines)+ # TODO (SHOPX-875): add undiscounted_base_shipping_price field to Order model,+ # and use it herebase_shipping_price = order.base_shipping_pricesubtotal = base_subtotalshipping_price = base_shipping_pricecurrency = order.currencyorder_discounts_to_update = []+ shipping_voucher_discount = Nonefor order_discount in order.discounts.all():subtotal_before_discount = subtotalshipping_price_before_discount = shipping_price@@ -110,6 +113,8 @@ def propagate_order_discount_on_order_prices(currency=currency,price_to_discount=subtotal,)+ elif voucher and voucher.type == VoucherType.SHIPPING:+ shipping_voucher_discount = order_discountelif order_discount.type == DiscountType.ORDER_PROMOTION:subtotal = apply_discount_to_value(value=order_discount.value,@@ -158,6 +163,15 @@ def propagate_order_discount_on_order_prices(if order_discounts_to_update:OrderDiscount.objects.bulk_update(order_discounts_to_update, ["amount_value"])+ # Apply shipping voucher discount+ if shipping_voucher_discount:+ shipping_price = apply_discount_to_value(+ value=shipping_voucher_discount.value,+ value_type=shipping_voucher_discount.value_type,+ currency=currency,+ price_to_discount=shipping_price,+ )+return subtotal, shipping_price@@ -308,6 +322,9 @@ def assign_order_prices(shipping_price: Money,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):+ # TODO (SHOPX-875): set order.base_shipping_price as this price should include+ # the shipping discount - must be done together with adding+ # undiscounted_base_shipping_price to Order modelorder.shipping_price_net_amount = shipping_price.amountorder.shipping_price_gross_amount = shipping_price.amountorder.total_net_amount = subtotal.amount + shipping_price.amountdiff --git a/saleor/order/models.py b/saleor/order/models.pyindex f3ba9addd4..2b8e2a3290 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -214,6 +214,9 @@ class Order(ModelWithMetadata, ModelWithExternalReference):gross_amount_field="shipping_price_gross_amount",currency_field="currency",)+ # Price with applied shipping voucher discount+ # (for draft order - price without discount)+ # FIXME (SHOPX-875)base_shipping_price_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,diff --git a/saleor/order/tests/test_apply_order_discount.py b/saleor/order/tests/test_apply_order_discount.pyindex 0484db7ad6..6c05367456 100644--- a/saleor/order/tests/test_apply_order_discount.py+++ b/saleor/order/tests/test_apply_order_discount.py@@ -179,6 +179,49 @@ def test_apply_order_discounts_manual_discount(order_with_lines):assert order_discount.amount_value == discount_amount+def test_apply_order_discounts_shipping_voucher(+ order_with_lines, voucher_free_shipping+):+ # given+ order = order_with_lines+ lines = order.lines.all()+ shipping_price = order.shipping_price.net+ currency = order.currency+ subtotal = zero_money(currency)+ for line in lines:+ subtotal += line.base_unit_price * line.quantity++ discount_amount = shipping_price.amount+ order_discount = order.discounts.create(+ type=DiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=discount_amount,+ name="Voucher",+ translated_name="VoucherPL",+ currency=currency,+ amount_value=discount_amount,+ voucher=voucher_free_shipping,+ )++ # when+ discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)++ # then+ assert discounted_shipping_price == zero_money(currency)+ assert discounted_subtotal == subtotal+ assert order.subtotal_net_amount == discounted_subtotal.amount+ assert order.subtotal_gross_amount == discounted_subtotal.amount+ assert order.total_net == discounted_subtotal + discounted_shipping_price+ assert order.total_gross == discounted_subtotal + discounted_shipping_price+ assert order.shipping_price_net == discounted_shipping_price+ assert order.shipping_price_gross == discounted_shipping_price+ assert order.undiscounted_total_net == subtotal + shipping_price+ assert order.undiscounted_total_gross == subtotal + shipping_price+ order_discount.refresh_from_db()+ # OrderDiscount has amount value only from not applied discounts+ assert order_discount.amount_value == 0++def test_apply_order_discounts_zero_discount(order_with_lines):# givenorder = order_with_linesdiff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex 2e80477856..27fbc1e30c 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -19,6 +19,7 @@ from ...checkout.utils import get_address_for_checkout_taxes, is_shipping_requirfrom ...core.http_client import HTTPClientfrom ...core.taxes import TaxErrorfrom ...discount import DiscountType, VoucherType+from ...discount.utils import is_order_level_voucherfrom ...order import base_calculations as base_order_calculationsfrom ...order.utils import (get_address_for_order_taxes,@@ -293,11 +294,7 @@ def generate_request_data_from_checkout_lines(prices_entered_with_tax = checkout_info.tax_configuration.prices_entered_with_taxvoucher = checkout_info.voucher- is_entire_order_discount = (- voucher.type == VoucherType.ENTIRE_ORDER- if voucher and not voucher.apply_once_per_order- else False- )+ is_entire_order_discount = is_order_level_voucher(voucher)applicable_checkout_discount = (bool(checkout_info.discounts) or is_entire_order_discount)diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.pyindex 9561fa22c7..adfe3a2a30 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py@@ -5,12 +5,16 @@ from unittest.mock import ANYimport pytestfrom freezegun import freeze_time-from prices import Money, fixed_discount+from prices import Money, TaxedMoney, fixed_discountfrom .....core.prices import quantize_pricefrom .....discount import DiscountValueType, VoucherTypefrom .....graphql.core.utils import to_global_id_or_none+from .....order import OrderStatus+from .....order.calculations import fetch_order_prices_if_expiredfrom .....order.models import Order+from .....order.utils import update_discount_for_order_line+from .....plugins.manager import get_plugins_managerfrom .....tests.fixtures import recalculate_orderfrom .....webhook.event_types import WebhookEventSyncTypefrom .....webhook.models import Webhook@@ -411,7 +415,16 @@ def test_order_calculate_taxes(order = order_line.orderexpected_shipping_price = Money("2.00", order.currency)order.base_shipping_price = expected_shipping_price- order.save()+ order.shipping_price = TaxedMoney(+ net=expected_shipping_price, gross=expected_shipping_price+ )+ order.save(+ update_fields=[+ "base_shipping_price_amount",+ "shipping_price_net_amount",+ "shipping_price_gross_amount",+ ]+ )shipping_method = shipping_zone.shipping_methods.first()order.shipping_method = shipping_methodwebhook_app.permissions.add(permission_handle_taxes)@@ -471,10 +484,298 @@ def test_order_calculate_taxes(@freeze_time("2020-03-18 12:00:00")-def test_order_calculate_taxes_with_discounts(+def test_draft_order_calculate_taxes_line_discount(order_line,webhook_app,permission_handle_taxes,+ shipping_zone,+ voucher_specific_product_type,+):+ # given+ order = order_line.order+ expected_shipping_price = Money("2.00", order.currency)+ order.base_shipping_price = expected_shipping_price+ order.shipping_price = TaxedMoney(+ net=expected_shipping_price, gross=expected_shipping_price+ )+ order.status = OrderStatus.DRAFT+ order.save(+ update_fields=[+ "base_shipping_price_amount",+ "shipping_price_net_amount",+ "shipping_price_gross_amount",+ "status",+ ]+ )++ discount_value = Decimal("5")+ update_discount_for_order_line(+ order_line, order, "test discount", DiscountValueType.FIXED, discount_value+ )+ manager = get_plugins_manager(allow_replica=False)+ fetch_order_prices_if_expired(order, manager, order.lines.all(), True)++ shipping_method = shipping_zone.shipping_methods.first()+ order.shipping_method = shipping_method+ webhook_app.permissions.add(permission_handle_taxes)+ webhook = Webhook.objects.create(+ name="Webhook",+ app=webhook_app,+ target_url="http://www.example.com/any",+ subscription_query=TAXES_SUBSCRIPTION_QUERY,+ )+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES+ webhook.events.create(event_type=event_type)++ # when+ deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)++ # then+ expected_total_price_amount = (+ order_line.undiscounted_base_unit_price_amount - discount_value+ ) * order_line.quantity+ assert json.loads(deliveries.payload.payload) == {+ "__typename": "CalculateTaxes",+ "taxBase": {+ "address": {"id": to_global_id_or_none(order.shipping_address)},+ "currency": "USD",+ "discounts": [],+ "channel": {"id": to_global_id_or_none(order.channel)},+ "lines": [+ {+ "chargeTaxes": True,+ "productName": order_line.product_name,+ "productSku": "SKU_A",+ "quantity": order_line.quantity,+ "sourceLine": {+ "__typename": "OrderLine",+ "id": to_global_id_or_none(order_line),+ },+ "totalPrice": {"amount": float(expected_total_price_amount)},+ "unitPrice": {+ "amount": float(+ expected_total_price_amount / order_line.quantity+ )+ },+ "variantName": order_line.variant_name,+ }+ ],+ "pricesEnteredWithTax": True,+ "shippingPrice": {"amount": float(expected_shipping_price.amount)},+ "sourceObject": {+ "__typename": "Order",+ "id": to_global_id_or_none(order),+ },+ },+ }+++@freeze_time("2020-03-18 12:00:00")+def test_draft_order_calculate_taxes_entire_order_voucher(+ draft_order_with_voucher, subscription_calculate_taxes_for_order, shipping_zone+):+ # given+ order = draft_order_with_voucher+ webhook = subscription_calculate_taxes_for_order+ expected_shipping_price = Money("2.00", order.currency)++ voucher = draft_order_with_voucher.voucher+ voucher.type = VoucherType.ENTIRE_ORDER+ voucher.save(update_fields=["type"])++ discount_amount = Decimal("10")+ order_discount = order.discounts.first()+ order_discount.value = discount_amount+ order_discount.save(update_fields=["value"])++ order.base_shipping_price = expected_shipping_price+ order.shipping_price = TaxedMoney(+ net=expected_shipping_price, gross=expected_shipping_price+ )+ order.save(+ update_fields=[+ "base_shipping_price_amount",+ "shipping_price_net_amount",+ "shipping_price_gross_amount",+ ]+ )++ manager = get_plugins_manager(allow_replica=False)+ fetch_order_prices_if_expired(order, manager, order.lines.all(), True)++ shipping_method = shipping_zone.shipping_methods.first()+ order.shipping_method = shipping_method++ webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY+ webhook.save(update_fields=["subscription_query"])++ # when+ deliveries = create_delivery_for_subscription_sync_event(+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook+ )++ # then+ assert json.loads(deliveries.payload.payload) == {+ "__typename": "CalculateTaxes",+ "taxBase": {+ "address": {"id": to_global_id_or_none(order.shipping_address)},+ "currency": "USD",+ "discounts": [{"amount": {"amount": float(discount_amount)}}],+ "channel": {"id": to_global_id_or_none(order.channel)},+ "lines": [+ {+ "chargeTaxes": True,+ "productName": line.product_name,+ "productSku": line.product_sku,+ "quantity": line.quantity,+ "sourceLine": {+ "__typename": "OrderLine",+ "id": to_global_id_or_none(line),+ },+ "totalPrice": {+ "amount": float(line.base_unit_price_amount * line.quantity)+ },+ "unitPrice": {"amount": float(line.base_unit_price_amount)},+ "variantName": line.variant_name,+ }+ for line in order.lines.all()+ ],+ "pricesEnteredWithTax": True,+ "shippingPrice": {"amount": float(expected_shipping_price.amount)},+ "sourceObject": {+ "__typename": "Order",+ "id": to_global_id_or_none(order),+ },+ },+ }+++@freeze_time("2020-03-18 12:00:00")+def test_draft_order_calculate_taxes_apply_once_per_order_voucher(+ draft_order_with_voucher, subscription_calculate_taxes_for_order, shipping_zone+):+ # given+ order = draft_order_with_voucher+ webhook = subscription_calculate_taxes_for_order+ expected_shipping_price = Money("2.00", order.currency)++ voucher = draft_order_with_voucher.voucher+ voucher.type = VoucherType.ENTIRE_ORDER+ voucher.apply_once_per_order = True+ voucher.save(update_fields=["type", "apply_once_per_order"])++ discount_amount = Decimal("10")+ order_discount = order.discounts.first()+ order_discount.value = discount_amount+ order_discount.save(update_fields=["value"])++ order.base_shipping_price = expected_shipping_price+ order.shipping_price = TaxedMoney(+ net=expected_shipping_price, gross=expected_shipping_price+ )+ order.save(+ update_fields=[+ "base_shipping_price_amount",+ "shipping_price_net_amount",+ "shipping_price_gross_amount",+ ]+ )++ manager = get_plugins_manager(allow_replica=False)+ fetch_order_prices_if_expired(order, manager, order.lines.all(), True)++ shipping_method = shipping_zone.shipping_methods.first()+ order.shipping_method = shipping_method++ webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY+ webhook.save(update_fields=["subscription_query"])++ # when+ deliveries = create_delivery_for_subscription_sync_event(+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook+ )++ # then+ assert json.loads(deliveries.payload.payload) == {+ "__typename": "CalculateTaxes",+ "taxBase": {+ "address": {"id": to_global_id_or_none(order.shipping_address)},+ "currency": "USD",+ "discounts": [{"amount": {"amount": float(discount_amount)}}],+ "channel": {"id": to_global_id_or_none(order.channel)},+ "lines": [+ {+ "chargeTaxes": True,+ "productName": line.product_name,+ "productSku": line.product_sku,+ "quantity": line.quantity,+ "sourceLine": {+ "__typename": "OrderLine",+ "id": to_global_id_or_none(line),+ },+ "totalPrice": {+ "amount": float(line.base_unit_price_amount * line.quantity)+ },+ "unitPrice": {"amount": float(line.base_unit_price_amount)},+ "variantName": line.variant_name,+ }+ for line in order.lines.all()+ ],+ "pricesEnteredWithTax": True,+ "shippingPrice": {"amount": float(expected_shipping_price.amount)},+ "sourceObject": {+ "__typename": "Order",+ "id": to_global_id_or_none(order),+ },+ },+ }+++@freeze_time("2020-03-18 12:00:00")[email protected]("charge_taxes", [True, False])+def test_draft_order_calculate_taxes_free_shipping_voucher(+ draft_order_with_free_shipping_voucher,+ subscription_calculate_taxes_for_order,+ shipping_zone,+ charge_taxes,+):+ # given+ order = draft_order_with_free_shipping_voucher+ webhook = subscription_calculate_taxes_for_order+ shipping_method = shipping_zone.shipping_methods.first()+ order.shipping_method = shipping_method++ webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY+ webhook.save(update_fields=["subscription_query"])++ # when+ deliveries = create_delivery_for_subscription_sync_event(+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook+ )++ # then+ assert json.loads(deliveries.payload.payload) == {+ "__typename": "CalculateTaxes",+ "taxBase": {+ "address": {"id": to_global_id_or_none(order.shipping_address)},+ "currency": "USD",+ "discounts": [],+ "channel": {"id": to_global_id_or_none(order.channel)},+ "lines": ANY,+ "pricesEnteredWithTax": True,+ "shippingPrice": {"amount": 0.0},+ "sourceObject": {+ "__typename": "Order",+ "id": to_global_id_or_none(order),+ },+ },+ }+++@freeze_time("2020-03-18 12:00:00")+def test_order_calculate_taxes_with_manual_discount(+ order_line,+ subscription_calculate_taxes_for_order,):# givenorder = order_line.order@@ -495,18 +796,14 @@ def test_order_calculate_taxes_with_discounts(recalculate_order(order)order.refresh_from_db()- webhook_app.permissions.add(permission_handle_taxes)- webhook = Webhook.objects.create(- name="Webhook",- app=webhook_app,- target_url="http://www.example.com/any",- subscription_query=TAXES_SUBSCRIPTION_QUERY,- )- event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES- webhook.events.create(event_type=event_type)+ webhook = subscription_calculate_taxes_for_order+ webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY+ webhook.save(update_fields=["subscription_query"])# when- deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)+ deliveries = create_delivery_for_subscription_sync_event(+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook+ )# thenassert json.loads(deliveries.payload.payload) == {diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.pyindex 1074037fcd..4c139f2c98 100644--- a/saleor/tax/tests/test_order_calculations.py+++ b/saleor/tax/tests/test_order_calculations.py@@ -371,25 +371,22 @@ def test_calculate_order_shipping_voucher_on_shipping(_enable_flat_rates(order, prices_entered_with_tax)lines = order.lines.all()currency = order.currency- discount_amount = Decimal("5.0")method = shipping_zone.shipping_methods.get()order.shipping_address = order.billing_address.get_copy()order.shipping_method_name = method.nameorder.shipping_method = method- order.base_shipping_price = method.channel_listings.get(- channel=order.channel- ).price - Money(discount_amount, currency)order.voucher = voucher_shipping_typeorder.save()+ voucher_listing = voucher_shipping_type.channel_listings.get(channel=order.channel)+order.discounts.create(type=DiscountType.VOUCHER,value_type=DiscountValueType.FIXED,- value=discount_amount,name=voucher_shipping_type.code,currency=currency,- amount_value=discount_amount,+ value=voucher_listing.discount_value,voucher=voucher_shipping_type,)channel = order.channel@@ -404,7 +401,7 @@ def test_calculate_order_shipping_voucher_on_shipping(# thenprice = order.shipping_priceprice = quantize_price(price, price.currency)- expected_gross_amount = shipping_price.amount - discount_amount+ expected_gross_amount = shipping_price.amount - voucher_listing.discount_valueassert price == TaxedMoney(net=quantize_price(Money(expected_gross_amount / Decimal("1.23"), currency), currencydiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f0cd337b4d..adf6b9238a 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -81,6 +81,7 @@ from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTagfrom ..menu.models import Menu, MenuItem, MenuItemTranslationfrom ..order import OrderOrigin, OrderStatusfrom ..order.actions import cancel_fulfillment, fulfill_order_lines+from ..order.base_calculations import apply_order_discountsfrom ..order.events import (OrderEvents,fulfillment_refunded_event,@@ -5665,6 +5666,7 @@ def draft_order_with_fixed_discount_order(draft_order):draft_order.total = discount(draft_order.total)draft_order.discounts.create(value_type=DiscountValueType.FIXED,+ type=DiscountType.MANUAL,value=value,reason="Discount reason",amount=(draft_order.undiscounted_total - draft_order.total).gross,@@ -5696,6 +5698,34 @@ def draft_order_with_voucher(return order+def draft_order_with_free_shipping_voucher(+ draft_order_with_fixed_discount_order, voucher_free_shipping+):+ order = draft_order_with_fixed_discount_order+ voucher_code = voucher_free_shipping.codes.first()+ discount = order.discounts.first()+ discount.type = DiscountType.VOUCHER+ discount.voucher = voucher_free_shipping+ discount.voucher_code = voucher_code.code+ discount.save(update_fields=["type", "voucher", "voucher_code"])++ channel = order.channel+ channel.include_draft_order_in_voucher_usage = True+ channel.save(update_fields=["include_draft_order_in_voucher_usage"])++ order.voucher = voucher_free_shipping+ order.voucher_code = voucher_code.code+ subtotal, shipping_price = apply_order_discounts(order, order.lines.all())+ order.subtotal = TaxedMoney(gross=subtotal, net=subtotal)+ order.shipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)+ total = subtotal + shipping_price+ order.total = TaxedMoney(net=total, gross=total)+ order.save()++ return order++@pytest.fixturedef draft_order_without_inventory_tracking(order_with_line_without_inventory_tracking):order_with_line_without_inventory_tracking.status = OrderStatus.DRAFTdiff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex abc2fa61a1..fd9ec95f96 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -33,6 +33,7 @@ from ..core.utils.anonymization import ()from ..core.utils.json_serializer import CustomJsonEncoderfrom ..discount import VoucherType+from ..discount.utils import is_order_level_voucherfrom ..order import FulfillmentStatus, OrderStatusfrom ..order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..order.utils import get_order_country@@ -1309,10 +1310,8 @@ def generate_checkout_payload_for_tax_calculation(# order promotion discount and entire_order voucher discount with# apply_once_per_order set to False is not already included in the total pricediscounted_object_promotion = bool(checkout_info.discounts)- discount_not_included = discounted_object_promotion or (+ discount_not_included = discounted_object_promotion or is_order_level_voucher(checkout_info.voucher- and checkout_info.voucher.type == VoucherType.ENTIRE_ORDER- and not checkout_info.voucher.apply_once_per_order)if not checkout.discount_amount:discounts = []@@ -1435,9 +1434,8 @@ def generate_order_payload_for_tax_calculation(order: "Order"):discounts = order.discounts.all()discounts_dict = []for discount in discounts:- if discount.voucher and discount.voucher.type == VoucherType.ENTIRE_ORDER:- if discount.voucher.apply_once_per_order:- continue+ if is_order_level_voucher(discount.voucher):+ continuequantize_price_fields(discount, ("amount_value",), order.currency)discount_amount = quantize_price(discount.amount_value, order.currency)discounts_dict.append({"name": discount.name, "amount": discount_amount})diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex dd73ec2743..1b9664f7b9 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -443,6 +443,10 @@ def test_generate_order_payload_for_tax_calculation_voucher_discounts(),"metadata": order.metadata,"discounts": [+ {+ "name": discount_1.name,+ "amount": str(quantize_price(discount_1.amount_value, currency)),+ },{"name": discount_2.name,"amount": str(quantize_price(discount_2.amount_value, currency)),