Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `TaxableObjectDiscountType` to inform tax apps how to distribute discounts. (#16630)
Piotr Zabieglik19bb9b070965
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5db477ad9a..e7056cf8cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `CheckoutCustomerNoteUpdate` mutation - #16315 by @pitkes22- Add `customerNote` field to `Checkout` type to make it consistent with `Order` model - #16561 by @Air-t+- Add `type` field to `TaxableObjectDiscount` type - #16630 by @zedzior### Webhooksdiff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.pyindex 969196b50c..eb29f12968 100644--- a/saleor/discount/tests/test_discounts.py+++ b/saleor/discount/tests/test_discounts.py@@ -16,6 +16,7 @@ from ..models import (VoucherCode,VoucherCustomer,)+from ..utils.manual_discount import split_manual_discountfrom ..utils.promotion import (get_discount_name,get_discount_translated_name,@@ -672,3 +673,55 @@ def test_get_the_cheapest_line(checkout_with_items, channel_USD):line_info = _get_the_cheapest_line(lines)# thenassert line_info == lines[0]+++ (+ "value",+ "value_type",+ "subtotal",+ "shipping_price",+ "subtotal_portion",+ "shipping_portion",+ ),+ [+ (20, DiscountValueType.FIXED, 30, 10, 15, 5),+ (100, DiscountValueType.FIXED, 30, 10, 30, 10),+ (13.77, DiscountValueType.FIXED, 30, 10, Decimal("10.33"), Decimal("3.44")),+ (0, DiscountValueType.FIXED, 30, 10, 0, 0),+ (20, DiscountValueType.FIXED, 0, 10, 0, 10),+ (50, DiscountValueType.FIXED, 30, 0, 30, 0),+ (50, DiscountValueType.FIXED, 0, 0, 0, 0),+ (0, DiscountValueType.PERCENTAGE, 30, 10, 0, 0),+ (50, DiscountValueType.PERCENTAGE, 30, 10, 15, 5),+ (33.33, DiscountValueType.PERCENTAGE, 30, 10, 10, Decimal("3.33")),+ (100, DiscountValueType.PERCENTAGE, 30, 10, 30, 10),+ (50, DiscountValueType.PERCENTAGE, 0, 10, 0, 5),+ (50, DiscountValueType.PERCENTAGE, 30, 0, 15, 0),+ (50, DiscountValueType.PERCENTAGE, 0, 0, 0, 0),+ ],+)+def test_split_manual_discount(+ value,+ value_type,+ subtotal,+ shipping_price,+ subtotal_portion,+ shipping_portion,+ draft_order_with_fixed_discount_order,+):+ # given+ subtotal = Money(subtotal, currency="USD")+ shipping = Money(shipping_price, currency="USD")+ discount = draft_order_with_fixed_discount_order.discounts.first()+ discount.value = value+ discount.value_type = value_type++ # when+ subtotal_discount, shipping_discount = split_manual_discount(+ discount, subtotal, shipping+ )++ # then+ assert subtotal_discount == Money(subtotal_portion, "USD")+ assert shipping_discount == Money(shipping_portion, "USD")diff --git a/saleor/discount/utils/manual_discount.py b/saleor/discount/utils/manual_discount.pyindex 9c4be560d4..844e42c889 100644--- a/saleor/discount/utils/manual_discount.py+++ b/saleor/discount/utils/manual_discount.py@@ -4,7 +4,10 @@ from typing import Optional, Unionfrom prices import Money, TaxedMoney, fixed_discount, percentage_discount+from ...core.prices import quantize_price+from ...core.taxes import zero_moneyfrom .. import DiscountValueType+from ..models import OrderDiscountdef apply_discount_to_value(@@ -25,3 +28,42 @@ def apply_discount_to_value(**discount_kwargs,)return discount(price_to_discount)+++def split_manual_discount(+ discount: OrderDiscount, subtotal: Money, shipping_price: Money+) -> tuple[Money, Money]:+ """Discounts sent to tax app must be split into subtotal and shipping portion."""+ currency = subtotal.currency+ subtotal_discount, shipping_discount = zero_money(currency), zero_money(currency)+ if discount.value_type == DiscountValueType.PERCENTAGE:+ discounted_subtotal = apply_discount_to_value(+ value=discount.value,+ value_type=discount.value_type,+ currency=currency,+ price_to_discount=subtotal,+ )+ subtotal_discount = subtotal - discounted_subtotal+ discounted_shipping_price = apply_discount_to_value(+ value=discount.value,+ value_type=discount.value_type,+ currency=currency,+ price_to_discount=shipping_price,+ )+ shipping_discount = shipping_price - discounted_shipping_price+ elif discount.value_type == DiscountValueType.FIXED:+ total = subtotal + shipping_price+ if total.amount > 0:+ discounted_total = apply_discount_to_value(+ value=discount.value,+ value_type=discount.value_type,+ currency=currency,+ price_to_discount=total,+ )+ total_discount = total - discounted_total+ subtotal_discount = subtotal / total * total_discount+ shipping_discount = total_discount - subtotal_discount++ return quantize_price(subtotal_discount, currency), quantize_price(+ shipping_discount, currency+ )diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.pyindex 6365f85f12..17831b0bd7 100644--- a/saleor/graphql/core/types/taxes.py+++ b/saleor/graphql/core/types/taxes.py@@ -2,13 +2,15 @@ from functools import partialfrom typing import Unionimport graphene+from prices import Moneyfrom promise import Promisefrom ....checkout import base_calculationsfrom ....checkout.models import Checkout, CheckoutLinefrom ....core.prices import quantize_price+from ....discount import DiscountTypefrom ....discount.utils.checkout import has_checkout_order_promotion-from ....discount.utils.shared import is_order_level_discount+from ....discount.utils.manual_discount import split_manual_discountfrom ....discount.utils.voucher import is_order_level_voucherfrom ....order.models import Order, OrderLinefrom ....order.utils import get_order_country@@ -36,9 +38,10 @@ from ...tax.dataloaders import (TaxConfigurationByChannelId,TaxConfigurationPerCountryByTaxConfigurationIDLoader,)+from ...tax.enums import TaxableObjectDiscountTypeEnumfrom .. import ResolveInfofrom .common import NonNullList-from .money import Money+from .money import Money as MoneyTypefrom .order_or_checkout import OrderOrCheckoutBase@@ -76,7 +79,7 @@ class TaxableObjectLine(BaseObjectType):product_sku = graphene.String(description="The product sku.")unit_price = graphene.Field(- Money,+ MoneyType,description=("Price of the single item in the order line. ""The price includes catalogue promotions, specific product "@@ -86,7 +89,7 @@ class TaxableObjectLine(BaseObjectType):required=True,)total_price = graphene.Field(- Money,+ MoneyType,description=("Price of the order line. ""The price includes catalogue promotions, specific product "@@ -265,7 +268,12 @@ class TaxableObjectLine(BaseObjectType):class TaxableObjectDiscount(BaseObjectType):name = graphene.String(description="The name of the discount.")amount = graphene.Field(- Money, description="The amount of the discount.", required=True+ MoneyType, description="The amount of the discount.", required=True+ )+ type = TaxableObjectDiscountTypeEnum(+ required=True,+ default_value=TaxableObjectDiscountTypeEnum.SUBTOTAL,+ description="Indicates which part of the order the discount should affect: SUBTOTAL or SHIPPING.",)class Meta:@@ -284,7 +292,7 @@ class TaxableObject(BaseObjectType):)currency = graphene.String(required=True, description="The currency of the object.")shipping_price = graphene.Field(- Money,+ MoneyType,required=True,description=("The price of shipping method, includes shipping voucher discount "@@ -372,8 +380,16 @@ class TaxableObject(BaseObjectType):def calculate_checkout_discounts(checkout_info):checkout = checkout_info.checkoutdiscount_name = checkout.discount_name+ # All order level discounts applicable for checkout, like entire order+ # vouchers and order promotions, reduce subtotal valuereturn (- [{"name": discount_name, "amount": checkout.discount}]+ [+ {+ "name": discount_name,+ "amount": checkout.discount,+ "type": TaxableObjectDiscountTypeEnum.SUBTOTAL,+ }+ ]if checkout.discountand (is_order_level_voucher(checkout_info.voucher)@@ -389,13 +405,44 @@ class TaxableObject(BaseObjectType):)def map_discounts(discounts):- return [- {"name": discount.name, "amount": discount.amount}- for discount in discounts- # Only order level discounts, like entire order vouchers,- # order promotions and manual discounts should be taken into account- if is_order_level_discount(discount)- ]+ # Only order level discounts, like entire order vouchers,+ # order promotions and manual discounts should be taken into account.+ # Manual discount needs to be split into subtotal and shipping portions.+ taxable_discounts = []+ currency = root.currency+ for discount in discounts:+ shipping_discount = Money(0, currency)+ subtotal_discount = Money(0, currency)+ if discount.type == DiscountType.MANUAL:+ subtotal = root.subtotal.net+ shipping = root.base_shipping_price+ subtotal_discount, shipping_discount = split_manual_discount(+ discount, subtotal, shipping+ )+ if (+ is_order_level_voucher(discount.voucher)+ or discount.type == DiscountType.ORDER_PROMOTION+ ):+ subtotal_discount = discount.amount++ if subtotal_discount.amount:+ taxable_discounts.append(+ {+ "name": discount.name,+ "amount": subtotal_discount,+ "type": TaxableObjectDiscountTypeEnum.SUBTOTAL,+ }+ )+ if shipping_discount.amount:+ taxable_discounts.append(+ {+ "name": discount.name,+ "amount": shipping_discount,+ "type": TaxableObjectDiscountTypeEnum.SHIPPING,+ }+ )++ return taxable_discountsreturn (OrderDiscountsByOrderIDLoader(info.context)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4743c33c6c..69591d5c69 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -36420,6 +36420,19 @@ type TaxableObjectDiscount @doc(category: "Taxes") {"""The amount of the discount."""amount: Money!++ """+ Indicates which part of the order the discount should affect: SUBTOTAL or SHIPPING.+ """+ type: TaxableObjectDiscountTypeEnum!+}++"""+Indicates which part of the order the discount should affect: SUBTOTAL or SHIPPING.+"""+enum TaxableObjectDiscountTypeEnum @doc(category: "Taxes") {+ SUBTOTAL+ SHIPPING}type TaxableObjectLine @doc(category: "Taxes") {diff --git a/saleor/graphql/tax/enums.py b/saleor/graphql/tax/enums.pyindex 786d6914c5..ed2d181e52 100644--- a/saleor/graphql/tax/enums.py+++ b/saleor/graphql/tax/enums.py@@ -1,4 +1,9 @@-from ...tax import TaxCalculationStrategy as InternalTaxCalculationStrategy+from ...tax import (+ TaxableObjectDiscountType,+)+from ...tax import (+ TaxCalculationStrategy as InternalTaxCalculationStrategy,+)from ..core.doc_category import DOC_CATEGORY_TAXESfrom ..core.enums import to_enum@@ -17,3 +22,10 @@ TaxCalculationStrategy = to_enum(type_name="TaxCalculationStrategy",)TaxCalculationStrategy.doc_category = DOC_CATEGORY_TAXES+++TaxableObjectDiscountTypeEnum = to_enum(+ TaxableObjectDiscountType,+ description="Indicates which part of the order the discount should affect: SUBTOTAL or SHIPPING.",+)+TaxableObjectDiscountTypeEnum.doc_category = DOC_CATEGORY_TAXESdiff --git a/saleor/tax/__init__.py b/saleor/tax/__init__.pyindex 1eb3ead6a2..98d37c13d4 100644--- a/saleor/tax/__init__.py+++ b/saleor/tax/__init__.py@@ -3,3 +3,10 @@ class TaxCalculationStrategy:TAX_APP = "TAX_APP"CHOICES = [(FLAT_RATES, "Flat rates"), (TAX_APP, "Tax app")]+++class TaxableObjectDiscountType:+ SUBTOTAL = "SUBTOTAL"+ SHIPPING = "SHIPPING"++ CHOICES = [(SUBTOTAL, "Subtotal"), (SHIPPING, "Shipping")]diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.pyindex 16766966cd..f0a2e01956 100644--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py@@ -16,6 +16,7 @@ from ....order.calculations import fetch_order_prices_if_expiredfrom ....order.models import Orderfrom ....order.utils import update_discount_for_order_linefrom ....plugins.manager import get_plugins_manager+from ....tax import TaxableObjectDiscountTypefrom ....tests.fixtures import recalculate_orderfrom ...event_types import WebhookEventSyncTypefrom ...models import Webhook@@ -45,6 +46,7 @@ subscription {amount {amount}+ type}lines {@@ -159,6 +161,7 @@ def test_checkout_calculate_taxes_with_free_shipping_voucher(checkout_with_voucher_free_shipping,webhook_app,permission_handle_taxes,+ checkout_with_shipping_address,):# givencheckout = checkout_with_voucher_free_shipping@@ -232,8 +235,16 @@ def test_checkout_calculate_taxes_with_entire_order_voucher(checkout_with_voucher,webhook_app,permission_handle_taxes,+ address,+ shipping_method,):# given+ checkout = checkout_with_voucher+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+webhook_app.permissions.add(permission_handle_taxes)webhook = Webhook.objects.create(name="Webhook",@@ -246,16 +257,18 @@ def test_checkout_calculate_taxes_with_entire_order_voucher(# whendeliveries = create_delivery_for_subscription_sync_event(- event_type, checkout_with_voucher, webhook+ event_type, checkout, webhook)# thenassert json.loads(deliveries.payload.get_payload()) == {"__typename": "CalculateTaxes","taxBase": {- "address": None,+ "address": {"id": to_global_id_or_none(address)},"currency": "USD",- "discounts": [{"amount": {"amount": 20.0}}],+ "discounts": [+ {"amount": {"amount": 20.0}, "type": TaxableObjectDiscountType.SUBTOTAL}+ ],"channel": {"id": to_global_id_or_none(checkout_with_voucher.channel)},"lines": [{@@ -264,7 +277,7 @@ def test_checkout_calculate_taxes_with_entire_order_voucher("productSku": "123","quantity": 3,"sourceLine": {- "id": to_global_id_or_none(checkout_with_voucher.lines.first()),+ "id": to_global_id_or_none(checkout.lines.first()),"__typename": "CheckoutLine",},"totalPrice": {"amount": 30.0},@@ -273,9 +286,9 @@ def test_checkout_calculate_taxes_with_entire_order_voucher(}],"pricesEnteredWithTax": True,- "shippingPrice": {"amount": 0.0},+ "shippingPrice": {"amount": 10.0},"sourceObject": {- "id": to_global_id_or_none(checkout_with_voucher),+ "id": to_global_id_or_none(checkout),"__typename": "Checkout",},},@@ -342,13 +355,20 @@ def test_checkout_calculate_taxes_with_entire_order_voucher_once_per_order(@freeze_time("2020-03-18 12:00:00")def test_checkout_calculate_taxes_with_shipping_voucher(- checkout_with_voucher,- voucher,+ checkout_with_item,+ voucher_free_shipping,webhook_app,permission_handle_taxes,+ address,+ shipping_method,):# given- voucher.type = VoucherType.SHIPPING+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.voucher_code = voucher_free_shipping.codes.first()+webhook_app.permissions.add(permission_handle_taxes)webhook = Webhook.objects.create(name="Webhook",@@ -361,17 +381,17 @@ def test_checkout_calculate_taxes_with_shipping_voucher(# whendeliveries = create_delivery_for_subscription_sync_event(- event_type, checkout_with_voucher, webhook+ event_type, checkout, webhook)# thenassert json.loads(deliveries.payload.get_payload()) == {"__typename": "CalculateTaxes","taxBase": {- "address": None,+ "address": {"id": to_global_id_or_none(address)},"currency": "USD",- "discounts": [{"amount": {"amount": 20.0}}],- "channel": {"id": to_global_id_or_none(checkout_with_voucher.channel)},+ "discounts": [],+ "channel": {"id": to_global_id_or_none(checkout.channel)},"lines": [{"chargeTaxes": True,@@ -379,7 +399,7 @@ def test_checkout_calculate_taxes_with_shipping_voucher("productSku": "123","quantity": 3,"sourceLine": {- "id": to_global_id_or_none(checkout_with_voucher.lines.first()),+ "id": to_global_id_or_none(checkout.lines.first()),"__typename": "CheckoutLine",},"totalPrice": {"amount": 30.0},@@ -390,7 +410,7 @@ def test_checkout_calculate_taxes_with_shipping_voucher("pricesEnteredWithTax": True,"shippingPrice": {"amount": 0.0},"sourceObject": {- "id": to_global_id_or_none(checkout_with_voucher),+ "id": to_global_id_or_none(checkout),"__typename": "Checkout",},},@@ -432,7 +452,12 @@ def test_checkout_calculate_taxes_with_order_promotion("taxBase": {"address": None,"currency": "USD",- "discounts": [{"amount": {"amount": float(discount_amount)}}],+ "discounts": [+ {+ "amount": {"amount": float(discount_amount)},+ "type": TaxableObjectDiscountType.SUBTOTAL,+ }+ ],"channel": {"id": channel_id},"lines": [{@@ -722,7 +747,12 @@ def test_draft_order_calculate_taxes_entire_order_voucher("taxBase": {"address": {"id": to_global_id_or_none(order.shipping_address)},"currency": "USD",- "discounts": [{"amount": {"amount": float(discount_amount)}}],+ "discounts": [+ {+ "amount": {"amount": float(discount_amount)},+ "type": TaxableObjectDiscountType.SUBTOTAL,+ }+ ],"channel": {"id": to_global_id_or_none(order.channel)},"lines": [{@@ -983,6 +1013,8 @@ def test_order_calculate_taxes_with_manual_discount():# givenorder = order_line.order+ currency = order.currency+order.total = order_line.total_price + order.shipping_priceorder.undiscounted_total = order.totalorder.save()@@ -997,6 +1029,10 @@ def test_order_calculate_taxes_with_manual_discount(reason="Discount reason",amount=(order.undiscounted_total - order.total).gross,)++ shipping_price = Money(Decimal("10"), currency)+ order.base_shipping_price = shipping_price+recalculate_order(order)order.refresh_from_db()@@ -1004,6 +1040,13 @@ def test_order_calculate_taxes_with_manual_discount(webhook.subscription_query = TAXES_SUBSCRIPTION_QUERYwebhook.save(update_fields=["subscription_query"])+ # Manual discount applies both to subtotal and shipping. For tax calculation it+ # requires to be split into subtotal and shipping portion.+ subtotal = order.subtotal.net+ total = subtotal + shipping_price+ manual_discount_subtotal_portion = subtotal / total * value+ manual_discount_shipping_portion = value - manual_discount_subtotal_portion+# whendeliveries = create_delivery_for_subscription_sync_event(WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook@@ -1015,7 +1058,16 @@ def test_order_calculate_taxes_with_manual_discount("taxBase": {"address": {"id": to_global_id_or_none(order.shipping_address)},"currency": "USD",- "discounts": [{"amount": {"amount": 20.0}}],+ "discounts": [+ {+ "amount": {"amount": float(manual_discount_subtotal_portion)},+ "type": TaxableObjectDiscountType.SUBTOTAL,+ },+ {+ "amount": {"amount": float(manual_discount_shipping_portion)},+ "type": TaxableObjectDiscountType.SHIPPING,+ },+ ],"channel": {"id": to_global_id_or_none(order.channel)},"lines": [{@@ -1033,7 +1085,7 @@ def test_order_calculate_taxes_with_manual_discount(}],"pricesEnteredWithTax": True,- "shippingPrice": {"amount": 0.0},+ "shippingPrice": {"amount": float(shipping_price.amount)},"sourceObject": {"__typename": "Order", "id": to_global_id_or_none(order)},},}@@ -1110,7 +1162,12 @@ def test_order_calculate_taxes_order_promotion("taxBase": {"address": {"id": to_global_id_or_none(order.shipping_address)},"currency": "USD",- "discounts": [{"amount": {"amount": float(discount_amount)}}],+ "discounts": [+ {+ "amount": {"amount": float(discount_amount)},+ "type": TaxableObjectDiscountType.SUBTOTAL,+ }+ ],"channel": {"id": to_global_id_or_none(order.channel)},"lines": [{