Skip to content

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

Use Promise for handling order calculate-taxes webhook. #18793

Maciej Korycinski0423c2ff3d8e
diff --git a/saleor/app/tests/fixtures/webhooks/tax_app.py b/saleor/app/tests/fixtures/webhooks/tax_app.py
index 74b4b28af5..e644f1568b 100644
--- a/saleor/app/tests/fixtures/webhooks/tax_app.py
+++ b/saleor/app/tests/fixtures/webhooks/tax_app.py
@@ -5,7 +5,125 @@ from .....app.types import AppType
from .....graphql.core.utils import to_global_id_or_none
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook, WebhookEvent
-from .....webhook.tests.subscription_webhooks import subscription_queries
+
+CALCULATE_TAXES_SUBSCRIPTION_QUERY = """
+subscription CalculateTaxes {
+ event {
+ ...CalculateTaxesEvent
+ }
+}
+
+fragment CalculateTaxesEvent on Event {
+ __typename
+ ... on CalculateTaxes {
+ taxBase {
+ ...TaxBase
+ }
+ recipient {
+ privateMetadata {
+ key
+ value
+ }
+ }
+ }
+}
+
+fragment TaxBase on TaxableObject {
+ pricesEnteredWithTax
+ currency
+ channel {
+ slug
+ }
+ discounts {
+ ...TaxDiscount
+ }
+ address {
+ ...Address
+ }
+ shippingPrice {
+ amount
+ }
+ lines {
+ ...TaxBaseLine
+ }
+ sourceObject {
+ __typename
+ ... on Checkout {
+ avataxEntityCode: metafield(key: "avataxEntityCode")
+ user {
+ ...User
+ }
+ }
+ ... on Order {
+ avataxEntityCode: metafield(key: "avataxEntityCode")
+ user {
+ ...User
+ }
+ }
+ }
+}
+
+fragment TaxDiscount on TaxableObjectDiscount {
+ name
+ amount {
+ amount
+ }
+}
+
+fragment Address on Address {
+ streetAddress1
+ streetAddress2
+ city
+ countryArea
+ postalCode
+ country {
+ code
+ }
+}
+
+fragment TaxBaseLine on TaxableObjectLine {
+ sourceLine {
+ __typename
+ ... on CheckoutLine {
+ id
+ checkoutProductVariant: variant {
+ id
+ product {
+ taxClass {
+ id
+ name
+ }
+ }
+ }
+ }
+ ... on OrderLine {
+ id
+ orderProductVariant: variant {
+ id
+ product {
+ taxClass {
+ id
+ name
+ }
+ }
+ }
+ }
+ }
+ quantity
+ unitPrice {
+ amount
+ }
+ totalPrice {
+ amount
+ }
+}
+
+fragment User on User {
+ id
+ email
+ avataxCustomerCode: metafield(key: "avataxCustomerCode")
+}
+"""
@pytest.fixture
@@ -20,7 +138,7 @@ def tax_app(db, permission_handle_taxes, permission_manage_users):
name="tax-webhook-1",
app=app,
target_url="https://tax-app.com/api/",
- subscription_query=subscription_queries.CALCULATE_TAXES_SUBSCRIPTION_QUERY,
+ subscription_query=CALCULATE_TAXES_SUBSCRIPTION_QUERY,
)
webhook.events.bulk_create(
[
@@ -56,7 +174,7 @@ def external_tax_app(db, permission_handle_taxes):
name="external-tax-webhook-1",
app=app,
target_url="https://tax-app.example.com/api/",
- subscription_query=subscription_queries.CALCULATE_TAXES_SUBSCRIPTION_QUERY,
+ subscription_query=CALCULATE_TAXES_SUBSCRIPTION_QUERY,
)
webhook.events.bulk_create(
[
diff --git a/saleor/core/db/connection.py b/saleor/core/db/connection.py
index 2ea1db12fb..17411dbca9 100644
--- a/saleor/core/db/connection.py
+++ b/saleor/core/db/connection.py
@@ -54,6 +54,20 @@ def allow_writer():
setattr(default_connection, "_allow_writer", False)
+@contextmanager
+def allow_writer_for_default_connection(connection_name: str):
+ """Context manager that allows write access when connection points to writer.
+
+ This is a helper context manager that conditionally allows write access based on the
+ given connection name.
+ """
+ if connection_name == settings.DATABASE_CONNECTION_DEFAULT_NAME:
+ with allow_writer():
+ yield
+ else:
+ yield
+
+
@contextmanager
def allow_writer_in_context(context: SaleorContext):
"""Context manager that allows write access to the default database connection in a context (SaleorContext).
@@ -62,10 +76,7 @@ def allow_writer_in_context(context: SaleorContext):
database connection name in the given context.
"""
conn_name = get_database_connection_name(context)
- if conn_name == settings.DATABASE_CONNECTION_DEFAULT_NAME:
- with allow_writer():
- yield
- else:
+ with allow_writer_for_default_connection(conn_name):
yield
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
index 92727f3748..22390b688c 100644
--- a/saleor/core/tests/test_taxes.py
+++ b/saleor/core/tests/test_taxes.py
@@ -1,16 +1,13 @@
import graphene
import pytest
-from django.utils import timezone
from ...app.models import App
from ...permission.enums import (
CheckoutPermissions,
- OrderPermissions,
get_permissions_from_codenames,
)
-from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...webhook.event_types import WebhookEventSyncType
from ...webhook.models import Webhook, WebhookEvent
-from ...webhook.transport.taxes import get_current_tax_app
@pytest.fixture
@@ -63,63 +60,3 @@ def tax_app(tax_app_factory):
name="Tax App",
is_active=True,
)
-
-
-def test_get_current_tax_app(tax_app):
- assert tax_app == get_current_tax_app()
-
-
-def test_get_current_tax_app_removed_app(tax_app):
- tax_app.removed_at = timezone.now()
- tax_app.save(update_fields=["removed_at"])
- assert get_current_tax_app() is None
-
-
-def test_get_current_tax_app_multiple_apps(app_factory, tax_app_factory):
- # given
- tax_app_factory(
- name="A Tax App",
- )
- tax_app_factory(
- name="Z Tax App",
- )
- expected_app = tax_app_factory(
- name="Tax App",
- )
- app_factory(
- name="Non Tax App",
- is_active=True,
- webhook_event_types=[
- WebhookEventAsyncType.ORDER_UPDATED,
- ],
- permissions=[
- OrderPermissions.MANAGE_ORDERS,
- ],
- )
- tax_app_factory(name="Unauthorized Tax App", permissions=[])
- tax_app_factory(
- name="Partial Tax App 2",
- webhook_event_types=[
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- ],
- )
- tax_app_factory(
- name="Partial Tax App 1",
- webhook_event_types=[
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ],
- )
- tax_app_factory(
- name="Inactive Tax App",
- is_active=False,
- )
-
- # when
- app = get_current_tax_app()
-
- # then
- assert expected_app == app
-
-
-def test_get_current_tax_app_no_app():
- assert get_current_tax_app() is None
diff --git a/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
index 17406298f7..8325346439 100644
--- a/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
+++ b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
@@ -44,7 +44,9 @@ def test_create_discount_for_voucher_specific_product_fixed(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -144,7 +146,9 @@ def test_create_discount_for_voucher_specific_product_percentage(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -248,7 +252,9 @@ def test_create_discount_for_voucher_apply_once_per_order_percentage(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -358,7 +364,9 @@ def test_create_discount_for_voucher_apply_once_per_order_fixed(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -465,7 +473,9 @@ def test_create_discount_for_voucher_entire_order_fixed(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -583,7 +593,9 @@ def test_create_discount_for_voucher_entire_order_multiple_lines(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -675,7 +687,9 @@ def test_create_discount_for_voucher_entire_order_percentage(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -785,7 +799,9 @@ def test_create_discount_for_voucher_shipping_fixed(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -861,7 +877,9 @@ def test_create_discount_for_voucher_shipping_percentage(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -933,7 +951,9 @@ def test_create_discount_for_voucher_specific_product_line_with_catalogue_discou
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderLineDiscount.objects.count() == 2
diff --git a/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
index ae4975523c..8719bcdcb4 100644
--- a/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
+++ b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
@@ -46,7 +46,9 @@ def test_update_voucher_discount_specific_product_with_different_variants(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
discount_1 = line_1.discounts.get()
@@ -67,7 +69,9 @@ def test_update_voucher_discount_specific_product_with_different_variants(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -174,7 +178,9 @@ def test_update_voucher_discount_specific_product_with_apply_once_per_order(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
cheapest_line, line_2 = lines
discount_1 = line_2.discounts.get()
@@ -195,7 +201,9 @@ def test_update_voucher_discount_specific_product_with_apply_once_per_order(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
cheapest_line, line_2 = lines
@@ -309,7 +317,9 @@ def test_update_voucher_discount_apply_once_per_order_with_specific_product(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
discount = line_1.discounts.get()
@@ -331,7 +341,9 @@ def test_update_voucher_discount_apply_once_per_order_with_specific_product(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -428,7 +440,9 @@ def test_update_voucher_discount_specific_product_with_entire_order(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
discount_1 = line_2.discounts.get()
@@ -451,7 +465,9 @@ def test_update_voucher_discount_specific_product_with_entire_order(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
with pytest.raises(OrderLineDiscount.DoesNotExist):
@@ -579,7 +595,9 @@ def test_update_voucher_discount_shipping_with_specific_product(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
assert order.base_shipping_price == shipping_price_after_discount
@@ -598,7 +616,9 @@ def test_update_voucher_discount_shipping_with_specific_product(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -706,7 +726,9 @@ def test_update_voucher_discount_specific_product_with_shipping(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
assert (
@@ -725,7 +747,9 @@ def test_update_voucher_discount_specific_product_with_shipping(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -826,7 +850,9 @@ def test_update_voucher_discount_shipping_with_entire_order(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
assert order.base_shipping_price == shipping_price_after_discount
@@ -847,7 +873,9 @@ def test_update_voucher_discount_shipping_with_entire_order(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -973,7 +1001,9 @@ def test_update_voucher_discount_entire_order_with_shipping(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
assert order.subtotal_net_amount == quantize_price(
undiscounted_subtotal.amount - voucher_1_discount.amount, currency
@@ -993,7 +1023,9 @@ def test_update_voucher_discount_entire_order_with_shipping(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -1092,7 +1124,9 @@ def test_update_voucher_discount_entire_order_with_specific_product(
order.voucher = voucher_1
order.voucher_code = voucher_1.codes.first().code
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
assert order.subtotal_net_amount == quantize_price(
undiscounted_subtotal.amount - voucher_1_discount.amount, currency
@@ -1111,7 +1145,9 @@ def test_update_voucher_discount_entire_order_with_specific_product(
# when
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 5a0dd994aa..b03a2391fa 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -4,7 +4,17 @@ from typing import cast
from uuid import UUID
from django.db.models import F
-
+from promise import Promise
+
+from ...core.db.connection import allow_writer_in_context
+from ...order.calculations import (
+ get_expired_line_ids,
+ prepare_order_lines_for_refresh,
+ process_order_prices,
+ process_order_promotion,
+ should_refresh_prices,
+)
+from ...order.delivery_context import get_valid_shipping_methods_for_order
from ...order.models import (
Fulfillment,
FulfillmentLine,
@@ -15,8 +25,18 @@ from ...order.models import (
OrderLine,
)
from ...payment.models import TransactionEvent, TransactionItem
+from ...shipping.interface import ShippingMethodData
from ...warehouse.models import Allocation
+from ..app.dataloaders.utils import get_app_promise
+from ..channel.dataloaders.by_self import ChannelByIdLoader
from ..core.dataloaders import DataLoader
+from ..plugins.dataloaders import (
+ plugin_manager_promise,
+)
+from ..shipping.dataloaders import (
+ ShippingMethodChannelListingByChannelSlugLoader,
+)
+from ..utils import get_user_or_app_from_context
class OrderLinesByVariantIdAndChannelIdLoader(
@@ -254,3 +274,176 @@ class TransactionEventsByOrderGrantedRefundIdLoader(
for event in events:
event_map[event.related_granted_refund_id].append(event)
return [event_map.get(granted_refund_id, []) for granted_refund_id in keys]
+
+
+class OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(
+ DataLoader[tuple[UUID, bool], tuple[Order, Iterable[OrderLine]]]
+):
+ context_key = "order_promotion_calculate_by_order_id_and_webhook_sync"
+
+ def batch_load(self, keys):
+ orders_loader = OrderByIdLoader(self.context).load_many(
+ [order_id for order_id, _ in keys]
+ )
+ lines_loader = OrderLinesByOrderIdLoader(self.context).load_many(
+ [order_id for order_id, _ in keys]
+ )
+
+ current_lines_ids_per_order: dict[UUID, set[UUID]] = {}
+
+ def refresh_lines(data: list[tuple[Order, list[OrderLine]]]):
+ for order, _order_lines in data:
+ if order is None:
+ continue
+
+ if order.id not in current_lines_ids_per_order:
+ continue
+ if current_lines_ids_per_order[order.id] != {
+ line.id for line in _order_lines
+ }:
+ # While re-calculating the prices, the order lines might have been
+ # changed (gift promotions). In that case, we need to refresh
+ # the order lines in dataloader cache to make sure that the
+ # rest of the code works with up-to-date data.
+ OrderLinesByOrderIdLoader(self.context).clear(order.id)
+ OrderLinesByOrderIdLoader(self.context).prime(
+ order.id, _order_lines
+ )
+ return data
+
+ def calculate_prices(data):
+ orders, lines = data
+ results: list[Promise[tuple[Order | None, Iterable[OrderLine]]]] = []
+ for order, order_lines, (_, allow_sync_webhooks) in zip(
+ orders, lines, keys, strict=True
+ ):
+ if order is None:
+ results.append(Promise.resolve((None, [])))
+ continue
+ order = cast(Order, order)
+
+ expired_line_ids = get_expired_line_ids(order, order_lines)
+ if not should_refresh_prices(
+ order=order,
+ force_update=False,
+ expired_line_ids=expired_line_ids,
+ database_connection_name=self.database_connection_name,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ):
+ results.append(Promise.resolve((order, order_lines)))
+ continue
+
+ lines_info = prepare_order_lines_for_refresh(
+ order=order,
+ lines=order_lines,
+ expired_line_ids=expired_line_ids,
+ database_connection_name=self.database_connection_name,
+ )
+ if lines_info is None:
+ results.append(Promise.resolve((order, order_lines)))
+ continue
+
+ process_order_promotion(
+ order,
+ lines_info,
+ database_connection_name=self.database_connection_name,
+ )
+ refreshed_lines = [line_info.line for line_info in lines_info]
+ current_lines_ids_per_order[order.id] = {
+ line.id for line in refreshed_lines
+ }
+
+ results.append(Promise.resolve((order, refreshed_lines)))
+ return Promise.all(results).then(refresh_lines)
+
+ return Promise.all([orders_loader, lines_loader]).then(calculate_prices)
+
+
+class OrderPriceCalculationByOrderIdAndWebhookSyncLoader(
+ DataLoader[tuple[UUID, bool], tuple[Order, Iterable[OrderLine]]]
+):
+ context_key = "order_price_calculation_by_order_id_and_webhook_sync"
+
+ def batch_load(self, keys):
+ def with_updated_promotions(
+ data,
+ ):
+ app, orders_and_lines = data
+
+ def calculate_prices(manager):
+ results: list[Promise[tuple[Order, Iterable[OrderLine]]]] = []
+ for (order, lines), (_, allow_sync_webhooks) in zip(
+ orders_and_lines, keys, strict=True
+ ):
+ expired_line_ids = get_expired_line_ids(order, lines)
+ if not should_refresh_prices(
+ order=order,
+ force_update=False,
+ expired_line_ids=expired_line_ids,
+ database_connection_name=self.database_connection_name,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ):
+ results.append(Promise.resolve((order, lines)))
+ continue
+ result = process_order_prices(
+ order=order,
+ manager=manager,
+ requestor=app or self.context.user,
+ lines=lines,
+ database_connection_name=self.database_connection_name,
+ )
+ results.append(result)
+ return Promise.all(results)
+
+ return plugin_manager_promise(self.context, app).then(calculate_prices)
+
+ return Promise.all(
+ [
+ get_app_promise(self.context),
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(
+ self.context
+ ).load_many(keys),
+ ]
+ ).then(with_updated_promotions)
+
+
+class OrderShippingMethodsByOrderIdAndWebhookSyncLoader(
+ DataLoader[tuple[UUID, bool], list[ShippingMethodData]]
+):
+ context_key = "order_shipping_methods_by_order"
+
+ def batch_load(self, keys):
+ requestor = get_user_or_app_from_context(self.context)
+ orders = OrderByIdLoader(self.context).load_many([order for (order, _) in keys])
+
+ def with_orders(orders: list[Order]):
+ def with_listings(channel_listings):
+ results: list[Promise[list[ShippingMethodData]]] = []
+ with allow_writer_in_context(self.context):
+ for order, listings, (_, allow_sync_webhooks) in zip(
+ orders, channel_listings, keys, strict=True
+ ):
+ result = get_valid_shipping_methods_for_order(
+ order,
+ listings,
+ requestor=requestor,
+ database_connection_name=self.database_connection_name,
+ allow_sync_webhooks=allow_sync_webhooks,
+ )
+ results.append(result)
+ return Promise.all(results)
+
+ def with_channels(channels):
+ return (
+ ShippingMethodChannelListingByChannelSlugLoader(self.context)
+ .load_many([c.slug for c in channels])
+ .then(with_listings)
+ )
+
+ return (
+ ChannelByIdLoader(self.context)
+ .load_many([order.channel_id for order in orders if order is not None])
+ .then(with_channels)
+ )
+
+ return orders.then(with_orders)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 0a5c27ec45..ce70f4bd2b 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -120,6 +120,7 @@ class DraftOrderComplete(BaseMutation):
):
user = info.context.user
app = get_app_promise(info.context).get()
+ requestor = app or user
manager = get_plugin_manager_promise(info.context).get()
order = cls.get_node_or_error(
@@ -131,8 +132,8 @@ class DraftOrderComplete(BaseMutation):
cls.check_channel_permissions(info, [order.channel_id])
force_update = order.tax_error is not None
order, _ = fetch_order_prices_if_expired(
- order, manager, force_update=force_update
- )
+ order, manager, requestor=requestor, force_update=force_update
+ ).get()
if order.tax_error is not None:
raise ValidationError(
"Configured Tax App returned invalid response.",
@@ -142,7 +143,7 @@ class DraftOrderComplete(BaseMutation):
country = get_order_country(order)
validate_draft_order(
- order, order.lines.all(), country, requestor=app or user
+ order, order.lines.all(), country, requestor=requestor
).get()
with traced_atomic_transaction():
update_fields = [
diff --git a/saleor/graphql/order/mutations/order_discount_update.py b/saleor/graphql/order/mutations/order_discount_update.py
index 8625b5bcab..f0e852213d 100644
--- a/saleor/graphql/order/mutations/order_discount_update.py
+++ b/saleor/graphql/order/mutations/order_discount_update.py
@@ -15,6 +15,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.types import OrderError
from ...discount.types import OrderDiscount
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...utils import get_user_or_app_from_context
from ..types import Order
from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
@@ -51,6 +52,7 @@ class OrderDiscountUpdate(OrderDiscountCommon):
cls, _root, info: ResolveInfo, /, *, discount_id: str, input
):
manager = get_plugin_manager_promise(info.context).get()
+ requestor = get_user_or_app_from_context(info.context)
order_discount = cls.get_node_or_error(
info, discount_id, only_type=OrderDiscount
)
@@ -86,7 +88,9 @@ class OrderDiscountUpdate(OrderDiscountCommon):
# discount.
# Calling refreshing prices because it's set proper discount amount
# on OrderDiscount.
- fetch_order_prices_if_expired(order, manager, force_update=True)
+ fetch_order_prices_if_expired(
+ order, manager, requestor=requestor, force_update=True
+ ).get()
order_discount.refresh_from_db()
app = get_app_promise(info.context).get()
events.order_discount_updated_event(
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
index 9f1f373c22..9ca59cd643 100644
--- a/saleor/graphql/order/mutations/order_mark_as_paid.py
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -24,6 +24,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.types import OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...utils import get_user_or_app_from_context
from ..types import Order
from .utils import try_payment_action
@@ -113,8 +114,14 @@ class OrderMarkAsPaid(BaseMutation):
):
order = cls.get_node_or_error(info, id, only_type=Order)
cls.check_channel_permissions(info, [order.channel_id])
+
+ requestor = get_user_or_app_from_context(info.context)
manager = get_plugin_manager_promise(info.context).get()
- order, _ = fetch_order_prices_if_expired(order, manager)
+
+ order, _ = fetch_order_prices_if_expired(
+ order, manager, requestor=requestor
+ ).get()
+
cls.clean_billing_address(order)
user = info.context.user
user = cast(User, user)
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 9c94862752..c4637cc83c 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -35,6 +35,7 @@ from ..utils import get_user_or_app_from_context
from .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBulkDelete
from .bulk_mutations.order_bulk_cancel import OrderBulkCancel
from .bulk_mutations.order_bulk_create import OrderBulkCreate
+from .dataloaders import OrderByIdLoader
from .filters import (
DraftOrderFilter,
DraftOrderWhereInput,
@@ -227,7 +228,10 @@ class OrderQueries(graphene.ObjectType):
except ValidationError:
return None
_, id = from_global_id_or_error(id, Order)
- return resolve_order(info, id)
+ wrapped_order = resolve_order(info, id)
+ if wrapped_order:
+ OrderByIdLoader(info.context).prime(id, wrapped_order.node)
+ return wrapped_order
@staticmethod
def resolve_orders(_root, info: ResolveInfo, *, channel=None, **kwargs):
@@ -287,7 +291,12 @@ class OrderQueries(graphene.ObjectType):
@staticmethod
def resolve_order_by_token(_root, info: ResolveInfo, *, token):
- return resolve_order_by_token(info, token)
+ wrapped_order = resolve_order_by_token(info, token)
+ if wrapped_order:
+ OrderByIdLoader(info.context).prime(
+ wrapped_order.node.id, wrapped_order.node
+ )
+ return wrapped_order
class OrderMutations(graphene.ObjectType):
diff --git a/saleor/graphql/order/tests/integration/test_bulk_order.py b/saleor/graphql/order/tests/integration/test_bulk_order.py
index 2cb1938e8c..8435a9e67d 100644
--- a/saleor/graphql/order/tests/integration/test_bulk_order.py
+++ b/saleor/graphql/order/tests/integration/test_bulk_order.py
@@ -392,8 +392,11 @@ def test_refresh_order_prices_from_imported_draft_order_with_unit_discount(
# refetch order prices
order = Order.objects.get()
order, lines = fetch_order_prices_if_expired(
- order, get_plugins_manager(allow_replica=True), force_update=True
- )
+ order,
+ get_plugins_manager(allow_replica=True),
+ requestor=None,
+ force_update=True,
+ ).get()
# then - ensure the order prices are updated, the discount is applied
line = lines[0]
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index a13091d4e1..ee17d8e340 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1445,7 +1445,9 @@ def test_draft_order_complete_with_catalogue_and_order_discount(
currency = order.currency
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- fetch_order_prices_if_expired(order, plugins_manager, force_update=True)
+ fetch_order_prices_if_expired(
+ order, plugins_manager, requestor=None, force_update=True
+ ).get()
# when
response = staff_api_client.post_graphql(
@@ -1542,7 +1544,9 @@ def test_draft_order_complete_with_catalogue_and_gift_discount(
currency = order.currency
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- fetch_order_prices_if_expired(order, plugins_manager, force_update=True)
+ fetch_order_prices_if_expired(
+ order, plugins_manager, requestor=None, force_update=True
+ ).get()
# when
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 7dd8e2ba40..1bc1e6c2c8 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -1,7 +1,7 @@
import datetime
from datetime import timedelta
from decimal import Decimal
-from unittest.mock import ANY, Mock, patch
+from unittest.mock import ANY, patch
import graphene
import pytest
@@ -14,12 +14,13 @@ from .....account.models import Address
from .....checkout import AddressType
from .....core.models import EventDelivery
from .....core.prices import quantize_price
-from .....core.taxes import TaxError, zero_taxed_money
+from .....core.taxes import TaxError
from .....discount import DiscountType, DiscountValueType, RewardType, RewardValueType
from .....discount.models import VoucherChannelListing, VoucherCode, VoucherCustomer
from .....order import OrderStatus
from .....order import events as order_events
from .....order.actions import call_order_event
+from .....order.calculations import process_order_prices
from .....order.error_codes import OrderErrorCode
from .....order.models import Order, OrderEvent, OrderLine
from .....payment.model_helpers import get_subtotal
@@ -2535,9 +2536,12 @@ def test_draft_order_create_invalid_address_skip_validation(
assert order.billing_address.validation_skipped is True
-@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+@patch(
+ "saleor.graphql.order.dataloaders.process_order_prices",
+ wraps=process_order_prices,
+)
def test_draft_order_create_price_recalculation(
- mock_fetch_order_prices_if_expired,
+ mock_process_order_prices,
staff_api_client,
permission_group_manage_orders,
customer_user,
@@ -2549,13 +2553,7 @@ def test_draft_order_create_price_recalculation(
):
# given
permission_group_manage_orders.user_set.add(staff_api_client.user)
- fake_order = Mock()
- fake_order.total = zero_taxed_money(channel_PLN.currency_code)
- fake_order.subtotal = zero_taxed_money(channel_PLN.currency_code)
- fake_order.undiscounted_total = zero_taxed_money(channel_PLN.currency_code)
- fake_order.shipping_price = zero_taxed_money(channel_PLN.currency_code)
- fetch_prices_response = Mock(return_value=(fake_order, None))
- mock_fetch_order_prices_if_expired.side_effect = fetch_prices_response
+
query = DRAFT_ORDER_CREATE_MUTATION
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_1 = product_available_in_many_channels.variants.first()
@@ -2597,7 +2595,7 @@ def test_draft_order_create_price_recalculation(
assert Order.objects.count() == 1
order = Order.objects.first()
lines = list(order.lines.all())
- mock_fetch_order_prices_if_expired.assert_called()
+ mock_process_order_prices.assert_called()
def test_draft_order_create_update_display_gross_prices(
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index f1cf0daf23..a9962aab9b 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -3007,7 +3007,7 @@ def test_draft_order_update_with_voucher_specific_product_and_manual_line_discou
value_type=DiscountValueType.FIXED,
value=manual_line_discount_value,
)
- fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
shipping_price = order.shipping_price.net
currency = order.currency
@@ -3155,7 +3155,7 @@ def test_draft_order_update_with_voucher_apply_once_per_order_and_manual_line_di
value_type=DiscountValueType.FIXED,
value=manual_line_discount_value,
)
- fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
shipping_price = order.shipping_price.net
currency = order.currency
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 9cb17fb62b..3fcc142af9 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -126,7 +126,7 @@ def test_add_fixed_order_discount_to_order(
assert len(errors) == 0
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
# Use `net` values in comparison due to that fixture have taxes incluted in
# prices but after recalculation taxes are removed because in tests we
@@ -189,7 +189,7 @@ def test_add_percentage_order_discount_to_order(
assert len(errors) == 0
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
# Use `net` values in comparison due to that fixture have taxes included in
# prices but after recalculation taxes are removed because in tests we
@@ -286,7 +286,7 @@ def test_add_fixed_order_discount_to_order_by_app(
assert Decimal(discount_data["amount_value"]) == order_discount.amount.amount
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
# Use `net` values in comparison due to that fixture have taxes incluted in
# prices but after recalculation taxes are removed because in tests we
@@ -353,7 +353,7 @@ def test_add_manual_discount_replaces_entire_voucher(
assert manual_discount.amount.amount == expected_discount_amount.amount
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
assert (
order.total_net_amount
@@ -410,7 +410,7 @@ def test_add_manual_discount_keeps_shipping_voucher(
applied_discount_amount = manual_discount_value + shipping_discount.amount_value
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
assert (
order.total_net_amount
== order.undiscounted_total_net_amount - applied_discount_amount
@@ -461,7 +461,7 @@ def test_add_manual_discount_replaces_order_promotion(
assert manual_discount.amount.amount == discount_value
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
assert (
order.total_net_amount == order.undiscounted_total_net_amount - discount_value
@@ -520,7 +520,7 @@ def test_add_manual_discount_replaces_gift_discount(
assert manual_discount.amount.amount == discount_value
assert order.should_refresh_prices
- fetch_order_prices_if_expired(order, plugins_manager)
+ fetch_order_prices_if_expired(order, plugins_manager, None).get()
assert (
order.total_net_amount == order.undiscounted_total_net_amount - discount_value
)
@@ -1118,7 +1118,7 @@ def test_delete_manual_discount_from_order_with_entire_order_voucher(
order.voucher_code = code
order.voucher = voucher
order.save(update_fields=["voucher_code", "voucher"])
- fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
assert order.discounts.get() == manual_discount
voucher_discount_amount = voucher.channel_listings.get().discount
undiscounted_total_net_amount = order.undiscounted_total_net_amount
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.py
index 1514896eb3..d02ce13d02 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -834,7 +834,9 @@ def test_order_line_update_apply_once_per_order_voucher_discount(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, staff_api_client.user, None, True
+ ).get()
line_1, line_2 = lines
assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
@@ -993,8 +995,10 @@ def test_order_line_update_specific_product_voucher_discount_percentage(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, staff_api_client.user, None, True
+ ).get()
line_1, line_2 = lines
initial_unit_discount = (
line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
@@ -1149,7 +1153,9 @@ def test_order_line_update_specific_product_voucher_discount_fixed(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, staff_api_client.user, None, True
+ ).get()
line_1, line_2 = lines
assert (
@@ -1302,7 +1308,9 @@ def test_order_line_update_specific_product_voucher_discount_multiple_lines(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, staff_api_client.user, None, True
+ ).get()
line_1, line_2 = lines
assert (
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index fe8f8446f6..fedc11bf1b 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -1505,7 +1505,9 @@ def test_order_lines_create_apply_once_per_order_voucher_new_cheapest_line(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
@@ -1704,7 +1706,9 @@ def test_order_lines_create_apply_once_per_order_voucher_existing_variant(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
@@ -1869,7 +1873,9 @@ def test_order_lines_create_specific_product_voucher_existing_variant(
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher_code", "voucher_id", "status"])
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
line_1, line_2 = lines
initial_unit_discount = (
diff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
index 78f9bb1e26..80e6ed6dbd 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
@@ -559,7 +559,9 @@ def test_order_update_shipping_with_voucher_discount(
order.voucher = voucher
order.save()
create_or_update_voucher_discount_objects_for_order(order)
- order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
discount = order.discounts.get()
initial_discount_amount = (
diff --git a/saleor/graphql/order/tests/queries/test_order_tax.py b/saleor/graphql/order/tests/queries/test_order_tax.py
index 3e2ae9cea7..32964059d1 100644
--- a/saleor/graphql/order/tests/queries/test_order_tax.py
+++ b/saleor/graphql/order/tests/queries/test_order_tax.py
@@ -1,40 +1,42 @@
from decimal import Decimal
from functools import reduce
from operator import getitem
-from unittest.mock import Mock, patch
+from unittest.mock import patch
import graphene
import pytest
-from prices import Money, TaxedMoney
+from prices import TaxedMoney
+from .....core.prices import quantize_price
+from .....core.taxes import zero_taxed_money
from .....order import OrderStatus
-from .....order.interface import OrderTaxedPricesData
+from .....order.calculations import process_order_prices
from ....tests.utils import get_graphql_content
@pytest.mark.parametrize(
- ("fun_to_patch", "price_name"),
+ ("field_on_order", "price_name"),
[
- ("order_total", "total"),
- ("order_undiscounted_total", "undiscountedTotal"),
- ("order_shipping", "shippingPrice"),
+ ("total", "total"),
+ ("undiscounted_total", "undiscountedTotal"),
+ ("shipping_price", "shippingPrice"),
],
)
def test_order_resolver_tax_recalculation(
staff_api_client,
permission_manage_orders,
order_with_lines,
- fun_to_patch,
+ field_on_order,
price_name,
+ tax_configuration_flat_rates,
):
# given
- price = TaxedMoney(
- net=Money(amount="1234.56", currency="USD"),
- gross=Money(amount="1267.89", currency="USD"),
- )
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.should_refresh_prices = True
+ order.total = zero_taxed_money(currency=order.currency)
+ order.undiscounted_total = zero_taxed_money(currency=order.currency)
+ order.shipping_price = zero_taxed_money(currency=order.currency)
order.save()
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -48,10 +50,14 @@ def test_order_resolver_tax_recalculation(
"""
variables = {"id": order_id}
+ current_tax_price = getattr(order, field_on_order)
+ assert current_tax_price.net == current_tax_price.gross
+
# when
with patch(
- f"saleor.order.calculations.{fun_to_patch}", new=Mock(return_value=price)
- ):
+ "saleor.graphql.order.dataloaders.process_order_prices",
+ wraps=process_order_prices,
+ ) as mocked_process_order_prices:
response = staff_api_client.post_graphql(
query,
variables,
@@ -60,43 +66,47 @@ def test_order_resolver_tax_recalculation(
)
content = get_graphql_content(response)
data = content["data"]["order"]
+ assert mocked_process_order_prices.called
# then
- assert str(data[price_name]["net"]["amount"]) == str(price.net.amount)
- assert str(data[price_name]["gross"]["amount"]) == str(price.gross.amount)
-
-
-ORDER_LINE_PRICE_DATA = OrderTaxedPricesData(
- price_with_discounts=TaxedMoney(
- net=Money(amount="1234.56", currency="USD"),
- gross=Money(amount="1267.89", currency="USD"),
- ),
- undiscounted_price=TaxedMoney(
- net=Money(amount="7234.56", currency="USD"),
- gross=Money(amount="7267.89", currency="USD"),
- ),
-)
+ order.refresh_from_db()
+ assert order.should_refresh_prices is False
+ assert quantize_price(
+ Decimal(data[price_name]["gross"]["amount"]), order.currency
+ ) == quantize_price(getattr(order, field_on_order).gross.amount, order.currency)
+
+ assert Decimal(data[price_name]["net"]["amount"]) == quantize_price(
+ getattr(order, field_on_order).net.amount, order.currency
+ )
@pytest.mark.parametrize(
- ("fun_to_patch", "price_name", "expected_price"),
+ (
+ "field_on_order_line",
+ "price_name",
+ ),
[
- ("order_line_unit", "unitPrice", ORDER_LINE_PRICE_DATA.price_with_discounts),
(
- "order_line_unit",
+ "unit_price",
+ "unitPrice",
+ ),
+ (
+ "undiscounted_unit_price",
"undiscountedUnitPrice",
- ORDER_LINE_PRICE_DATA.undiscounted_price,
),
- ("order_line_total", "totalPrice", ORDER_LINE_PRICE_DATA.price_with_discounts),
+ (
+ "total_price",
+ "totalPrice",
+ ),
],
)
def test_order_line_resolver_tax_recalculation(
staff_api_client,
permission_manage_orders,
order_with_lines,
- fun_to_patch,
+ field_on_order_line,
price_name,
- expected_price,
+ tax_configuration_flat_rates,
):
# given
order = order_with_lines
@@ -105,6 +115,16 @@ def test_order_line_resolver_tax_recalculation(
order.save()
order.lines.last().delete()
+ assert order.lines.count() == 1
+
+ order_line = order.lines.first()
+ order_line.unit_price = zero_taxed_money(currency=order.currency)
+ order_line.undiscounted_unit_price = zero_taxed_money(currency=order.currency)
+ order_line.total_price = zero_taxed_money(currency=order.currency)
+ order_line.save()
+
+ taxed_price: TaxedMoney = getattr(order_line, field_on_order_line)
+ assert taxed_price.net == taxed_price.gross
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -121,9 +141,9 @@ def test_order_line_resolver_tax_recalculation(
# when
with patch(
- f"saleor.order.calculations.{fun_to_patch}",
- new=Mock(return_value=ORDER_LINE_PRICE_DATA),
- ):
+ "saleor.graphql.order.dataloaders.process_order_prices",
+ wraps=process_order_prices,
+ ) as mocked_process_order_prices:
response = staff_api_client.post_graphql(
query,
variables,
@@ -132,10 +152,22 @@ def test_order_line_resolver_tax_recalculation(
)
content = get_graphql_content(response)
data = content["data"]["order"]["lines"][0]
-
+ assert mocked_process_order_prices.called
# then
- assert str(data[price_name]["net"]["amount"]) == str(expected_price.net.amount)
- assert str(data[price_name]["gross"]["amount"]) == str(expected_price.gross.amount)
+ order.refresh_from_db()
+ assert order.should_refresh_prices is False
+ order_line.refresh_from_db()
+
+ assert quantize_price(
+ Decimal(data[price_name]["net"]["amount"]), order.currency
+ ) == quantize_price(
+ getattr(order_line, field_on_order_line).net.amount, order.currency
+ )
+ assert quantize_price(
+ Decimal(data[price_name]["gross"]["amount"]), order.currency
+ ) == quantize_price(
+ getattr(order_line, field_on_order_line).gross.amount, order.currency
+ )
ORDER_SHIPPING_TAX_RATE_QUERY = """
@@ -158,10 +190,10 @@ query OrderLineTaxRate($id: ID!) {
@pytest.mark.parametrize(
- ("query", "fun_to_patch", "path"),
+ ("query", "path"),
[
- (ORDER_SHIPPING_TAX_RATE_QUERY, "order_shipping_tax_rate", ["shippingTaxRate"]),
- (ORDER_LINE_TAX_RATE_QUERY, "order_line_tax_rate", ["lines", 0, "taxRate"]),
+ (ORDER_SHIPPING_TAX_RATE_QUERY, ["shippingTaxRate"]),
+ (ORDER_LINE_TAX_RATE_QUERY, ["lines", 0, "taxRate"]),
],
)
def test_order_tax_rate_resolver_tax_recalculation(
@@ -169,17 +201,23 @@ def test_order_tax_rate_resolver_tax_recalculation(
permission_manage_orders,
order_with_lines,
query,
- fun_to_patch,
path,
+ tax_configuration_flat_rates,
):
# given
- tax_rate = Decimal("0.01")
+ expected_tax_rate = Decimal("0.23")
+
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
order.should_refresh_prices = True
+ order.shipping_tax_rate = Decimal("0.0")
order.save()
order.lines.last().delete()
+ assert order.lines.count() == 1
+ order_line = order.lines.first()
+ order_line.tax_rate = Decimal("0.0")
+ order_line.save()
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -187,8 +225,9 @@ def test_order_tax_rate_resolver_tax_recalculation(
# when
with patch(
- f"saleor.order.calculations.{fun_to_patch}", new=Mock(return_value=tax_rate)
- ):
+ "saleor.graphql.order.dataloaders.process_order_prices",
+ wraps=process_order_prices,
+ ) as mocked_process_order_prices:
response = staff_api_client.post_graphql(
query,
variables,
@@ -197,6 +236,6 @@ def test_order_tax_rate_resolver_tax_recalculation(
)
content = get_graphql_content(response)
data = content["data"]["order"]
-
+ assert mocked_process_order_prices.called
# then
- assert str(reduce(getitem, path, data)) == str(tax_rate)
+ assert str(reduce(getitem, path, data)) == str(expected_tax_rate)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 69fbb6a697..68ff789849 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -29,12 +29,10 @@ from ...graphql.core.federation.resolvers import (
from ...graphql.order.resolvers import resolve_orders
from ...graphql.utils import get_user_or_app_from_context
from ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoader
-from ...order import OrderOrigin, OrderStatus, calculations, models
-from ...order.calculations import fetch_order_prices_if_expired
+from ...order import OrderOrigin, OrderStatus, models
from ...order.delivery_context import (
get_external_shipping_id,
get_valid_collection_points_for_order,
- get_valid_shipping_methods_for_order,
)
from ...order.models import FulfillmentStatus
from ...order.utils import (
@@ -131,10 +129,6 @@ from ..payment.types import (
TransactionEvent,
TransactionItem,
)
-from ..plugins.dataloaders import (
- get_plugin_manager_promise,
- plugin_manager_promise_callback,
-)
from ..product.dataloaders import (
ImagesByProductIdLoader,
MediaByProductVariantIdLoader,
@@ -146,7 +140,6 @@ from ..product.dataloaders import (
from ..product.types import DigitalContentUrl, ProductVariant
from ..shipping.dataloaders import (
ShippingMethodByIdLoader,
- ShippingMethodChannelListingByChannelSlugLoader,
ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
)
from ..shipping.types import ShippingMethod
@@ -170,6 +163,9 @@ from .dataloaders import (
OrderGrantedRefundsByOrderIdLoader,
OrderLineByIdLoader,
OrderLinesByOrderIdLoader,
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader,
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader,
+ OrderShippingMethodsByOrderIdAndWebhookSyncLoader,
TransactionEventsByOrderGrantedRefundIdLoader,
TransactionItemsByOrderIDLoader,
)
@@ -1210,23 +1206,18 @@ class OrderLine(
def resolve_unit_price(root: SyncWebhookControlContext[models.OrderLine], info):
order_line = root.node
- @allow_writer_in_context(info.context)
- def _resolve_unit_price(data):
- order, lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_line_unit(
- order,
- order_line,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ).price_with_discounts
+ def _get_unit_price(data):
+ order, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
+ )
+ return quantize_price(line.unit_price, order.currency)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_unit_price)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_unit_price)
+ )
@staticmethod
def resolve_quantity_to_fulfill(
@@ -1242,24 +1233,17 @@ class OrderLine(
):
order_line = root.node
- @allow_writer_in_context(info.context)
- def _resolve_undiscounted_unit_price(data):
- order, lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_line_unit(
- order,
- order_line,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ).undiscounted_price
+ def _get_undiscounted_unit_price(data):
+ order, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
+ )
+ return quantize_price(line.undiscounted_unit_price, order.currency)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(
- _resolve_undiscounted_unit_price
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_undiscounted_unit_price)
)
@staticmethod
@@ -1268,20 +1252,18 @@ class OrderLine(
):
order_line = root.node
- def _resolve_unit_discount_type(data):
- order, lines, manager = data
- return calculations.order_line_unit_discount_type(
- order,
- order_line,
- manager,
- lines,
- allow_sync_webhooks=root.allow_sync_webhooks,
+ def _get_unit_discount_type(data):
+ _, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
)
+ return line.unit_discount_type
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_unit_discount_type)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_unit_discount_type)
+ )
@staticmethod
def resolve_unit_discount_value(
@@ -1289,62 +1271,53 @@ class OrderLine(
):
order_line = root.node
- def _resolve_unit_discount_value(data):
- order, lines, manager = data
- return calculations.order_line_unit_discount_value(
- order,
- order_line,
- manager,
- lines,
- allow_sync_webhooks=root.allow_sync_webhooks,
+ def _get_unit_discount_value(data):
+ _, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
)
+ return line.unit_discount_value
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_unit_discount_value)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_unit_discount_value)
+ )
@staticmethod
def resolve_unit_discount(root: SyncWebhookControlContext[models.OrderLine], info):
order_line = root.node
- def _resolve_unit_discount(data):
- order, lines, manager = data
- return calculations.order_line_unit_discount(
- order,
- order_line,
- manager,
- lines,
- allow_sync_webhooks=root.allow_sync_webhooks,
+ def _get_unit_discount(data):
+ order, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
)
+ return quantize_price(line.unit_discount, order.currency)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_unit_discount)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_unit_discount)
+ )
@staticmethod
@traced_resolver
def resolve_tax_rate(root: SyncWebhookControlContext[models.OrderLine], info):
order_line = root.node
- @allow_writer_in_context(info.context)
- def _resolve_tax_rate(data):
- order, lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_line_tax_rate(
- order,
- order_line,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ) or Decimal(0)
+ def _get_tax_rate(data):
+ _, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
+ )
+ return line.tax_rate or Decimal(0)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_tax_rate)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_tax_rate)
+ )
@staticmethod
@traced_resolver
@@ -1352,23 +1325,18 @@ class OrderLine(
def resolve_total_price(root: SyncWebhookControlContext[models.OrderLine], info):
order_line = root.node
- @allow_writer_in_context(info.context)
- def _resolve_total_price(data):
- order, lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_line_total(
- order,
- order_line,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ).price_with_discounts
+ def _get_total_price(data):
+ order, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
+ )
+ return quantize_price(line.total_price, order.currency)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(_resolve_total_price)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_total_price)
+ )
@staticmethod
@traced_resolver
@@ -1378,24 +1346,17 @@ class OrderLine(
):
order_line = root.node
- @allow_writer_in_context(info.context)
- def _resolve_undiscounted_total_price(data):
- order, lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_line_total(
- order,
- order_line,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ).undiscounted_price
+ def _get_undiscounted_total_price(data):
+ order, lines = data
+ line = next(
+ (line for line in lines if line.pk == order_line.pk), order_line
+ )
+ return quantize_price(line.undiscounted_total_price, order.currency)
- order = OrderByIdLoader(info.context).load(order_line.order_id)
- lines = OrderLinesByOrderIdLoader(info.context).load(order_line.order_id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([order, lines, manager]).then(
- _resolve_undiscounted_total_price
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order_line.order_id, root.allow_sync_webhooks))
+ .then(_get_undiscounted_total_price)
)
@staticmethod
@@ -1473,12 +1434,11 @@ class OrderLine(
def resolve_discounts(root: SyncWebhookControlContext[models.OrderLine], info):
line = root.node
- def with_manager_and_order(data):
- manager, order = data
-
- def handle_line_discount_from_checkout(data):
- channel, line_discounts = data
+ def handle_discounts(data):
+ price_data, line_discounts = data
+ order, _ = price_data
+ def with_channel(channel):
# For legacy propagation, voucher discount was returned as OrderDiscount
# when legacy is disabled, return the voucher discount as
# OrderLineDiscount. It is a temporary solution to provide a grace
@@ -1497,21 +1457,21 @@ class OrderLine(
return discounts_to_return
- with allow_writer_in_context(info.context):
- fetch_order_prices_if_expired(
- order, manager, allow_sync_webhooks=root.allow_sync_webhooks
- )
- channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)
- order_line_discounts = OrderLineDiscountsByOrderLineIDLoader(
- info.context
- ).load(line.id)
- return Promise.all([channel_loader, order_line_discounts]).then(
- handle_line_discount_from_checkout
+ return (
+ ChannelByIdLoader(info.context)
+ .load(order.channel_id)
+ .then(with_channel)
)
- manager = get_plugin_manager_promise(info.context)
- order = OrderByIdLoader(info.context).load(line.order_id)
- return Promise.all([manager, order]).then(with_manager_and_order)
+ price_calculation = OrderPriceCalculationByOrderIdAndWebhookSyncLoader(
+ info.context
+ ).load((line.order_id, root.allow_sync_webhooks))
+ order_line_discounts = OrderLineDiscountsByOrderLineIDLoader(info.context).load(
+ line.id
+ )
+ return Promise.all([price_calculation, order_line_discounts]).then(
+ handle_discounts
+ )
@federated_entity("id")
@@ -1904,22 +1864,24 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
def resolve_discounts(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- # Line-lvl voucher discounts are represented as OrderDiscount objects for order
- # created from checkout.
- def wrap_line_discounts_from_checkout(data):
- channel, order_discounts = data
+ def with_recalculated_prices(price_data):
+ order, order_lines = price_data
- if order.origin != OrderOrigin.CHECKOUT:
- return order_discounts
+ def handle_discounts(data):
+ channel, order_discounts = data
- # voucher discount is stored as OrderLineDiscount object in DB.
- # for backward compatibility, when legacy propagation is enabled
- # we convert the order-line-discounts into single OrderDiscount
- # It is a temporary solution to provide a grace period for migration
- if not channel.use_legacy_line_discount_propagation_for_order:
- return order_discounts
+ # Line-lvl voucher discounts are represented as OrderDiscount objects
+ # for order created from checkout.
+ if order.origin != OrderOrigin.CHECKOUT:
+ return order_discounts
+
+ # voucher discount is stored as OrderLineDiscount object in DB.
+ # for backward compatibility, when legacy propagation is enabled
+ # we convert the order-line-discounts into single OrderDiscount
+ # It is a temporary solution to provide a grace period for migration
+ if not channel.use_legacy_line_discount_propagation_for_order:
+ return order_discounts
- def wrap_order_line(order_lines):
def wrap_order_line_discount(
order_line_discounts: list[list[discount_models.OrderLineDiscount]],
):
@@ -1965,78 +1927,69 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
.then(wrap_order_line_discount)
)
- return (
- OrderLinesByOrderIdLoader(info.context)
- .load(order.id)
- .then(wrap_order_line)
- )
-
- def with_manager(manager):
- with allow_writer_in_context(info.context):
- fetch_order_prices_if_expired(
- order, manager, allow_sync_webhooks=root.allow_sync_webhooks
- )
channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)
order_discounts = OrderDiscountsByOrderIDLoader(info.context).load(order.id)
- return Promise.all([channel_loader, order_discounts]).then(
- wrap_line_discounts_from_checkout
- )
+ return Promise.all([channel_loader, order_discounts]).then(handle_discounts)
- return get_plugin_manager_promise(info.context).then(with_manager)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(with_recalculated_prices)
+ )
@staticmethod
@traced_resolver
def resolve_discount(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- def return_voucher_discount(discounts) -> Money | None:
- if not discounts:
+ def with_recalculated_promotion(_data):
+ def return_voucher_discount(discounts) -> Money | None:
+ if not discounts:
+ return None
+ for discount in discounts:
+ if discount.type == DiscountType.VOUCHER:
+ return Money(
+ amount=discount.amount_value, currency=discount.currency
+ )
return None
- for discount in discounts:
- if discount.type == DiscountType.VOUCHER:
- return Money(
- amount=discount.amount_value, currency=discount.currency
- )
- return None
- def with_manager(manager):
- with allow_writer_in_context(info.context):
- fetch_order_prices_if_expired(
- order, manager, allow_sync_webhooks=root.allow_sync_webhooks
- )
return (
OrderDiscountsByOrderIDLoader(info.context)
.load(order.id)
.then(return_voucher_discount)
)
- return get_plugin_manager_promise(info.context).then(with_manager)
+ return (
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(info.context)
+ .load((root.node.id, root.allow_sync_webhooks))
+ .then(with_recalculated_promotion)
+ )
@staticmethod
@traced_resolver
def resolve_discount_name(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- def return_voucher_name(discounts) -> Money | None:
- if not discounts:
+ def with_recalculated_promotion(_data):
+ def return_voucher_name(discounts) -> Money | None:
+ if not discounts:
+ return None
+ for discount in discounts:
+ if discount.type == DiscountType.VOUCHER:
+ return discount.name
return None
- for discount in discounts:
- if discount.type == DiscountType.VOUCHER:
- return discount.name
- return None
- def with_manager(manager):
- with allow_writer_in_context(info.context):
- fetch_order_prices_if_expired(
- order, manager, allow_sync_webhooks=root.allow_sync_webhooks
- )
return (
OrderDiscountsByOrderIDLoader(info.context)
.load(order.id)
.then(return_voucher_name)
)
- return get_plugin_manager_promise(info.context).then(with_manager)
+ return (
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(info.context)
+ .load((root.node.id, root.allow_sync_webhooks))
+ .then(with_recalculated_promotion)
+ )
@staticmethod
@traced_resolver
@@ -2045,26 +1998,26 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
):
order = root.node
- def return_voucher_translated_name(discounts) -> Money | None:
- if not discounts:
+ def with_recalculated_promotion(_data):
+ def return_voucher_translated_name(discounts) -> Money | None:
+ if not discounts:
+ return None
+ for discount in discounts:
+ if discount.type == DiscountType.VOUCHER:
+ return discount.translated_name
return None
- for discount in discounts:
- if discount.type == DiscountType.VOUCHER:
- return discount.translated_name
- return None
- def with_manager(manager):
- with allow_writer_in_context(info.context):
- fetch_order_prices_if_expired(
- order, manager, allow_sync_webhooks=root.allow_sync_webhooks
- )
return (
OrderDiscountsByOrderIDLoader(info.context)
.load(order.id)
.then(return_voucher_translated_name)
)
- return get_plugin_manager_promise(info.context).then(with_manager)
+ return (
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(info.context)
+ .load((root.node.id, root.allow_sync_webhooks))
+ .then(with_recalculated_promotion)
+ )
@staticmethod
@traced_resolver
@@ -2143,21 +2096,17 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
):
order = root.node
- def _resolve_undiscounted_shipping_price(data):
- lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
-
- return calculations.order_undiscounted_shipping(
- order,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
+ def _get_undiscounted_shipping_price(data):
+ order, _ = data
+ return quantize_price(
+ order.undiscounted_base_shipping_price, order.currency
)
- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([lines, manager]).then(_resolve_undiscounted_shipping_price)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(_get_undiscounted_shipping_price)
+ )
@staticmethod
@traced_resolver
@@ -2165,21 +2114,15 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
def resolve_shipping_price(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- @allow_writer_in_context(info.context)
- def _resolve_shipping_price(data):
- lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_shipping(
- order,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def get_shipping_price(data):
+ order, _ = data
+ return quantize_price(order.shipping_price, order.currency)
- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([lines, manager]).then(_resolve_shipping_price)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(get_shipping_price)
+ )
@staticmethod
@traced_resolver
@@ -2187,21 +2130,15 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
def resolve_shipping_tax_rate(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- @allow_writer_in_context(info.context)
- def _resolve_shipping_tax_rate(data):
- lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_shipping_tax_rate(
- order,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- ) or Decimal(0)
+ def _get_shipping_tax_rate(data):
+ order, _ = data
+ return order.shipping_tax_rate or Decimal(0)
- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([lines, manager]).then(_resolve_shipping_tax_rate)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(_get_shipping_tax_rate)
+ )
@staticmethod
def resolve_actions(root: SyncWebhookControlContext[models.Order], info):
@@ -2229,43 +2166,30 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
def resolve_subtotal(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- @allow_writer_in_context(info.context)
- def _resolve_subtotal(data):
- order_lines, manager = data
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_subtotal(
- order,
- manager,
- order_lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
-
- order_lines = OrderLinesByOrderIdLoader(info.context).load(order.id)
- manager = get_plugin_manager_promise(info.context)
+ def _get_subtotal(data):
+ order, _ = data
+ return quantize_price(order.subtotal, order.currency)
- return Promise.all([order_lines, manager]).then(_resolve_subtotal)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(_get_subtotal)
+ )
@staticmethod
@traced_resolver
@prevent_sync_event_circular_query
- @plugin_manager_promise_callback
- def resolve_total(root: SyncWebhookControlContext[models.Order], info, manager):
+ def resolve_total(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- @allow_writer_in_context(info.context)
- def _resolve_total(lines):
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_total(
- order,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def _get_total(data):
+ order, _ = data
+ return quantize_price(order.total, order.currency)
return (
- OrderLinesByOrderIdLoader(info.context).load(order.id).then(_resolve_total)
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(_get_total)
)
@staticmethod
@@ -2274,21 +2198,15 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
def resolve_undiscounted_total(root: SyncWebhookControlContext[models.Order], info):
order = root.node
- @allow_writer_in_context(info.context)
- def _resolve_undiscounted_total(lines_and_manager):
- lines, manager = lines_and_manager
- database_connection_name = get_database_connection_name(info.context)
- return calculations.order_undiscounted_total(
- order,
- manager,
- lines,
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def _get_undiscounted_total(data):
+ order, _ = data
+ return quantize_price(order.undiscounted_total, order.currency)
- lines = OrderLinesByOrderIdLoader(info.context).load(order.id)
- manager = get_plugin_manager_promise(info.context)
- return Promise.all([lines, manager]).then(_resolve_undiscounted_total)
+ return (
+ OrderPriceCalculationByOrderIdAndWebhookSyncLoader(info.context)
+ .load((order.id, root.allow_sync_webhooks))
+ .then(_get_undiscounted_total)
+ )
@staticmethod
def resolve_total_authorized(root: SyncWebhookControlContext[models.Order], info):
@@ -2394,7 +2312,8 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
@staticmethod
def resolve_lines(root: SyncWebhookControlContext[models.Order], info):
- def _wrap_with_sync_webhook_control_context(lines):
+ def _wrap_with_sync_webhook_control_context(data):
+ _order, lines = data
return [
SyncWebhookControlContext(
node=line, allow_sync_webhooks=root.allow_sync_webhooks
@@ -2403,8 +2322,8 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
]
return (
- OrderLinesByOrderIdLoader(info.context)
- .load(root.node.id)
+ OrderPromotionCalculateByOrderIdLoaderAndWebhookSyncLoader(info.context)
+ .load((root.node.id, root.allow_sync_webhooks))
.then(_wrap_with_sync_webhook_control_context)
)
@@ -2708,38 +2627,16 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
@classmethod
@traced_resolver
@prevent_sync_event_circular_query
- # TODO: We should optimize it in/after PR#5819
def resolve_shipping_methods(
cls, root: SyncWebhookControlContext[models.Order], info
):
- order = root.node
-
- def with_channel(channel):
- database_connection_name = get_database_connection_name(info.context)
-
- @allow_writer_in_context(info.context)
- def with_listings(channel_listings):
- return get_valid_shipping_methods_for_order(
- order,
- channel_listings,
- requestor=get_user_or_app_from_context(info.context),
- database_connection_name=database_connection_name,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
-
- return (
- ShippingMethodChannelListingByChannelSlugLoader(info.context)
- .load(channel.slug)
- .then(with_listings)
- )
-
- channel_loader = ChannelByIdLoader(info.context).load(order.channel_id)
- return channel_loader.then(with_channel)
+ return OrderShippingMethodsByOrderIdAndWebhookSyncLoader(info.context).load(
+ (root.node.id, root.allow_sync_webhooks)
+ )
@classmethod
@traced_resolver
@prevent_sync_event_circular_query
- # TODO: We should optimize it in/after PR#5819
def resolve_available_shipping_methods(
cls, root: SyncWebhookControlContext[models.Order], info
):
diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.py
index ceb8e305ef..62ab2362bd 100644
--- a/saleor/graphql/webhook/subscription_payload.py
+++ b/saleor/graphql/webhook/subscription_payload.py
@@ -216,11 +216,13 @@ def generate_payload_from_subscription(
ast,
)
app_id = request.app.pk if request.app else None
+
results = document.execute(
allow_subscriptions=True,
root=(event_type, subscribable_object),
context=get_context_value(request),
)
+
if hasattr(results, "errors"):
logger.warning(
"Unable to build a payload for subscription. Error: %s",
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 1cddbf9b65..5e7146bcfd 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -165,6 +165,8 @@ def _trigger_order_sync_webhooks(
webhook_event_map: dict[str, set["Webhook"]],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
+ # FIXME: We can drop this after migrating the ASYNC webhooks to promise
+ # approach
if (
webhook_event_map.get(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
and order.should_refresh_prices
@@ -172,15 +174,15 @@ def _trigger_order_sync_webhooks(
fetch_order_prices_if_expired(
order,
manager,
+ # This is temporary, as the whole handler will be dropped when moving
+ # ASYNC webhooks to Promises.
+ requestor=None,
database_connection_name=database_connection_name,
- )
+ ).get()
if webhook_event_map.get(WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS):
shipping_listings = ShippingMethodChannelListing.objects.filter(
channel_id=order.channel_id
)
- # FIXME: Calling .get() as we need to have all webhooks on Promise
- # to be able to use them here. We can drop this after migrating
- # fetch_order_prices_if_expired to use Promise as well.
get_valid_shipping_methods_for_order(
order,
shipping_listings,
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index ade164f89e..795a18b68e 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -1,17 +1,15 @@
from collections.abc import Iterable
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from django.conf import settings
from prices import Money, TaxedMoney
-from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.taxes import zero_money
from ..discount import DiscountType, DiscountValueType
from ..discount.models import OrderDiscount
from ..discount.utils.manual_discount import apply_discount_to_value
from ..discount.utils.voucher import is_order_level_voucher, is_shipping_voucher
-from ..shipping.models import ShippingMethodChannelListing
from .interface import OrderTaxedPricesData
if TYPE_CHECKING:
@@ -338,22 +336,9 @@ def undiscounted_order_shipping(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> Money:
"""Return shipping price without any discounts."""
- # TODO: add undiscounted_shipping_price field to order model.
- # https://github.com/saleor/saleor/issues/14915
-
- with allow_writer():
- # TODO: load shipping_method with dataloader and pass as an argument
- shipping_method = order.shipping_method
-
- if shipping_method:
- if (
- listing := ShippingMethodChannelListing.objects.using(
- database_connection_name
- )
- .filter(channel=order.channel, shipping_method=shipping_method)
- .first()
- ):
- return Money(listing.price_amount, order.currency)
+ if order.undiscounted_base_shipping_price is not None:
+ undiscounted = cast(Money, order.undiscounted_base_shipping_price)
+ return undiscounted
return zero_money(order.currency)
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 6bf1d62b60..6be59fdd05 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -1,14 +1,19 @@
import logging
from collections.abc import Iterable
from decimal import Decimal
+from typing import TYPE_CHECKING, Union
from uuid import UUID
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from prices import Money, TaxedMoney
+from promise import Promise
-from ..core.db.connection import allow_writer
+from ..core.db.connection import (
+ allow_writer,
+ allow_writer_for_default_connection,
+)
from ..core.prices import quantize_price
from ..core.taxes import (
TaxData,
@@ -55,17 +60,144 @@ from .utils import (
order_info_for_logs,
)
+if TYPE_CHECKING:
+ from ..account.models import User
+ from ..app.models import App
+
logger = logging.getLogger(__name__)
+def should_refresh_prices(
+ order: Order,
+ force_update: bool,
+ expired_line_ids: list[UUID],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ allow_sync_webhooks: bool = True,
+) -> bool:
+ if order.status not in ORDER_EDITABLE_STATUS:
+ return False
+
+ if not force_update and not order.should_refresh_prices and not expired_line_ids:
+ return False
+
+ with allow_writer_for_default_connection(database_connection_name):
+ tax_strategy = get_tax_calculation_strategy_for_order(order)
+ if tax_strategy == TaxCalculationStrategy.TAX_APP and not allow_sync_webhooks:
+ return False
+ return True
+
+
+def prepare_order_lines_for_refresh(
+ order: Order,
+ lines: Iterable[OrderLine] | None,
+ expired_line_ids: list[UUID],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+) -> list[EditableOrderLineInfo] | None:
+ with allow_writer_for_default_connection(database_connection_name):
+ if expired_line_ids:
+ # handle line base price expiration
+ return refresh_order_base_prices_and_discounts(
+ order, expired_line_ids, lines
+ )
+
+ return fetch_draft_order_lines_info(order, lines)
+
+
+def process_order_promotion(
+ order: Order,
+ lines_info: list[EditableOrderLineInfo],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+):
+ with allow_writer_for_default_connection(database_connection_name):
+ # order promotion is qualified based on the most actual prices, therefor need to be assessed
+ # on the every recalculation
+ handle_order_promotion(order, lines_info, database_connection_name)
+
+
+def process_order_prices(
+ order: Order,
+ manager: PluginsManager,
+ requestor: Union["App", "User", None],
+ lines: list[OrderLine],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+) -> Promise[tuple[Order, Iterable[OrderLine]]]:
+ def process_calculation_result(_):
+ order.should_refresh_prices = False
+ with allow_writer():
+ with transaction.atomic(savepoint=False):
+ try:
+ locked_order = (
+ order_qs_select_for_update().only("updated_at").get(id=order.id)
+ )
+ except Order.DoesNotExist:
+ # Order was removed. Return data without saving.
+ return order, lines
+
+ # Check whether the order has been modified during the recalculation process by another process.
+ # If so, we should skip saving. The same applies if the order has been removed. This is important
+ # to avoid overwriting changes made by the other requests. Skipping the save function does not affect
+ # the query response because it returns the adjusted order and line info objects.
+ if locked_order.updated_at == order.updated_at:
+ order.save(
+ update_fields=[
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "total_net_amount",
+ "total_gross_amount",
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "base_shipping_price_amount",
+ "shipping_tax_rate",
+ "should_refresh_prices",
+ "tax_error",
+ ]
+ )
+ order.lines.bulk_update(
+ lines,
+ [
+ "unit_price_net_amount",
+ "unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_unit_price_gross_amount",
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "tax_rate",
+ ],
+ )
+ return order, lines
+
+ with allow_writer_for_default_connection(database_connection_name):
+ calculate_prices(
+ order,
+ lines,
+ database_connection_name=database_connection_name,
+ )
+
+ tax_strategy = get_tax_calculation_strategy_for_order(order)
+
+ return calculate_taxes(
+ order,
+ manager,
+ lines,
+ tax_calculation_strategy=tax_strategy,
+ database_connection_name=database_connection_name,
+ requestor=requestor,
+ ).then(process_calculation_result)
+
+
def fetch_order_prices_if_expired(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> tuple[Order, Iterable[OrderLine]]:
+) -> Promise[tuple[Order, Iterable[OrderLine]]]:
"""Fetch order prices with taxes.
First applies order level discounts, then calculates taxes.
@@ -73,91 +205,38 @@ def fetch_order_prices_if_expired(
Prices will be updated if force_update is True
or if order.should_refresh_prices is True.
"""
- if order.status not in ORDER_EDITABLE_STATUS:
- return order, lines or []
expired_line_ids = get_expired_line_ids(order, lines)
- if not force_update and not order.should_refresh_prices and not expired_line_ids:
- return order, lines or []
- tax_strategy = get_tax_calculation_strategy_for_order(order)
- if tax_strategy == TaxCalculationStrategy.TAX_APP and not allow_sync_webhooks:
- return order, lines or []
-
- if expired_line_ids:
- # handle line base price expiration
- lines_info = refresh_order_base_prices_and_discounts(
- order, expired_line_ids, lines
- )
- else:
- lines_info = fetch_draft_order_lines_info(order, lines)
-
- # order promotion is qualified based on the most actual prices, therefor need to be assessed
- # on the every recalculation
- handle_order_promotion(order, lines_info, database_connection_name)
+ if not should_refresh_prices(
+ order=order,
+ force_update=force_update,
+ expired_line_ids=expired_line_ids,
+ database_connection_name=database_connection_name,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ):
+ return Promise.resolve((order, lines or []))
- lines = [line_info.line for line_info in lines_info]
- calculate_prices(
- order,
- lines,
+ lines_info = prepare_order_lines_for_refresh(
+ order=order,
+ lines=lines,
+ expired_line_ids=expired_line_ids,
database_connection_name=database_connection_name,
)
- calculate_taxes(
- order,
- manager,
- lines,
- tax_calculation_strategy=tax_strategy,
- database_connection_name=database_connection_name,
+ if lines_info is None:
+ return Promise.resolve((order, lines or []))
+
+ process_order_promotion(
+ order, lines_info, database_connection_name=database_connection_name
)
- order.should_refresh_prices = False
- with allow_writer():
- with transaction.atomic(savepoint=False):
- try:
- locked_order = (
- order_qs_select_for_update().only("updated_at").get(id=order.id)
- )
- except Order.DoesNotExist:
- # Order was removed. Return data without saving.
- return order, lines
-
- # Check whether the order has been modified during the recalculation process by another process.
- # If so, we should skip saving. The same applies if the order has been removed. This is important
- # to avoid overwriting changes made by the other requests. Skipping the save function does not affect
- # the query response because it returns the adjusted order and line info objects.
- if locked_order.updated_at == order.updated_at:
- order.save(
- update_fields=[
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "total_net_amount",
- "total_gross_amount",
- "undiscounted_total_net_amount",
- "undiscounted_total_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "base_shipping_price_amount",
- "shipping_tax_rate",
- "should_refresh_prices",
- "tax_error",
- ]
- )
- order.lines.bulk_update(
- lines,
- [
- "unit_price_net_amount",
- "unit_price_gross_amount",
- "undiscounted_unit_price_net_amount",
- "undiscounted_unit_price_gross_amount",
- "total_price_net_amount",
- "total_price_gross_amount",
- "undiscounted_total_price_net_amount",
- "undiscounted_total_price_gross_amount",
- "tax_rate",
- ],
- )
-
- return order, lines
+ return process_order_prices(
+ order=order,
+ manager=manager,
+ requestor=requestor,
+ lines=[line_info.line for line_info in lines_info],
+ database_connection_name=database_connection_name,
+ )
def get_expired_line_ids(order: Order, lines: Iterable[OrderLine] | None) -> list[UUID]:
@@ -174,13 +253,46 @@ def get_expired_line_ids(order: Order, lines: Iterable[OrderLine] | None) -> lis
]
+def promise_calculate_taxes_with_error_handling(
+ tax_calculation_strategy: str,
+ tax_app_identifier: str | None,
+ order: Order,
+ lines: Iterable[OrderLine],
+ manager: PluginsManager,
+ prices_entered_with_tax: bool,
+ requestor: Union["App", "User", None],
+ database_connection_name: str,
+) -> Promise[None]:
+ def process_error(e: Exception):
+ if not isinstance(e, TaxDataError):
+ raise e
+ if str(e) != TaxDataErrorMessage.EMPTY:
+ extra = order_info_for_logs(order, lines)
+ if getattr(e, "errors", None):
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
+ order.tax_error = str(e)
+
+ return _calculate_and_add_tax(
+ tax_calculation_strategy,
+ tax_app_identifier,
+ order,
+ lines,
+ manager,
+ prices_entered_with_tax,
+ requestor=requestor,
+ database_connection_name=database_connection_name,
+ ).catch(process_error)
+
+
def calculate_taxes(
order: Order,
manager: PluginsManager,
lines: Iterable[OrderLine],
tax_calculation_strategy: str,
+ requestor: Union["App", "User", None],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
+) -> Promise[None]:
tax_configuration = order.channel.tax_configuration
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
charge_taxes = get_charge_taxes_for_order(order)
@@ -188,56 +300,40 @@ def calculate_taxes(
tax_app_identifier = get_tax_app_identifier_for_order(order)
order.tax_error = None
- if prices_entered_with_tax:
- # If prices are entered with tax, we need to always calculate it anyway, to
- # display the tax rate to the user.
- try:
- _calculate_and_add_tax(
- tax_calculation_strategy,
- tax_app_identifier,
- order,
- lines,
- manager,
- prices_entered_with_tax,
- database_connection_name=database_connection_name,
- )
- except TaxDataError as e:
- if str(e) != TaxDataErrorMessage.EMPTY:
- extra = order_info_for_logs(order, lines)
- if e.errors:
- extra["errors"] = e.errors
- logger.warning(str(e), extra=extra)
- order.tax_error = str(e)
-
- if not should_charge_tax:
- # If charge_taxes is disabled or order is exempt from taxes, remove the
- # tax from the original gross prices.
- remove_tax(order, lines, prices_entered_with_tax)
- else:
- # Prices are entered without taxes.
+ def remove_tax_if_needed(_):
if should_charge_tax:
- # Calculate taxes if charge_taxes is enabled and order is not exempt
- # from taxes.
- try:
- _calculate_and_add_tax(
- tax_calculation_strategy,
- tax_app_identifier,
- order,
- lines,
- manager,
- prices_entered_with_tax,
- database_connection_name=database_connection_name,
- )
- except TaxDataError as e:
- if str(e) != TaxDataErrorMessage.EMPTY:
- extra = order_info_for_logs(order, lines)
- if e.errors:
- extra["errors"] = e.errors
- logger.warning(str(e), extra=extra)
- order.tax_error = str(e)
- else:
- remove_tax(order, lines, prices_entered_with_tax)
+ return
+ # If charge_taxes is disabled or order is exempt from taxes, remove the
+ # tax from the original gross prices.
+ remove_tax(order, lines, prices_entered_with_tax)
+
+ if prices_entered_with_tax:
+ return promise_calculate_taxes_with_error_handling(
+ tax_calculation_strategy=tax_calculation_strategy,
+ tax_app_identifier=tax_app_identifier,
+ order=order,
+ lines=lines,
+ manager=manager,
+ prices_entered_with_tax=prices_entered_with_tax,
+ requestor=requestor,
+ database_connection_name=database_connection_name,
+ ).then(remove_tax_if_needed, remove_tax_if_needed)
+
+ # Prices are entered without taxes.
+ if not should_charge_tax:
+ return Promise.resolve(None).then(remove_tax_if_needed)
+
+ return promise_calculate_taxes_with_error_handling(
+ tax_calculation_strategy=tax_calculation_strategy,
+ tax_app_identifier=tax_app_identifier,
+ order=order,
+ lines=lines,
+ manager=manager,
+ prices_entered_with_tax=prices_entered_with_tax,
+ requestor=requestor,
+ database_connection_name=database_connection_name,
+ )
def _calculate_and_add_tax(
@@ -247,33 +343,11 @@ def _calculate_and_add_tax(
lines: Iterable["OrderLine"],
manager: "PluginsManager",
prices_entered_with_tax: bool,
+ requestor: Union["App", "User", None],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- if tax_calculation_strategy == TaxCalculationStrategy.TAX_APP:
- # If taxAppId is not configured run all active plugins and tax apps.
- # If taxAppId is provided run tax plugin or Tax App. taxAppId can be
- # configured with Avatax plugin identifier.
- if not tax_app_identifier:
- # This is deprecated flow, kept to maintain backward compatibility.
- # In Saleor 4.0 `tax_app_identifier` should be required and the flow should
- # be dropped.
- _recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
- # Get the taxes calculated with apps and apply to order.
- # We should allow empty tax_data in case any tax webhook has not been
- # configured - handled by `allowed_empty_tax_data`
- tax_data = _get_taxes_for_order(
- order, tax_app_identifier, manager, allowed_empty_tax_data=True
- )
- _apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
- else:
- _call_plugin_or_tax_app(
- tax_app_identifier,
- order,
- lines,
- manager,
- prices_entered_with_tax,
- )
- else:
+) -> Promise[None]:
+ @allow_writer_for_default_connection(database_connection_name)
+ def process_flat_taxes(_):
# Get taxes calculated with flat rates and apply to order.
update_order_prices_with_flat_rates(
order,
@@ -282,6 +356,35 @@ def _calculate_and_add_tax(
database_connection_name=database_connection_name,
)
+ if tax_calculation_strategy == TaxCalculationStrategy.FLAT_RATES:
+ return Promise.resolve(None).then(process_flat_taxes)
+
+ if tax_app_identifier:
+ return _call_plugin_or_tax_app(
+ tax_app_identifier,
+ order,
+ lines,
+ manager,
+ prices_entered_with_tax,
+ requestor=requestor,
+ )
+
+ # Deprecated flow when no tax app identifier is provided.
+ def recalculate_with_tax_app_data(tax_data: TaxData | None):
+ _apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
+
+ _recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
+ # Get the taxes calculated with apps and apply to order.
+ # We should allow empty tax_data in case any tax webhook has not been
+ # configured - handled by `allowed_empty_tax_data`
+ return _get_promised_taxes_for_order(
+ order,
+ lines=lines,
+ tax_app_identifier=None,
+ allowed_empty_tax_data=True,
+ requestor=requestor,
+ ).then(recalculate_with_tax_app_data)
+
def _call_plugin_or_tax_app(
tax_app_identifier: str,
@@ -289,14 +392,15 @@ def _call_plugin_or_tax_app(
lines: Iterable["OrderLine"],
manager: "PluginsManager",
prices_entered_with_tax: bool,
-):
- if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ requestor: Union["App", "User", None],
+) -> Promise[None]:
+ def recalculate_with_plugins(_):
plugin_ids = [tax_app_identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")]
plugins = manager.get_plugins(
order.channel.slug, active_only=True, plugin_ids=plugin_ids
)
if not plugins:
- raise TaxDataError(TaxDataErrorMessage.EMPTY)
+ return Promise.reject(TaxDataError(TaxDataErrorMessage.EMPTY))
_recalculate_with_plugins(
manager,
order,
@@ -305,37 +409,52 @@ def _call_plugin_or_tax_app(
plugin_ids=plugin_ids,
)
if order.tax_error:
- raise TaxDataError(order.tax_error)
- else:
- tax_data = _get_taxes_for_order(order, tax_app_identifier, manager)
+ return Promise.reject(TaxDataError(order.tax_error))
+ return Promise.resolve(None)
+
+ def recalculate_with_tax_app_data(tax_data: TaxData | None):
_apply_tax_data(order, lines, tax_data, prices_entered_with_tax)
+ if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ return Promise.resolve(None).then(recalculate_with_plugins)
+
+ return _get_promised_taxes_for_order(
+ order, lines, tax_app_identifier, requestor=requestor
+ ).then(recalculate_with_tax_app_data)
-def _get_taxes_for_order(
+
+def _get_promised_taxes_for_order(
order: "Order",
+ lines: Iterable["OrderLine"],
tax_app_identifier: str | None,
- manager: "PluginsManager",
+ requestor: Union["App", "User", None],
allowed_empty_tax_data: bool = False,
-):
+) -> Promise[TaxData | None]:
"""Get taxes for order from tax apps.
The `allowed_empty_tax_data` flag prevents an error from being raised when tax data
is missing due to the absence of a configured tax app.
"""
- tax_data = None
- try:
- tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
- except TaxDataError as e:
- raise e from e
- finally:
- # log in case the tax_data is missing
+ from .webhooks import order_calculate_taxes
+
+ def process_error(e: Exception):
+ if isinstance(e, TaxDataError):
+ log_address_if_validation_skipped_for_order(order, logger)
+ return Promise.reject(e)
+
+ def process_response(tax_data: TaxData | None) -> Promise[TaxData | None]:
if tax_data is None:
log_address_if_validation_skipped_for_order(order, logger)
- if not tax_data and not allowed_empty_tax_data:
- raise TaxDataError(TaxDataErrorMessage.EMPTY)
+ if not tax_data and not allowed_empty_tax_data:
+ return Promise.reject(TaxDataError(TaxDataErrorMessage.EMPTY))
+ return Promise.resolve(tax_data)
- return tax_data
+ return (
+ order_calculate_taxes.get_taxes(order, lines, tax_app_identifier, requestor)
+ .then(process_response)
+ .catch(process_error)
+ )
def _recalculate_with_plugins(
@@ -652,11 +771,12 @@ def order_line_unit(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> OrderTaxedPricesData:
+) -> Promise[OrderTaxedPricesData]:
"""Return the unit price of provided line, taxes included.
It takes into account all plugins.
@@ -664,30 +784,36 @@ def order_line_unit(
and save them in the model directly.
"""
currency = order.currency
- _, lines = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return OrderTaxedPricesData(
+ undiscounted_price=quantize_price(line.undiscounted_unit_price, currency),
+ price_with_discounts=quantize_price(line.unit_price, currency),
+ )
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- order_line = _find_order_line(lines, order_line)
- return OrderTaxedPricesData(
- undiscounted_price=quantize_price(order_line.undiscounted_unit_price, currency),
- price_with_discounts=quantize_price(order_line.unit_price, currency),
- )
+ ).then(process_result)
def order_line_total(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> OrderTaxedPricesData:
+) -> Promise[OrderTaxedPricesData]:
"""Return the total price of provided line, taxes included.
It takes into account all plugins.
@@ -695,58 +821,68 @@ def order_line_total(
and save them in the model directly.
"""
currency = order.currency
- _, lines = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return OrderTaxedPricesData(
+ undiscounted_price=quantize_price(line.undiscounted_total_price, currency),
+ price_with_discounts=quantize_price(line.total_price, currency),
+ )
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- order_line = _find_order_line(lines, order_line)
- return OrderTaxedPricesData(
- undiscounted_price=quantize_price(
- order_line.undiscounted_total_price, currency
- ),
- price_with_discounts=quantize_price(order_line.total_price, currency),
- )
+ ).then(process_result)
def order_line_tax_rate(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> Decimal | None:
+) -> Promise[Decimal | None]:
"""Return the tax rate of provided line.
It takes into account all plugins.
If the prices are expired, call all order price calculation methods
and save them in the model directly.
"""
- _, lines = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return line.tax_rate
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- order_line = _find_order_line(lines, order_line)
- return order_line.tax_rate
+ ).then(process_result)
def order_line_unit_discount(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
allow_sync_webhooks: bool = True,
-) -> Decimal:
+) -> Promise[Decimal]:
"""Return the line unit discount.
It takes into account all plugins.
@@ -758,63 +894,93 @@ def order_line_unit_discount(
- voucher applied on the line (`SPECIFIC_PRODUCT`, `apply_once_per_order` )
- manual line discounts
"""
- _, lines = fetch_order_prices_if_expired(
- order, manager, lines, force_update, allow_sync_webhooks=allow_sync_webhooks
- )
- order_line = _find_order_line(lines, order_line)
- return order_line.unit_discount
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return line.unit_discount
+
+ return fetch_order_prices_if_expired(
+ order,
+ manager,
+ requestor,
+ lines,
+ force_update,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ).then(process_result)
def order_line_unit_discount_value(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
allow_sync_webhooks: bool = True,
-) -> Decimal:
+) -> Promise[Decimal]:
"""Return the line unit discount value.
It takes into account all plugins.
If the prices are expired, call all order price calculation methods
and save them in the model directly.
"""
- _, lines = fetch_order_prices_if_expired(
- order, manager, lines, force_update, allow_sync_webhooks=allow_sync_webhooks
- )
- order_line = _find_order_line(lines, order_line)
- return order_line.unit_discount_value
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return line.unit_discount_value
+
+ return fetch_order_prices_if_expired(
+ order,
+ manager,
+ requestor,
+ lines,
+ force_update,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ).then(process_result)
def order_line_unit_discount_type(
order: Order,
order_line: OrderLine,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
allow_sync_webhooks: bool = True,
-) -> str | None:
+) -> Promise[str | None]:
"""Return the line unit discount type.
It takes into account all plugins.
If the prices are expired, call all order price calculation methods
and save them in the model directly.
"""
- _, lines = fetch_order_prices_if_expired(
- order, manager, lines, force_update, allow_sync_webhooks=allow_sync_webhooks
- )
- order_line = _find_order_line(lines, order_line)
- return order_line.unit_discount_type
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ _, lines = result
+ line = _find_order_line(lines, order_line)
+ return line.unit_discount_type
+
+ return fetch_order_prices_if_expired(
+ order,
+ manager,
+ requestor,
+ lines,
+ force_update,
+ allow_sync_webhooks=allow_sync_webhooks,
+ ).then(process_result)
def order_undiscounted_shipping(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> TaxedMoney:
+) -> Promise[TaxedMoney]:
"""Return the undiscounted shipping price of the order.
It takes into account all plugins.
@@ -822,25 +988,31 @@ def order_undiscounted_shipping(
and save them in the model directly.
"""
currency = order.currency
- order, _ = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return quantize_price(order.undiscounted_base_shipping_price, currency)
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- return quantize_price(order.undiscounted_base_shipping_price, currency)
+ ).then(process_result)
def order_shipping(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> TaxedMoney:
+) -> Promise[TaxedMoney]:
"""Return the shipping price of the order.
It takes into account all plugins.
@@ -848,50 +1020,62 @@ def order_shipping(
and save them in the model directly.
"""
currency = order.currency
- order, _ = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return quantize_price(order.shipping_price, currency)
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- return quantize_price(order.shipping_price, currency)
+ ).then(process_result)
def order_shipping_tax_rate(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> Decimal | None:
+) -> Promise[Decimal | None]:
"""Return the shipping tax rate of the order.
It takes into account all plugins.
If the prices are expired, call all order price calculation methods
and save them in the model directly.
"""
- order, _ = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return order.shipping_tax_rate
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- return order.shipping_tax_rate
+ ).then(process_result)
def order_subtotal(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-):
+) -> Promise[TaxedMoney]:
"""Return the total price of the order.
It takes into account all plugins.
@@ -899,27 +1083,31 @@ def order_subtotal(
and save them in the model directly.
"""
currency = order.currency
- order, lines = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return quantize_price(order.subtotal, currency)
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- # Lines aren't returned only if
- # we don't pass them to `fetch_order_prices_if_expired`.
- return quantize_price(order.subtotal, currency)
+ ).then(process_result)
def order_total(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> TaxedMoney:
+) -> Promise[TaxedMoney]:
"""Return the total price of the order.
It takes into account all plugins.
@@ -927,25 +1115,31 @@ def order_total(
and save them in the model directly.
"""
currency = order.currency
- order, _ = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return quantize_price(order.total, currency)
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- return quantize_price(order.total, currency)
+ ).then(process_result)
def order_undiscounted_total(
order: Order,
manager: PluginsManager,
+ requestor: Union["App", "User", None],
lines: Iterable[OrderLine] | None = None,
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
-) -> TaxedMoney:
+) -> Promise[TaxedMoney]:
"""Return the undiscounted total price of the order.
It takes into account all plugins.
@@ -953,12 +1147,17 @@ def order_undiscounted_total(
and save them in the model directly.
"""
currency = order.currency
- order, _ = fetch_order_prices_if_expired(
+
+ def process_result(result: tuple[Order, Iterable[OrderLine]]):
+ order, _ = result
+ return quantize_price(order.undiscounted_total, currency)
+
+ return fetch_order_prices_if_expired(
order,
manager,
+ requestor,
lines,
force_update,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
- return quantize_price(order.undiscounted_total, currency)
+ ).then(process_result)
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 9b29dfbf1a..e4512fa43f 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -139,9 +139,8 @@ def fetch_draft_order_lines_info(
)
if lines is None:
- with allow_writer():
- # TODO: load lines with dataloader and pass as an argument
- lines = list(order.lines.prefetch_related(*prefetch_related_fields))
+ # TODO: load lines with dataloader and pass as an argument
+ lines = list(order.lines.prefetch_related(*prefetch_related_fields))
else:
prefetch_related_objects(lines, *prefetch_related_fields)
diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.py
index fa942ff1c7..8aa433a672 100644
--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py
+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py
@@ -18,5 +18,5 @@ def test_fetch_order_prices(
order.status = OrderStatus.UNCONFIRMED
# when & then
- with django_assert_num_queries(30):
- fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ with django_assert_num_queries(29):
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index e238dfd842..dbd2ac5268 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -1,3 +1,4 @@
+import dataclasses
from decimal import Decimal
from typing import Literal
from unittest.mock import Mock, patch, sentinel
@@ -5,6 +6,7 @@ from unittest.mock import Mock, patch, sentinel
import pytest
from django.test import override_settings
from prices import Money, TaxedMoney
+from promise import Promise
from ...core.prices import quantize_price
from ...core.taxes import (
@@ -813,6 +815,7 @@ def fetch_kwargs(order_with_lines, plugins_manager):
return {
"order": order_with_lines,
"manager": plugins_manager,
+ "requestor": None,
"force_update": True,
}
@@ -821,8 +824,9 @@ def fetch_kwargs(order_with_lines, plugins_manager):
def fetch_kwargs_with_lines(order_with_lines, order_lines, plugins_manager):
return {
"order": order_with_lines,
- "lines": order_lines,
"manager": plugins_manager,
+ "requestor": None,
+ "lines": order_lines,
}
@@ -898,7 +902,7 @@ def test_fetch_order_prices_if_expired_plugins(
plugins_manager.calculate_order_total = Mock(return_value=total)
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
order_with_lines.refresh_from_db()
@@ -935,7 +939,7 @@ def test_fetch_order_prices_if_expired_flat_rates(
tc.save()
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
order.refresh_from_db()
line = order.lines.first()
@@ -950,18 +954,22 @@ def test_fetch_order_prices_if_expired_flat_rates(
assert order.shipping_tax_rate == Decimal("0.2300")
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_if_expired_webhooks_success(
- plugins_manager,
+ mocked_trigger_webhook_sync_promise,
fetch_kwargs,
order_with_lines,
tax_data,
+ tax_configuration_tax_app,
):
# given
currency = order_with_lines.currency
- plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
shipping_price = get_taxed_money(tax_data, "shipping_price", currency)
@@ -999,7 +1007,9 @@ def test_fetch_order_prices_if_expired_plugins_with_allow_sync_webhooks_to_false
lines_from_input = fetch_kwargs_with_lines["lines"]
# when
- order, lines = calculations.fetch_order_prices_if_expired(**fetch_kwargs_with_lines)
+ order, lines = calculations.fetch_order_prices_if_expired(
+ **fetch_kwargs_with_lines
+ ).get()
# then
assert order_from_input == order
@@ -1036,7 +1046,7 @@ def test_fetch_order_prices_if_expired_flat_rates_with_allow_sync_webhook_set_to
fetch_kwargs["allow_sync_webhooks"] = False
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
order.refresh_from_db()
line = order.lines.first()
@@ -1064,7 +1074,9 @@ def test_fetch_order_prices_tax_app_with_allow_sync_webhook_set_to_false(
lines_from_input = fetch_kwargs_with_lines["lines"]
# when
- order, lines = calculations.fetch_order_prices_if_expired(**fetch_kwargs_with_lines)
+ order, lines = calculations.fetch_order_prices_if_expired(
+ **fetch_kwargs_with_lines
+ ).get()
# then
assert order_from_input == order
@@ -1072,14 +1084,16 @@ def test_fetch_order_prices_tax_app_with_allow_sync_webhook_set_to_false(
plugins_manager.get_taxes_for_order.assert_not_called()
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
@pytest.mark.parametrize("prices_entered_with_tax", [True, False])
def test_fetch_order_prices_if_expired_recalculate_all_prices(
- plugins_manager,
+ mocked_trigger_webhook_sync_promise,
fetch_kwargs,
order_with_lines,
tax_data,
tax_data_prices_entered_with_tax,
prices_entered_with_tax,
+ tax_configuration_tax_app,
):
# given
tax_data = tax_data_prices_entered_with_tax if prices_entered_with_tax else tax_data
@@ -1093,10 +1107,13 @@ def test_fetch_order_prices_if_expired_recalculate_all_prices(
order_with_lines.undiscounted_total_net_amount = Decimal("0.00")
order_with_lines.undiscounted_total_gross_amount = Decimal("0.00")
order_with_lines.save()
- plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
order_with_lines.refresh_from_db()
@@ -1153,7 +1170,7 @@ def test_fetch_order_prices_when_tax_exemption(
plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
order_with_lines.refresh_from_db()
@@ -1194,7 +1211,7 @@ def test_fetch_order_prices_when_tax_exemption(
def test_fetch_order_prices_if_expired_prefetch(fetch_kwargs, order_lines):
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
assert all(line._state.fields_cache for line in order_lines)
@@ -1204,7 +1221,7 @@ def test_fetch_order_prices_if_expired_prefetch_with_lines(
fetch_kwargs_with_lines, order_lines
):
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs_with_lines)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs_with_lines).get()
# then
assert all(line._state.fields_cache for line in order_lines)
@@ -1225,7 +1242,7 @@ def test_fetch_order_prices_if_expired_use_base_shipping_price(
order.save()
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
order_with_lines.refresh_from_db()
@@ -1261,7 +1278,7 @@ def test_fetch_order_prices_if_expired_flat_rates_and_no_tax_calc_strategy(
)
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
order.refresh_from_db()
line = order.lines.first()
@@ -1269,21 +1286,30 @@ def test_fetch_order_prices_if_expired_flat_rates_and_no_tax_calc_strategy(
assert order.shipping_tax_rate == Decimal("0.2300")
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_on_promotion_if_expired_recalculate_all_prices(
- plugins_manager,
+ mocked_trigger_webhook_sync_promise,
fetch_kwargs,
order_with_lines,
order_line_on_promotion,
tax_data_prices_entered_with_tax,
+ tax_configuration_tax_app,
):
# given
+ tc = order_with_lines.channel.tax_configuration
+ tc.prices_entered_with_tax = True
+ tc.save(update_fields=["prices_entered_with_tax"])
+
tax_data = tax_data_prices_entered_with_tax
currency = order_with_lines.currency
order_line_on_promotion.order = order_with_lines
- plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
order_with_lines.refresh_from_db()
@@ -1326,10 +1352,14 @@ def test_order_line_unit(mocked_fetch_order_prices_if_expired):
unit_price=expected_line_unit_price,
undiscounted_unit_price=expected_line_undiscounted_unit_price,
)
- mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve(
+ (Mock(), [order_line])
+ )
# when
- line_unit_price = calculations.order_line_unit(order, order_line, Mock())
+ line_unit_price = calculations.order_line_unit(
+ order, order_line, None, Mock()
+ ).get()
# then
assert line_unit_price == OrderTaxedPricesData(
@@ -1354,10 +1384,14 @@ def test_order_line_total(mocked_fetch_order_prices_if_expired):
total_price=expected_line_total_price,
undiscounted_total_price=expected_line_undiscounted_total_price,
)
- mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve(
+ (Mock(), [order_line])
+ )
# when
- line_total_price = calculations.order_line_total(order, order_line, Mock())
+ line_total_price = calculations.order_line_total(
+ order, order_line, manager=Mock(), requestor=None
+ ).get()
# then
assert line_total_price == OrderTaxedPricesData(
@@ -1372,10 +1406,14 @@ def test_order_line_tax_rate(mocked_fetch_order_prices_if_expired):
expected_line_tax_rate = sentinel.TAX_RATE
order_line = Mock(pk=1, tax_rate=expected_line_tax_rate)
- mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve(
+ (Mock(), [order_line])
+ )
# when
- line_tax_rate = calculations.order_line_tax_rate(Mock(), order_line, Mock())
+ line_tax_rate = calculations.order_line_tax_rate(
+ order=Mock(), order_line=order_line, manager=Mock(), requestor=None
+ ).get()
# then
assert line_tax_rate == expected_line_tax_rate
@@ -1387,10 +1425,12 @@ def test_order_shipping(mocked_fetch_order_prices_if_expired):
expected_shipping_price = Decimal("1234.0000")
order = Mock(shipping_price=expected_shipping_price, currency="USD")
- mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve((order, Mock()))
# when
- shipping_price = calculations.order_shipping(order, Mock())
+ shipping_price = calculations.order_shipping(
+ order, manager=Mock(), requestor=None
+ ).get()
# then
assert shipping_price == quantize_price(expected_shipping_price, order.currency)
@@ -1402,10 +1442,12 @@ def test_order_shipping_tax_rate(mocked_fetch_order_prices_if_expired):
expected_shipping_tax_rate = sentinel.SHIPPING_TAX_RATE
order = Mock(shipping_tax_rate=expected_shipping_tax_rate)
- mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve((order, Mock()))
# when
- shipping_tax_rate = calculations.order_shipping_tax_rate(order, Mock())
+ shipping_tax_rate = calculations.order_shipping_tax_rate(
+ order, manager=Mock(), requestor=None
+ ).get()
# then
assert shipping_tax_rate == expected_shipping_tax_rate
@@ -1417,10 +1459,10 @@ def test_order_total(mocked_fetch_order_prices_if_expired):
expected_total = Decimal("1234.0000")
order = Mock(total=expected_total, currency="USD")
- mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve((order, Mock()))
# when
- total = calculations.order_total(order, Mock())
+ total = calculations.order_total(order, Mock(), requestor=None).get()
# then
assert total == quantize_price(expected_total, order.currency)
@@ -1446,10 +1488,12 @@ def test_order_subtotal(mocked_fetch_order_prices_if_expired):
for expected_line_total in expected_line_totals:
line = Mock(total_price=expected_line_total, currency=currency)
lines.append(line)
- mocked_fetch_order_prices_if_expired.return_value = (order, lines)
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve((order, lines))
# when
- subtotal = calculations.order_subtotal(order, manager, lines)
+ subtotal = calculations.order_subtotal(
+ order, manager, requestor=None, lines=lines
+ ).get()
# then
expected_subtotal = quantize_price(
@@ -1465,10 +1509,12 @@ def test_order_undiscounted_total(mocked_fetch_order_prices_if_expired):
expected_undiscounted_total = Decimal("1234.0000")
order = Mock(undiscounted_total=expected_undiscounted_total, currency="USD")
- mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+ mocked_fetch_order_prices_if_expired.return_value = Promise.resolve((order, Mock()))
# when
- undiscounted_total = calculations.order_undiscounted_total(order, Mock())
+ undiscounted_total = calculations.order_undiscounted_total(
+ order, manager=Mock(), requestor=None
+ ).get()
# then
assert undiscounted_total == quantize_price(
@@ -1476,12 +1522,12 @@ def test_order_undiscounted_total(mocked_fetch_order_prices_if_expired):
)
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
-@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_order")
@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
def test_fetch_order_data_calls_plugin(
- mock_get_taxes,
mock_calculate_order_line_total,
+ mock_trigger_webhook_sync_promise,
order_with_lines,
order_lines,
):
@@ -1501,50 +1547,51 @@ def test_fetch_order_data_calls_plugin(
fetch_kwargs = {
"order": order,
"manager": get_plugins_manager(allow_replica=False),
+ "requestor": None,
"lines": order_lines,
"force_update": True,
}
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
assert mock_calculate_order_line_total.call_count == 2
- mock_get_taxes.assert_not_called()
+ mock_trigger_webhook_sync_promise.assert_not_called()
@patch("saleor.plugins.manager.PluginsManager.calculate_order_total")
-@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_order")
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
@patch("saleor.order.calculations._apply_tax_data")
-@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
def test_fetch_order_data_calls_tax_app(
mock_apply_tax_data,
- mock_get_taxes,
+ mock_trigger_webhook_sync_promise,
mock_calculate_order_total,
order_with_lines,
order_lines,
- tax_data_response,
+ tax_data,
+ tax_configuration_tax_app,
):
# given
order = order_with_lines
- order.channel.tax_configuration.tax_app_id = "test.app"
- order.channel.tax_configuration.save()
-
- mock_get_taxes.return_value = tax_data_response
+ mock_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
fetch_kwargs = {
"order": order,
"manager": get_plugins_manager(allow_replica=False),
+ "requestor": None,
"lines": order_lines,
"force_update": True,
}
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
mock_apply_tax_data.assert_called_once()
- mock_get_taxes.assert_called_once()
+ mock_trigger_webhook_sync_promise.assert_called_once()
mock_calculate_order_total.assert_not_called()
@@ -1560,23 +1607,26 @@ def test_fetch_order_data_calls_inactive_plugin(
fetch_kwargs = {
"order": order,
"manager": get_plugins_manager(allow_replica=False),
+ "requestor": None,
"lines": order_lines,
"force_update": True,
}
# when
- calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs).get()
# then
assert order_with_lines.tax_error == "Empty tax data."
@pytest.mark.parametrize("tax_app_id", [None, "test.app"])
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_calculate_taxes_empty_tax_data_logging_address(
- tax_app_id, draft_order, order_lines, address, caplog
+ mocked_trigger_webhook_sync_promise, tax_app_id, draft_order, address, caplog
):
# given
order = draft_order
+ order_lines = list(order.lines.all())
address.validation_skipped = True
address.postal_code = "invalid postal code"
@@ -1589,24 +1639,14 @@ def test_calculate_taxes_empty_tax_data_logging_address(
order.channel.tax_configuration.tax_app_id = tax_app_id
order.channel.tax_configuration.save()
- zero_money = zero_taxed_money(order.currency)
- zero_prices = OrderTaxedPricesData(
- undiscounted_price=zero_money,
- price_with_discounts=zero_money,
- )
- manager_methods = {
- "calculate_order_line_unit": Mock(side_effect=TaxError()),
- "calculate_order_line_total": Mock(return_value=zero_prices),
- "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),
- "calculate_order_shipping": Mock(return_value=zero_money),
- "get_taxes_for_order": Mock(return_value=None),
- }
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(None)
+ manager = get_plugins_manager(allow_replica=False)
tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
# when
- calculations.calculate_taxes(order, manager, order_lines, tax_calculation_strategy)
+ calculations.calculate_taxes(
+ order, manager, order_lines, tax_calculation_strategy, requestor=None
+ ).get()
# then
assert (
@@ -1620,7 +1660,9 @@ def test_calculate_taxes_empty_tax_data_logging_address(
[(True, None), (True, "test.app"), (False, None), (False, "test.app")],
)
@patch.object(logger, "warning")
+@patch("saleor.order.webhooks.order_calculate_taxes.get_taxes")
def test_fetch_order_data_tax_data_with_tax_data_error(
+ mocked_get_taxes,
mocked_logger,
prices_entered_with_tax,
tax_app_id,
@@ -1637,24 +1679,12 @@ def test_fetch_order_data_tax_data_with_tax_data_error(
error_msg = "Invalid tax data"
errors = [{"error1": "Negative tax data"}, {"error2": "Invalid tax data"}]
returned_tax_error = TaxDataError(message=error_msg, errors=errors)
- zero_money = zero_taxed_money(order.currency)
- zero_prices = OrderTaxedPricesData(
- undiscounted_price=zero_money,
- price_with_discounts=zero_money,
- )
- manager_methods = {
- "calculate_order_line_unit": Mock(return_value=zero_prices),
- "calculate_order_line_total": Mock(return_value=zero_prices),
- "calculate_order_total": Mock(return_value=zero_money),
- "calculate_order_shipping": Mock(return_value=zero_money),
- "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_taxes_for_order": Mock(side_effect=returned_tax_error),
- }
- manager = Mock(**manager_methods)
+ mocked_get_taxes.return_value = Promise.reject(returned_tax_error)
# when
- calculations.fetch_order_prices_if_expired(order, manager, None, True)
+ calculations.fetch_order_prices_if_expired(
+ order, get_plugins_manager(allow_replica=False), None, None, True
+ ).get()
# then
assert order.tax_error == error_msg
@@ -1694,7 +1724,7 @@ def test_fetch_order_data_tax_data_missing_tax_id_empty_tax_data(
manager = Mock(**manager_methods)
# when
- calculations.fetch_order_prices_if_expired(order, manager, None, True)
+ calculations.fetch_order_prices_if_expired(order, manager, None, None, True).get()
# then
assert not order.tax_error
@@ -1741,7 +1771,7 @@ def test_fetch_order_data_plugin_tax_data_with_negative_values(
manager = get_plugins_manager(allow_replica=False)
# when
- calculations.fetch_order_prices_if_expired(order, manager, None, True)
+ calculations.fetch_order_prices_if_expired(order, manager, None, None, True).get()
# then
assert order.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE
@@ -1789,7 +1819,7 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(
manager = get_plugins_manager(allow_replica=False)
# when
- calculations.fetch_order_prices_if_expired(order, manager, None, True)
+ calculations.fetch_order_prices_if_expired(order, manager, None, None, True).get()
# then
assert order.tax_error == TaxDataErrorMessage.OVERFLOW
@@ -1845,8 +1875,9 @@ def test_fetch_order_prices_flat_rates_with_weighted_shipping_tax(
calculations.fetch_order_prices_if_expired(
order=order,
manager=plugins_manager,
+ requestor=None,
force_update=True,
- )
+ ).get()
# then
order.refresh_from_db()
@@ -1877,6 +1908,7 @@ def test_fetch_order_prices_if_expired_order_removed_before_save(
fetch_kwargs = {
"order": order,
"manager": manager,
+ "requestor": None,
"lines": lines,
"force_update": True,
}
@@ -1891,7 +1923,7 @@ def test_fetch_order_prices_if_expired_order_removed_before_save(
):
result_order, result_lines = calculations.fetch_order_prices_if_expired(
**fetch_kwargs
- )
+ ).get()
# then
# Check if order was deleted
@@ -1925,6 +1957,7 @@ def test_fetch_order_prices_if_expired_order_updated_during_price_recalculation(
fetch_kwargs = {
"order": order,
"manager": manager,
+ "requestor": None,
"lines": lines,
"force_update": True,
}
@@ -1941,7 +1974,7 @@ def test_fetch_order_prices_if_expired_order_updated_during_price_recalculation(
):
result_order, result_lines = calculations.fetch_order_prices_if_expired(
**fetch_kwargs
- )
+ ).get()
# then
# Check if prices are recalculated and returned in objects
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
index 8c1e8f20db..f354287fd7 100644
--- a/saleor/order/tests/test_fetch_order_prices.py
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -35,8 +35,8 @@ def test_fetch_order_prices_catalogue_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderLineDiscount.objects.count() == 1
@@ -153,8 +153,8 @@ def test_fetch_order_prices_order_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert not OrderLineDiscount.objects.exists()
@@ -285,8 +285,8 @@ def test_fetch_order_prices_gift_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert len(lines) == 3
@@ -416,8 +416,8 @@ def test_fetch_order_prices_catalogue_and_order_discounts_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1 = [line for line in lines if line.quantity == 3][0]
@@ -569,8 +569,8 @@ def test_fetch_order_prices_catalogue_and_gift_discounts_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert len(lines) == 3
@@ -729,8 +729,8 @@ def test_fetch_order_prices_catalogue_and_order_discounts_exceed_total_flat_rate
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1 = [line for line in lines if line.quantity == 3][0]
@@ -851,8 +851,8 @@ def test_fetch_order_prices_manual_discount_and_order_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert not OrderLineDiscount.objects.exists()
@@ -988,8 +988,8 @@ def test_fetch_order_prices_manual_discount_and_gift_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert not OrderLineDiscount.objects.exists()
@@ -1135,8 +1135,8 @@ def test_fetch_order_prices_manual_discount_and_catalogue_discount_flat_rates(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
catalogue_discount = OrderLineDiscount.objects.get()
@@ -1317,8 +1317,8 @@ def test_fetch_order_prices_manual_order_discount_voucher_specific_product(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -1435,8 +1435,8 @@ def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_ord
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
discounted_line, line_1 = lines
@@ -1525,13 +1525,17 @@ def test_fetch_order_prices_order_promotion_discount_race_condition(
# when
def call_before_creating_order_promotion_line_discount(*args, **kwargs):
- calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
with race_condition.RunBefore(
"saleor.discount.utils.promotion._handle_order_promotion",
call_before_creating_order_promotion_line_discount,
):
- calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+ calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 1
@@ -1596,8 +1600,8 @@ def test_fetch_order_prices_voucher_shipping_and_manual_discount_fixed(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 2
@@ -1691,8 +1695,8 @@ def test_fetch_order_prices_voucher_shipping_and_manual_discount_percentage(
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 2
@@ -1785,8 +1789,8 @@ def test_fetch_order_prices_voucher_shipping_and_manual_discount_fixed_exceed_to
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderDiscount.objects.count() == 2
@@ -1840,8 +1844,8 @@ def test_fetch_order_prices_catalogue_discount_prices_entered_with_tax_tax_exemp
# when
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert OrderLineDiscount.objects.count() == 1
@@ -1961,8 +1965,8 @@ def test_fetch_order_prices_removing_catalogue_promotion_doesnt_remove_discount(
tax_rate = Decimal("1.23")
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
variant_1 = line_1.variant
variant_1_listing = variant_1.channel_listings.get(channel=channel)
variant_1_undiscounted_unit_price = variant_1_listing.price_amount
@@ -1977,8 +1981,8 @@ def test_fetch_order_prices_removing_catalogue_promotion_doesnt_remove_discount(
fetch_variants_for_promotion_rules(PromotionRule.objects.all())
update_discounted_prices_for_promotion(Product.objects.all())
order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
+ order, plugins_manager, None, None, True
+ ).get()
# then
variant_1_listing.refresh_from_db()
diff --git a/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
index 3118b0af39..6ad9edf4f9 100644
--- a/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
+++ b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
@@ -60,8 +60,8 @@ def test_fetch_order_prices_lines_expired_base_prices(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -149,8 +149,8 @@ def test_fetch_order_prices_single_line_expired_base_prices(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -302,8 +302,8 @@ def test_fetch_order_prices_lines_expired_catalogue_discount(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -473,8 +473,8 @@ def test_fetch_order_prices_single_line_expired_catalogue_discount(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -606,8 +606,8 @@ def test_fetch_order_prices_lines_expired_new_catalogue_discount(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -756,8 +756,8 @@ def test_fetch_order_prices_lines_expired_manual_line_discount(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -913,8 +913,8 @@ def test_fetch_order_prices_single_line_expired_manual_line_discount(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -1077,8 +1077,8 @@ def test_fetch_order_prices_lines_expired_specific_product_voucher(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -1236,8 +1236,8 @@ def test_fetch_order_prices_single_line_expired_specific_product_voucher(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -1392,8 +1392,8 @@ def test_fetch_order_prices_lines_expired_apply_once_per_order_voucher(
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -1538,8 +1538,8 @@ def test_fetch_order_prices_single_line_expired_apply_once_per_order_voucher_new
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
@@ -1689,8 +1689,8 @@ def test_fetch_order_prices_single_line_expired_apply_once_per_order_voucher_old
# when
order, lines = fetch_order_prices_if_expired(
- order, plugins_manager, lines=None, force_update=False
- )
+ order, plugins_manager, requestor=None, lines=None, force_update=False
+ ).get()
# then
line_1, line_2 = lines
diff --git a/saleor/order/tests/test_fetch_order_prices_tax_app.py b/saleor/order/tests/test_fetch_order_prices_tax_app.py
index 8a73a095fb..ae471af4ad 100644
--- a/saleor/order/tests/test_fetch_order_prices_tax_app.py
+++ b/saleor/order/tests/test_fetch_order_prices_tax_app.py
@@ -1,8 +1,10 @@
+import dataclasses
from decimal import Decimal
-from unittest.mock import Mock
+from unittest.mock import patch
import graphene
import pytest
+from promise import Promise
from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxLineData
@@ -23,7 +25,13 @@ def order_with_lines(order_with_lines):
return order_with_lines
-def test_fetch_order_prices_tax_app(order_with_lines, tax_configuration_tax_app):
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_fetch_order_prices_tax_app(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
# given
order = order_with_lines
currency = order.currency
@@ -77,11 +85,14 @@ def test_fetch_order_prices_tax_app(order_with_lines, tax_configuration_tax_app)
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert order.shipping_price_net_amount == shipping_price_net
@@ -123,9 +134,12 @@ def test_fetch_order_prices_tax_app(order_with_lines, tax_configuration_tax_app)
assert line_2.unit_discount_amount == Decimal(0)
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_catalogue_discount_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines_and_catalogue_promotion,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines_and_catalogue_promotion
@@ -194,11 +208,14 @@ def test_fetch_order_prices_catalogue_discount_tax_app(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discount = line_1.discounts.get()
@@ -252,9 +269,12 @@ def test_fetch_order_prices_catalogue_discount_tax_app(
assert line_2.unit_price_gross_amount == line_2_unit_price_gross
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_order_discount_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines_and_order_promotion,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines_and_order_promotion
@@ -339,11 +359,14 @@ def test_fetch_order_prices_order_discount_tax_app(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discount = order.discounts.get()
@@ -421,9 +444,12 @@ def test_fetch_order_prices_order_discount_tax_app(
)
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
+ mocked_trigger_webhook_sync_promise,
order_with_lines_and_order_promotion,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines_and_order_promotion
@@ -509,11 +535,14 @@ def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
discount = order.discounts.get()
@@ -601,10 +630,13 @@ def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
)
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_gift_discount_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines_and_gift_promotion,
tax_configuration_tax_app,
channel_USD,
+ plugins_manager,
):
# given
order = order_with_lines_and_gift_promotion
@@ -669,12 +701,14 @@ def test_fetch_order_prices_gift_discount_tax_app(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
-
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
assert order.shipping_price_net_amount == shipping_price_net
assert order.shipping_price_gross_amount == shipping_price_gross
@@ -732,9 +766,12 @@ def test_fetch_order_prices_gift_discount_tax_app(
assert gift_discount.amount.amount == gift_price
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_catalogue_and_order_discounts_tax_app(
+ mocked_trigger_webhook_sync_promise,
draft_order_and_promotions,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order, rule_catalogue, rule_total, _ = draft_order_and_promotions
@@ -797,11 +834,14 @@ def test_fetch_order_prices_catalogue_and_order_discounts_tax_app(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -931,10 +971,13 @@ def test_fetch_order_prices_catalogue_and_order_discounts_tax_app(
)
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines,
voucher,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines
@@ -1051,11 +1094,14 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -1138,10 +1184,13 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
assert voucher_discount.amount.amount == voucher_reward
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines,
voucher,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines
@@ -1253,11 +1302,14 @@ def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_ap
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -1340,10 +1392,13 @@ def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_ap
assert voucher_discount.amount.amount == voucher_reward
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines,
voucher,
tax_configuration_tax_app,
+ plugins_manager,
):
# given
order = order_with_lines
@@ -1455,11 +1510,14 @@ def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
],
)
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(
+ dataclasses.asdict(tax_data)
+ )
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
@@ -1543,10 +1601,13 @@ def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
assert shipping_voucher_discount.amount.amount == voucher_discount_amount
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
def test_fetch_order_prices_entire_order_voucher_no_tax_data_tax_app(
+ mocked_trigger_webhook_sync_promise,
order_with_lines,
voucher,
tax_configuration_tax_app,
+ plugins_manager,
):
"""Test if for empty tax data, Saleor apply correctly net values."""
# given
@@ -1609,11 +1670,12 @@ def test_fetch_order_prices_entire_order_voucher_no_tax_data_tax_app(
tax_data = {}
- manager_methods = {"get_taxes_for_order": Mock(return_value=tax_data)}
- manager = Mock(**manager_methods)
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve(tax_data)
# when
- order, lines = fetch_order_prices_if_expired(order, manager, None, True)
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, None, None, True
+ ).get()
# then
line_1, line_2 = lines
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 1b57b74b3a..8068fc0560 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -71,8 +71,11 @@ def test_order_get_subtotal(order_with_lines):
)
fetch_order_prices_if_expired(
- order_with_lines, get_plugins_manager(allow_replica=False), force_update=True
- )
+ order_with_lines,
+ get_plugins_manager(allow_replica=False),
+ requestor=None,
+ force_update=True,
+ ).get()
target_subtotal = order_with_lines.total - order_with_lines.shipping_price
assert order_with_lines.subtotal == target_subtotal
diff --git a/saleor/order/tests/webhooks/static_payloads/__init__.py b/saleor/order/tests/webhooks/static_payloads/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py b/saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py
new file mode 100644
index 0000000000..556e4dd410
--- /dev/null
+++ b/saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py
@@ -0,0 +1,364 @@
+import datetime
+import json
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+import pytest
+from freezegun import freeze_time
+
+from .....core.prices import quantize_price
+from .....discount import DiscountType, DiscountValueType, VoucherType
+from ....webhooks.order_calculate_taxes import (
+ generate_order_payload_for_tax_calculation,
+)
+
+
+def order_for_payload(fulfilled_order, voucher_percentage):
+ order = fulfilled_order
+
+ order.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=Decimal(20),
+ amount_value=Decimal("33.0"),
+ reason="Discount from staff",
+ )
+ discount = order.discounts.create(
+ type=DiscountType.VOUCHER,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=Decimal(10),
+ amount_value=Decimal("16.5"),
+ name="Voucher",
+ voucher=voucher_percentage,
+ )
+
+ discount.created_at = datetime.datetime.now(tz=datetime.UTC) + datetime.timedelta(
+ days=1
+ )
+ discount.save(update_fields=["created_at"])
+
+ line_without_sku = order.lines.last()
+ line_without_sku.product_sku = None
+ line_without_sku.save()
+
+ return order
+
+
+@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
+# @patch("saleor.order.webhooks.order_calculate_taxes._generate_order_lines_payload_for_tax_calculation")
+def test_generate_order_payload_for_tax_calculation(
+ # mocked_order_lines,
+ order_for_payload,
+ prices_entered_with_tax,
+):
+ # given
+ order = order_for_payload
+
+ tax_configuration = order.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()
+
+ discount_1, discount_2 = list(order.discounts.all())
+ user = order.user
+
+ # when
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+
+ # then
+ currency = order.currency
+
+ assert payload == {
+ "type": "Order",
+ "id": graphene.Node.to_global_id("Order", order.id),
+ "channel": {
+ "id": graphene.Node.to_global_id("Channel", order.channel_id),
+ "type": "Channel",
+ "slug": order.channel.slug,
+ "currency_code": order.channel.currency_code,
+ },
+ "address": {
+ "id": graphene.Node.to_global_id("Address", order.shipping_address_id),
+ "type": "Address",
+ "first_name": order.shipping_address.first_name,
+ "last_name": order.shipping_address.last_name,
+ "company_name": order.shipping_address.company_name,
+ "street_address_1": order.shipping_address.street_address_1,
+ "street_address_2": order.shipping_address.street_address_2,
+ "city": order.shipping_address.city,
+ "city_area": order.shipping_address.city_area,
+ "postal_code": order.shipping_address.postal_code,
+ "country": order.shipping_address.country.code,
+ "country_area": order.shipping_address.country_area,
+ "phone": str(order.shipping_address.phone),
+ },
+ "user_id": graphene.Node.to_global_id("User", user.pk),
+ "user_public_metadata": user.metadata,
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "currency": order.currency,
+ "shipping_name": order.shipping_method.name,
+ "shipping_amount": str(
+ quantize_price(order.base_shipping_price_amount, currency)
+ ),
+ "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)),
+ },
+ ],
+ "lines": [
+ {
+ "type": "OrderLine",
+ "id": graphene.Node.to_global_id("OrderLine", line.id),
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "quantity": line.quantity,
+ "variant_id": line.product_variant_id,
+ "full_name": line.variant.display_product() if line.variant else None,
+ "product_metadata": (
+ line.variant.product.metadata if line.variant else {}
+ ),
+ "product_type_metadata": (
+ line.variant.product.product_type.metadata if line.variant else {}
+ ),
+ "charge_taxes": True,
+ "sku": line.product_sku,
+ "unit_amount": str(
+ quantize_price(line.base_unit_price_amount, line.currency)
+ ),
+ "total_amount": str(
+ quantize_price(
+ line.base_unit_price_amount * line.quantity, line.currency
+ )
+ ),
+ }
+ for line in order.lines.all()
+ ],
+ }
+
+
+@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
+@patch(
+ "saleor.order.webhooks.order_calculate_taxes._generate_order_lines_payload_for_tax_calculation"
+)
+def test_generate_order_payload_for_tax_calculation_entire_order_voucher(
+ mocked_order_lines, order_for_payload, prices_entered_with_tax, voucher
+):
+ # given
+ order = order_for_payload
+
+ tax_configuration = order.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()
+
+ order_lines = '"order_lines"'
+ mocked_order_lines.return_value = order_lines
+
+ discount_1, discount_2 = list(order.discounts.all())
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = False
+ voucher.save()
+ discount_2.voucher = voucher
+ discount_2.save()
+ user = order.user
+
+ # when
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+
+ # then
+ currency = order.currency
+
+ assert payload == {
+ "type": "Order",
+ "id": graphene.Node.to_global_id("Order", order.id),
+ "channel": {
+ "id": graphene.Node.to_global_id("Channel", order.channel_id),
+ "type": "Channel",
+ "slug": order.channel.slug,
+ "currency_code": order.channel.currency_code,
+ },
+ "address": {
+ "id": graphene.Node.to_global_id("Address", order.shipping_address_id),
+ "type": "Address",
+ "first_name": order.shipping_address.first_name,
+ "last_name": order.shipping_address.last_name,
+ "company_name": order.shipping_address.company_name,
+ "street_address_1": order.shipping_address.street_address_1,
+ "street_address_2": order.shipping_address.street_address_2,
+ "city": order.shipping_address.city,
+ "city_area": order.shipping_address.city_area,
+ "postal_code": order.shipping_address.postal_code,
+ "country": order.shipping_address.country.code,
+ "country_area": order.shipping_address.country_area,
+ "phone": str(order.shipping_address.phone),
+ },
+ "user_id": graphene.Node.to_global_id("User", user.pk),
+ "user_public_metadata": user.metadata,
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "currency": order.currency,
+ "shipping_name": order.shipping_method.name,
+ "shipping_amount": str(
+ quantize_price(order.base_shipping_price_amount, currency)
+ ),
+ "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)),
+ },
+ ],
+ "lines": json.loads(order_lines),
+ }
+ mocked_order_lines.assert_called_once()
+
+
+@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_order_payload_for_tax_calculation_line_level_voucher_excluded(
+ order_for_payload, prices_entered_with_tax, voucher
+):
+ # given
+ order = order_for_payload
+
+ tax_configuration = order.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+
+ discount_1, discount_2 = list(order.discounts.all())
+ voucher.type = VoucherType.ENTIRE_ORDER
+ # line level vouchers should be excluded from discounts
+ voucher.apply_once_per_order = True
+ voucher.save()
+ discount_2.voucher = voucher
+ discount_2.save()
+
+ # when
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+
+ # then
+ assert payload["discounts"] == [
+ {
+ "name": discount_1.name,
+ "amount": str(quantize_price(discount_1.amount_value, order.currency)),
+ },
+ ]
+
+
[email protected]("charge_taxes", [True, False])
+def test_order_lines_for_tax_calculation_with_removed_variant(
+ order, order_line_with_one_allocation, charge_taxes
+):
+ tax_configuration = order.channel.tax_configuration
+ tax_configuration.charge_taxes = charge_taxes
+ tax_configuration.save(update_fields=["charge_taxes"])
+ tax_configuration.country_exceptions.all().delete()
+
+ order.lines.add(order_line_with_one_allocation)
+ currency = order.currency
+ line = order_line_with_one_allocation
+ line.voucher_code = "Voucher001"
+ line.unit_discount_amount = Decimal("10.0")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
+ line.sale_id = graphene.Node.to_global_id("Sale", 1)
+ variant = line.variant
+ line.variant = None
+ line.save()
+
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+ lines_payload = payload.get("lines")
+
+ assert len(lines_payload) == 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ line_payload = lines_payload[0]
+ assert line_payload == {
+ "type": "OrderLine",
+ "id": line_id,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "full_name": None,
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "product_metadata": {},
+ "product_type_metadata": {},
+ "quantity": line.quantity,
+ "sku": line.product_sku,
+ "charge_taxes": charge_taxes,
+ "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
+ "total_amount": str(
+ quantize_price(line.base_unit_price_amount * line.quantity, currency)
+ ),
+ }
+
+
+ ("charge_taxes", "prices_entered_with_tax"),
+ [(False, False), (False, True), (True, False), (True, True)],
+)
+def test_order_lines_for_tax_calculation_have_all_required_fields(
+ order,
+ order_line_with_one_allocation,
+ charge_taxes,
+ prices_entered_with_tax,
+):
+ tax_configuration = order.channel.tax_configuration
+ tax_configuration.charge_taxes = charge_taxes
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ order.lines.add(order_line_with_one_allocation)
+ currency = order.currency
+ line = order_line_with_one_allocation
+ line.voucher_code = "Voucher001"
+ line.unit_discount_amount = Decimal("10.0")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
+ line.sale_id = graphene.Node.to_global_id("Sale", 1)
+ line.save()
+ variant = line.variant
+ product = variant.product
+ product_type = product.product_type
+ product.metadata = {"product_meta": "value"}
+ product.save()
+ product_type.metadata = {"product_type_meta": "value"}
+ product_type.save()
+
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+ lines_payload = payload.get("lines")
+
+ assert len(lines_payload) == 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ line_payload = lines_payload[0]
+ assert line_payload == {
+ "type": "OrderLine",
+ "id": line_id,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "full_name": variant.display_product(),
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "product_metadata": {"product_meta": "value"},
+ "product_type_metadata": {"product_type_meta": "value"},
+ "quantity": line.quantity,
+ "sku": line.product_sku,
+ "charge_taxes": charge_taxes,
+ "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
+ "total_amount": str(
+ quantize_price(line.base_unit_price_amount * line.quantity, currency)
+ ),
+ }
diff --git a/saleor/order/tests/webhooks/subscriptions/__init__.py b/saleor/order/tests/webhooks/subscriptions/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/order/tests/webhooks/subscriptions/test_order_calculate_taxes.py b/saleor/order/tests/webhooks/subscriptions/test_order_calculate_taxes.py
new file mode 100644
index 0000000000..74f31d9144
--- /dev/null
+++ b/saleor/order/tests/webhooks/subscriptions/test_order_calculate_taxes.py
@@ -0,0 +1,1345 @@
+import json
+from decimal import Decimal
+from unittest.mock import ANY, Mock, patch
+
+import pytest
+from freezegun import freeze_time
+from prices import Money, TaxedMoney
+from promise import Promise
+
+from .....core.prices import quantize_price
+from .....discount import (
+ DiscountType,
+ DiscountValueType,
+ RewardType,
+ RewardValueType,
+ VoucherType,
+)
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+from .....graphql.core.utils import to_global_id_or_none
+from .....plugins.manager import get_plugins_manager
+from .....tax import TaxableObjectDiscountType
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from .....webhook.transport.synchronous.transport import (
+ create_delivery_for_subscription_sync_event,
+)
+from .... import OrderStatus
+from ....calculations import fetch_order_prices_if_expired
+from ....models import Order
+from ....utils import (
+ create_manual_order_discount,
+ update_discount_for_order_line,
+)
+
+TAXES_SUBSCRIPTION_QUERY = """
+subscription {
+ event {
+ __typename
+ ... on CalculateTaxes {
+ taxBase {
+ pricesEnteredWithTax
+ currency
+ shippingPrice {
+ amount
+ }
+ address {
+ id
+ }
+ channel {
+ id
+ }
+
+ discounts {
+ amount {
+ amount
+ }
+ type
+ }
+
+ lines {
+ quantity
+ chargeTaxes
+ productName
+ variantName
+ productSku
+ unitPrice {
+ amount
+ }
+
+ totalPrice {
+ amount
+ }
+ sourceLine {
+ __typename
+ ... on OrderLine {
+ id
+ }
+ }
+ }
+ sourceObject {
+ __typename
+ ... on Order {
+ id
+ metadata {
+ key
+ value
+ }
+ privateMetadata {
+ key
+ value
+ }
+ user {
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def subscription_order_calculate_taxes(subscription_webhook):
+ return subscription_webhook(
+ TAXES_SUBSCRIPTION_QUERY, WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
[email protected]("charge_taxes", [True, False])
+def test_order_calculate_taxes(order_line, tax_app, shipping_zone, charge_taxes):
+ # 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.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_method
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=tax_app,
+ target_url="http://127.0.0.1/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ tax_configuration = order.channel.tax_configuration
+ tax_configuration.charge_taxes = charge_taxes
+ tax_configuration.save(update_fields=["charge_taxes"])
+ tax_configuration.country_exceptions.all().delete()
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)
+
+ # then
+ shipping_price_amount = shipping_method.channel_listings.get(
+ channel=order.channel
+ ).price.amount
+ shipping_price_amount = quantize_price(shipping_price_amount, order.currency)
+ assert expected_shipping_price != shipping_price_amount
+ assert json.loads(deliveries.payload.get_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": charge_taxes,
+ "productName": "Test product",
+ "productSku": "SKU_A",
+ "quantity": 3,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(order_line),
+ },
+ "totalPrice": {"amount": 36.9},
+ "unitPrice": {"amount": 12.3},
+ "variantName": "SKU_A",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": expected_shipping_price.amount},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+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.undiscounted_base_shipping_price = expected_shipping_price
+ 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",
+ "undiscounted_base_shipping_price_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, None, order.lines.all(), True).get()
+
+ 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://127.0.0.1/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.get_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),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_draft_order_calculate_taxes_entire_order_voucher(
+ draft_order_with_voucher, subscription_order_calculate_taxes, shipping_zone
+):
+ # given
+ order = draft_order_with_voucher
+ webhook = subscription_order_calculate_taxes
+ 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)
+ channel_listing = voucher.channel_listings.get()
+ channel_listing.discount_value = discount_amount
+ channel_listing.save(update_fields=["discount_value"])
+
+ order_discount = order.discounts.first()
+ order_discount.value = discount_amount
+ order_discount.save(update_fields=["value"])
+
+ order.undiscounted_base_shipping_price = expected_shipping_price
+ 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",
+ "undiscounted_base_shipping_price_amount",
+ ]
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ fetch_order_prices_if_expired(order, manager, None, order.lines.all(), True).get()
+
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": float(discount_amount)},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ }
+ ],
+ "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),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_draft_order_calculate_taxes_apply_once_per_order_voucher(
+ draft_order_with_voucher, subscription_order_calculate_taxes, shipping_zone
+):
+ # given
+ order = draft_order_with_voucher
+ webhook = subscription_order_calculate_taxes
+ 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.undiscounted_base_shipping_price = expected_shipping_price
+ 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",
+ "undiscounted_base_shipping_price_amount",
+ ]
+ )
+
+ manager = get_plugins_manager(allow_replica=False)
+ fetch_order_prices_if_expired(order, manager, None, order.lines.all(), True).get()
+
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.get_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": line.product_name,
+ "productSku": line.product_sku,
+ "quantity": line.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line),
+ },
+ "totalPrice": {
+ "amount": float(
+ round(line.base_unit_price_amount * line.quantity, 2)
+ )
+ },
+ "unitPrice": {
+ "amount": float(round(line.base_unit_price_amount, 2))
+ },
+ "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),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_specific_product_voucher(
+ order_line,
+ subscription_order_calculate_taxes,
+ shipping_zone,
+ voucher_specific_product_type,
+):
+ # given
+ order = order_line.order
+ webhook = subscription_order_calculate_taxes
+ expected_shipping_price = Money("2.00", order.currency)
+ order.undiscounted_base_shipping_price = expected_shipping_price
+ order.base_shipping_price = expected_shipping_price
+ order.shipping_price = TaxedMoney(
+ net=expected_shipping_price, gross=expected_shipping_price
+ )
+ order.status = OrderStatus.DRAFT
+ order.voucher = voucher_specific_product_type
+ order.voucher_code = voucher_specific_product_type.codes.first().code
+ order.save(
+ update_fields=[
+ "base_shipping_price_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "undiscounted_base_shipping_price_amount",
+ "voucher_code",
+ "voucher",
+ "status",
+ ]
+ )
+
+ voucher_specific_product_type.discount_value_type = DiscountValueType.FIXED
+ voucher_specific_product_type.save(update_fields=["discount_value_type"])
+
+ voucher_listing = voucher_specific_product_type.channel_listings.get(
+ channel=order.channel
+ )
+ unit_discount_amount = Decimal(2)
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher_specific_product_type.variants.add(order_line.variant)
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ manager = get_plugins_manager(allow_replica=False)
+ fetch_order_prices_if_expired(order, manager, None, order.lines.all(), True).get()
+
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ expected_total_price_amount = (
+ order_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ ) * order_line.quantity
+ assert json.loads(deliveries.payload.get_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),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@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_order_calculate_taxes,
+ shipping_zone,
+ charge_taxes,
+):
+ # given
+ order = draft_order_with_free_shipping_voucher
+ webhook = subscription_order_calculate_taxes
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.get_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),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_with_manual_discount(
+ order_with_lines,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+):
+ # given
+ order = order_with_lines
+ shipping_price_amount = order.base_shipping_price_amount
+
+ discount_value = Decimal(20)
+ order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=discount_value,
+ reason="Discount reason",
+ )
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+ subtotal_amount = (
+ line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
+ )
+ total_amount = subtotal_amount + shipping_price_amount
+
+ manager = Mock(get_taxes_for_order=Mock(return_value={}))
+ fetch_order_prices_if_expired(order, manager, None, [line_1, line_2], True).get()
+
+ webhook = subscription_order_calculate_taxes
+
+ # Manual discount applies both to subtotal and shipping. For tax calculation it
+ # requires to be split into subtotal and shipping portion.
+ manual_discount_subtotal_portion = subtotal_amount / total_amount * discount_value
+ manual_discount_shipping_portion = discount_value - manual_discount_subtotal_portion
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "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": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {
+ "amount": float(line_1_unit_price * line_1.quantity)
+ },
+ "unitPrice": {"amount": float(line_1_unit_price)},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {
+ "amount": float(line_2_unit_price * line_2.quantity)
+ },
+ "unitPrice": {"amount": float(line_2_unit_price)},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": float(shipping_price_amount)},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_empty_order(
+ order, webhook_app, permission_handle_taxes, channel_USD
+):
+ # given
+ order = Order.objects.create(channel=channel_USD, currency="USD", lines_count=0)
+ webhook_app.permissions.add(permission_handle_taxes)
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://127.0.0.1/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
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": None,
+ "currency": "USD",
+ "discounts": [],
+ "lines": [],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "channel": {"id": to_global_id_or_none(order.channel)},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": None,
+ },
+ },
+ }
+
+
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_order_calculate_taxes_order_promotion(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ order_promotion_with_rule,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ webhook = subscription_order_calculate_taxes
+ channel = order.channel
+ shipping_price_amount = order.base_shipping_price_amount
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+
+ promotion = order_promotion_with_rule
+ rule = promotion.rules.get()
+ rule.order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ }
+ rule.save(update_fields=["order_predicate"])
+ reward_value = Decimal(5)
+ assert rule.reward_value == reward_value
+ assert rule.reward_value_type == RewardValueType.FIXED
+ assert rule.reward_type == RewardType.SUBTOTAL_DISCOUNT
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve({})
+
+ # when
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": reward_value},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ }
+ ],
+ "channel": {"id": to_global_id_or_none(channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
+ "unitPrice": {"amount": line_1_unit_price},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
+ "unitPrice": {"amount": line_2_unit_price},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": shipping_price_amount},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_order_calculate_taxes_order_voucher_and_manual_discount(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ voucher,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ webhook = subscription_order_calculate_taxes
+ channel = order.channel
+ shipping_price_amount = order.base_shipping_price_amount
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+ subtotal_amount = (
+ line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
+ )
+ total_amount = subtotal_amount + shipping_price_amount
+
+ assert voucher.type == VoucherType.ENTIRE_ORDER
+ order.voucher = voucher
+ order.save(update_fields=["voucher_id"])
+
+ manual_reward = Decimal(10)
+ create_manual_order_discount(
+ order=order,
+ reason="Manual discount",
+ value_type=DiscountValueType.FIXED,
+ value=manual_reward,
+ )
+
+ subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward
+ shipping_manual_reward_portion = manual_reward - subtotal_manual_reward_portion
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve({})
+
+ # when
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)
+ assert manual_discount.amount_value == manual_reward
+ assert not order.discounts.filter(type=DiscountType.VOUCHER).first()
+
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": subtotal_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ },
+ {
+ "amount": {"amount": shipping_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SHIPPING,
+ },
+ ],
+ "channel": {"id": to_global_id_or_none(channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
+ "unitPrice": {"amount": line_1_unit_price},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
+ "unitPrice": {"amount": line_2_unit_price},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": shipping_price_amount},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_order_calculate_taxes_order_promotion_and_manual_discount(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ order_promotion_with_rule,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ webhook = subscription_order_calculate_taxes
+ channel = order.channel
+ shipping_price_amount = order.base_shipping_price_amount
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+ subtotal_amount = (
+ line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
+ )
+ total_amount = subtotal_amount + shipping_price_amount
+
+ promotion = order_promotion_with_rule
+ rule = promotion.rules.get()
+ rule.order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ }
+ rule.save(update_fields=["order_predicate"])
+ assert rule.reward_type == RewardType.SUBTOTAL_DISCOUNT
+
+ manual_reward = Decimal(10)
+ create_manual_order_discount(
+ order=order,
+ reason="Manual discount",
+ value_type=DiscountValueType.FIXED,
+ value=manual_reward,
+ )
+
+ subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward
+ shipping_manual_reward_portion = manual_reward - subtotal_manual_reward_portion
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve({})
+
+ # when
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)
+ assert manual_discount.amount_value == manual_reward
+ assert not order.discounts.filter(type=DiscountType.ORDER_PROMOTION).first()
+
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": subtotal_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ },
+ {
+ "amount": {"amount": shipping_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SHIPPING,
+ },
+ ],
+ "channel": {"id": to_global_id_or_none(channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
+ "unitPrice": {"amount": line_1_unit_price},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
+ "unitPrice": {"amount": line_2_unit_price},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": shipping_price_amount},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_fixed(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ voucher_free_shipping,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ voucher = voucher_free_shipping
+ webhook = subscription_order_calculate_taxes
+ channel = order.channel
+ shipping_price_amount = order.base_shipping_price_amount
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+
+ assert voucher.type == VoucherType.SHIPPING
+ order.voucher = voucher
+ order.save(update_fields=["voucher_id"])
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ manual_reward = Decimal(10)
+ create_manual_order_discount(
+ order=order,
+ reason="Manual discount",
+ value_type=DiscountValueType.FIXED,
+ value=manual_reward,
+ )
+
+ # Since shipping is free, whole manual discount should be applied to subtotal
+ subtotal_manual_reward_portion = manual_reward
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve({})
+
+ # when
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)
+ assert manual_discount.amount_value == subtotal_manual_reward_portion
+ voucher_discount = order.discounts.get(type=DiscountType.VOUCHER)
+ assert voucher_discount.amount_value == shipping_price_amount
+
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": subtotal_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ },
+ ],
+ "channel": {"id": to_global_id_or_none(channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
+ "unitPrice": {"amount": line_1_unit_price},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
+ "unitPrice": {"amount": line_2_unit_price},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": 0},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
+
+
+@patch("saleor.tax.webhooks.shared.trigger_webhook_sync_promise")
+def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_percentage(
+ mocked_trigger_webhook_sync_promise,
+ order_with_lines,
+ voucher_free_shipping,
+ subscription_order_calculate_taxes,
+ tax_configuration_tax_app,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ voucher = voucher_free_shipping
+ webhook = subscription_order_calculate_taxes
+ channel = order.channel
+ shipping_price_amount = order.base_shipping_price_amount
+
+ line_1, line_2 = order.lines.all()
+ line_1_unit_price = line_1.base_unit_price_amount
+ line_2_unit_price = line_2.base_unit_price_amount
+
+ subtotal_amount = (
+ line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
+ )
+ total_amount = subtotal_amount + shipping_price_amount
+
+ assert voucher.type == VoucherType.SHIPPING
+ order.voucher = voucher
+ order.save(update_fields=["voucher_id"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ total_amount -= shipping_price_amount
+
+ manual_reward = Decimal(10)
+ create_manual_order_discount(
+ order=order,
+ reason="Manual discount",
+ value_type=DiscountValueType.PERCENTAGE,
+ value=manual_reward,
+ )
+
+ # Since shipping is free, whole manual discount should be applied to subtotal
+ subtotal_manual_reward_portion = manual_reward / 100 * total_amount
+
+ mocked_trigger_webhook_sync_promise.return_value = Promise.resolve({})
+
+ # when
+ fetch_order_prices_if_expired(order, plugins_manager, None, None, True).get()
+ deliveries = create_delivery_for_subscription_sync_event(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
+ )
+
+ # then
+ manual_discount = order.discounts.get(type=DiscountType.MANUAL)
+ assert manual_discount.amount_value == subtotal_manual_reward_portion
+ voucher_discount = order.discounts.get(type=DiscountType.VOUCHER)
+ assert voucher_discount.amount_value == shipping_price_amount
+
+ assert json.loads(deliveries.payload.get_payload()) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [
+ {
+ "amount": {"amount": subtotal_manual_reward_portion},
+ "type": TaxableObjectDiscountType.SUBTOTAL,
+ },
+ ],
+ "channel": {"id": to_global_id_or_none(channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": line_1.product_name,
+ "productSku": line_1.product_sku,
+ "quantity": line_1.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_1),
+ },
+ "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
+ "unitPrice": {"amount": line_1_unit_price},
+ "variantName": line_1.variant_name,
+ },
+ {
+ "chargeTaxes": True,
+ "productName": line_2.product_name,
+ "productSku": line_2.product_sku,
+ "quantity": line_2.quantity,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(line_2),
+ },
+ "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
+ "unitPrice": {"amount": line_2_unit_price},
+ "variantName": line_2.variant_name,
+ },
+ ],
+ "pricesEnteredWithTax": False,
+ "shippingPrice": {"amount": 0},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ "metadata": [
+ {"key": key, "value": value}
+ for key, value in order.metadata.items()
+ ],
+ "privateMetadata": [
+ {"key": key, "value": value}
+ for key, value in order.private_metadata.items()
+ ],
+ "user": {"id": to_global_id_or_none(order.user)},
+ },
+ },
+ }
diff --git a/saleor/order/tests/webhooks/test_exclude_shipping.py b/saleor/order/tests/webhooks/test_exclude_shipping.py
index 80790cadee..bdb6fcbe56 100644
--- a/saleor/order/tests/webhooks/test_exclude_shipping.py
+++ b/saleor/order/tests/webhooks/test_exclude_shipping.py
@@ -156,9 +156,9 @@ def test_excluded_shipping_methods_for_order(
mocked_webhook.assert_called_once_with(
WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
- payload,
shipping_webhook,
False,
+ static_payload=payload,
subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
@@ -265,9 +265,9 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
event_type = WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS
mocked_webhook.assert_any_call(
event_type,
- payload,
shipping_webhook,
False,
+ static_payload=payload,
subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
@@ -275,9 +275,9 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
)
mocked_webhook.assert_any_call(
event_type,
- payload,
second_shipping_webhook,
False,
+ static_payload=payload,
subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
@@ -396,9 +396,9 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
mocked_webhook.assert_any_call(
event_type,
- payload,
first_webhook,
False,
+ static_payload=payload,
subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
@@ -406,9 +406,9 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
)
mocked_webhook.assert_any_call(
event_type,
- payload,
second_webhook,
False,
+ static_payload=payload,
subscribable_object=(order_with_lines, available_shipping_methods),
timeout=settings.WEBHOOK_SYNC_TIMEOUT,
request=None,
diff --git a/saleor/order/tests/webhooks/test_order_calculate_taxes.py b/saleor/order/tests/webhooks/test_order_calculate_taxes.py
new file mode 100644
index 0000000000..c02b62b66e
--- /dev/null
+++ b/saleor/order/tests/webhooks/test_order_calculate_taxes.py
@@ -0,0 +1,248 @@
+import json
+from unittest.mock import ANY, patch
+
+import pytest
+from freezegun import freeze_time
+
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery
+from ....core.taxes import TaxDataError
+from ....graphql.webhook.subscription_payload import (
+ generate_payload_promise_from_subscription,
+)
+from ....tax.webhooks.parser import parse_tax_data
+from ....webhook.event_types import WebhookEventSyncType
+from ...webhooks.order_calculate_taxes import (
+ generate_order_payload_for_tax_calculation,
+ get_taxes,
+)
+
+
+@freeze_time()
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order(
+ mock_request,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ mock_request.return_value = tax_data_response
+
+ app_identifier = None
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = None
+ webhook.save(update_fields=["subscription_query"])
+
+ # when
+ tax_data = get_taxes(
+ order=order,
+ lines=order.lines.all(),
+ app_identifier=app_identifier,
+ requestor=None,
+ ).get()
+
+ # then
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == generate_order_payload_for_tax_calculation(
+ order
+ )
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ tax_data_response,
+ order.lines.count(),
+ )
+
+
+@freeze_time()
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order_with_sync_subscription(
+ mock_request,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ mock_request.return_value = tax_data_response
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = (
+ "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ )
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = None
+
+ # when
+ tax_data = get_taxes(
+ order=order,
+ lines=order.lines.all(),
+ app_identifier=app_identifier,
+ requestor=None,
+ ).get()
+
+ # then
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == json.dumps(
+ {"taxBase": {"currency": "USD"}}
+ )
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ tax_data_response,
+ order.lines.count(),
+ )
+
+
+def test_get_taxes_for_order_with_app_identifier_app_missing(order):
+ # given
+ app_identifier = "missing_app"
+
+ # when & then
+ with pytest.raises(TaxDataError, match="Configured tax app doesn't exist."):
+ get_taxes(order, order.lines.all(), app_identifier, None).get()
+
+
+def test_get_taxes_for_order_with_app_identifier_webhook_is_missing(order, app):
+ with pytest.raises(
+ TaxDataError,
+ match="Configured tax app's webhook for taxes calculation doesn't exists.",
+ ):
+ get_taxes(order, order.lines.all(), app.identifier, None).get()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order_with_app_identifier_invalid_response(
+ mock_request,
+ order,
+ tax_app,
+ tax_data_response_factory,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ mock_request.return_value = tax_data_response_factory(shipping_tax_rate=-10)
+
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ get_taxes(order, order.lines.all(), app_identifier, None).get()
+
+
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order_with_app_identifier_empty_response(
+ mock_request,
+ order,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ mock_request.return_value = None
+
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when & then
+ with pytest.raises(TaxDataError):
+ get_taxes(order, order.lines.all(), app_identifier, None).get()
+
+
+@freeze_time()
+@patch(
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription",
+ wraps=generate_payload_promise_from_subscription,
+)
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order_with_app_identifier(
+ mock_request,
+ mock_generate_payload,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ mock_request.return_value = tax_data_response
+
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when
+ tax_data = get_taxes(order, order.lines.all(), app_identifier, None).get()
+
+ # then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ subscribable_object=order,
+ subscription_query=subscription_query,
+ request=ANY,
+ )
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == json.dumps(expected_payload)
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ tax_data_response,
+ order.lines.count(),
+ )
+
+
+@freeze_time()
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_order_sets_issuing_principal(
+ mock_request, tax_data_response, order, tax_app, customer_user
+):
+ # given
+ mock_request.return_value = tax_data_response
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = "subscription{event{issuingPrincipal {__typename}}}"
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = tax_app.identifier
+
+ # when
+ tax_data = get_taxes(
+ order=order,
+ lines=order.lines.all(),
+ app_identifier=app_identifier,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ mock_request.assert_called_once()
+ assert not EventDelivery.objects.exists()
+
+ delivery = mock_request.mock_calls[0].args[0]
+ assert delivery.payload.get_payload() == json.dumps(
+ {"issuingPrincipal": {"__typename": "User"}}
+ )
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ tax_data_response,
+ order.lines.count(),
+ )
diff --git a/saleor/order/webhooks/exclude_shipping.py b/saleor/order/webhooks/exclude_shipping.py
index 05b4f8a188..0e4478427a 100644
--- a/saleor/order/webhooks/exclude_shipping.py
+++ b/saleor/order/webhooks/exclude_shipping.py
@@ -1,7 +1,6 @@
import json
import logging
from collections import defaultdict
-from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Union
@@ -72,14 +71,12 @@ def excluded_shipping_methods_for_order(
if not available_shipping_methods:
return Promise.resolve([])
- generate_function = generate_excluded_shipping_methods_for_order_payload
- payload_fun = lambda: generate_function( # noqa: E731
- order,
- available_shipping_methods,
- )
return _get_excluded_shipping_data(
event_type=WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS,
- payload_fun=payload_fun,
+ static_payload=generate_excluded_shipping_methods_for_order_payload(
+ order,
+ available_shipping_methods,
+ ),
subscribable_object=(order, available_shipping_methods),
allow_replica=allow_replica,
requestor=requestor,
@@ -100,7 +97,7 @@ def _get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:
def _get_excluded_shipping_methods_or_fetch(
webhooks: QuerySet,
event_type: str,
- payload: str,
+ static_payload: str,
subscribable_object: (
tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None
),
@@ -112,7 +109,7 @@ def _get_excluded_shipping_methods_or_fetch(
The data will be fetched from the cache. If missing it will fetch it from all
defined webhooks by calling a request to each of them one by one.
"""
- cache_data = _get_cache_data_for_exclude_shipping_methods(payload)
+ cache_data = _get_cache_data_for_exclude_shipping_methods(static_payload)
# Gather responses from webhooks
promised_responses = []
@@ -120,7 +117,7 @@ def _get_excluded_shipping_methods_or_fetch(
promised_responses.append(
trigger_webhook_sync_promise_if_not_cached(
event_type=event_type,
- payload=payload,
+ static_payload=static_payload,
webhook=webhook,
cache_data=cache_data,
allow_replica=allow_replica,
@@ -147,7 +144,7 @@ def _get_excluded_shipping_methods_or_fetch(
def _get_excluded_shipping_data(
event_type: str,
- payload_fun: Callable[[], str],
+ static_payload: str,
subscribable_object: (
tuple[Union["Order", "Checkout"], list["ShippingMethodData"]] | None
),
@@ -167,11 +164,10 @@ def _get_excluded_shipping_data(
"""
webhooks = get_webhooks_for_event(event_type)
if webhooks:
- payload = payload_fun()
promised_excluded_methods_map = _get_excluded_shipping_methods_or_fetch(
webhooks,
event_type,
- payload,
+ static_payload,
subscribable_object,
allow_replica,
requestor,
diff --git a/saleor/order/webhooks/order_calculate_taxes.py b/saleor/order/webhooks/order_calculate_taxes.py
new file mode 100644
index 0000000000..44d3d52c2a
--- /dev/null
+++ b/saleor/order/webhooks/order_calculate_taxes.py
@@ -0,0 +1,154 @@
+import json
+import logging
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Union
+
+import graphene
+from django.db.models import QuerySet
+from promise import Promise
+
+from ...app.models import App
+from ...core.db.connection import allow_writer
+from ...core.prices import quantize_price, quantize_price_fields
+from ...core.taxes import TaxData
+from ...discount.utils.shared import is_order_level_discount
+from ...tax.utils import get_charge_taxes_for_order
+from ...tax.webhooks import shared
+from ...webhook import traced_payload_generator
+from ...webhook.event_types import WebhookEventSyncType
+from ...webhook.payload_serializers import PayloadSerializer
+from ..models import Order, OrderLine
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...app.models import App
+
+
+logger = logging.getLogger(__name__)
+
+
+def _generate_order_lines_payload_for_tax_calculation(lines: QuerySet[OrderLine]):
+ serializer = PayloadSerializer()
+
+ charge_taxes = False
+ if lines:
+ charge_taxes = get_charge_taxes_for_order(lines[0].order)
+
+ return serializer.serialize(
+ lines,
+ fields=("product_name", "variant_name", "quantity"),
+ extra_dict_data={
+ "variant_id": (lambda line: line.product_variant_id),
+ "full_name": (
+ lambda line: line.variant.display_product() if line.variant else None
+ ),
+ "product_metadata": (
+ lambda line: line.variant.product.metadata if line.variant else {}
+ ),
+ "product_type_metadata": (
+ lambda line: (
+ line.variant.product.product_type.metadata if line.variant else {}
+ )
+ ),
+ "charge_taxes": (lambda _line: charge_taxes),
+ "sku": (lambda line: line.product_sku),
+ "unit_amount": (
+ lambda line: quantize_price(line.base_unit_price_amount, line.currency)
+ ),
+ "total_amount": (
+ lambda line: quantize_price(
+ line.base_unit_price_amount * line.quantity, line.currency
+ )
+ ),
+ },
+ )
+
+
+@allow_writer()
+@traced_payload_generator
+def generate_order_payload_for_tax_calculation(order: "Order"):
+ serializer = PayloadSerializer()
+
+ tax_configuration = order.channel.tax_configuration
+ prices_entered_with_tax = tax_configuration.prices_entered_with_tax
+
+ # Prepare Order data
+ address = order.shipping_address or order.billing_address
+ lines = order.lines.all()
+
+ # Prepare user data
+ user = order.user
+ user_id = None
+ user_public_metadata = {}
+ if user:
+ user_id = graphene.Node.to_global_id("User", user.id)
+ user_public_metadata = user.metadata
+
+ # Prepare discount data
+ discounts = order.discounts.all()
+ discounts_dict = []
+ for discount in discounts:
+ # Only order level discounts, like entire order vouchers,
+ # order promotions and manual discounts should be taken into account
+ if not is_order_level_discount(discount):
+ continue
+ quantize_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})
+
+ # Prepare shipping data
+ shipping_method_name = order.shipping_method_name
+ shipping_method_amount = quantize_price(
+ order.base_shipping_price_amount, order.currency
+ )
+
+ address_fields = (
+ "first_name",
+ "last_name",
+ "company_name",
+ "street_address_1",
+ "street_address_2",
+ "city",
+ "city_area",
+ "postal_code",
+ "country",
+ "country_area",
+ "phone",
+ )
+ order_data = serializer.serialize(
+ [order],
+ fields=["currency", "metadata"],
+ additional_fields={
+ "channel": (lambda o: o.channel, ("slug", "currency_code")),
+ "address": (lambda o: address, address_fields),
+ },
+ extra_dict_data={
+ "id": graphene.Node.to_global_id("Order", order.id),
+ "user_id": user_id,
+ "user_public_metadata": user_public_metadata,
+ "discounts": discounts_dict,
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "shipping_amount": shipping_method_amount,
+ "shipping_name": shipping_method_name,
+ "lines": json.loads(
+ _generate_order_lines_payload_for_tax_calculation(lines)
+ ),
+ },
+ )
+ return order_data
+
+
+def get_taxes(
+ order: Order,
+ lines: Iterable["OrderLine"],
+ app_identifier: str | None,
+ requestor: Union["App", "User", None],
+) -> Promise[TaxData | None]:
+ return shared.get_taxes(
+ taxable_object=order,
+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ app_identifier=app_identifier,
+ static_payload=generate_order_payload_for_tax_calculation(order),
+ lines_count=len(list(lines)),
+ requestor=requestor,
+ )
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 49067c2334..74853c98eb 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -734,10 +734,6 @@ class BasePlugin:
Optional["TaxData"],
]
- # Note: This method is deprecated and will be removed in a future release.
- # Webhook-related functionality will be moved from the plugin to core modules.
- get_taxes_for_order: Callable[["Order", str, Any], Optional["TaxData"]]
-
get_client_token: Callable[[Any, Any], Any]
get_order_line_tax_rate: Callable[
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 509ce32a64..19f74ed366 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -650,16 +650,6 @@ class PluginsManager(PaymentInterface):
channel_slug=checkout_info.channel.slug,
)
- # Note: this method is deprecated and will be removed in a future release.
- # Webhook-related functionality will be moved from plugin to core modules.
- def get_taxes_for_order(self, order: "Order", app_identifier) -> TaxData | None:
- return self.__run_tax_method_until_first_success(
- "get_taxes_for_order",
- order,
- app_identifier,
- channel_slug=order.channel.slug,
- )
-
def __run_tax_method_until_first_success(
self,
method_name: str,
diff --git a/saleor/plugins/tests/test_manager_get_taxes.py b/saleor/plugins/tests/test_manager_get_taxes.py
index 83f07cc712..f3e63d3f1f 100644
--- a/saleor/plugins/tests/test_manager_get_taxes.py
+++ b/saleor/plugins/tests/test_manager_get_taxes.py
@@ -118,93 +118,3 @@ def test_manager_get_taxes_for_checkout_multiple_plugins(
# then
assert tax_data == sample_tax_data(checkout)
-
-
- ("plugins", "expected_tax_data"),
- [
- ([], sample_none_data),
- (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
- ],
-)
-def test_manager_get_taxes_for_order(
- order,
- plugins,
- expected_tax_data,
-):
- # given
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins=plugins).get_taxes_for_order(
- order, app_identifier
- )
-
- # then
- assert tax_data == expected_tax_data(order)
-
-
-@patch(
- "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_order",
- side_effect=TaxDataError("test error"),
-)
-def test_manager_get_taxes_for_order_raises_error(
- mocked_get_taxes_for_order,
- order,
-):
- # given
- app_identifier = None
- plugins = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- # when & then
- with pytest.raises(TaxDataError):
- PluginsManager(plugins=plugins).get_taxes_for_order(order, app_identifier)
-
- mocked_get_taxes_for_order.assert_called_once()
-
-
-def test_manager_get_taxes_for_order_raises_no_active_plugin(
- order,
-):
- # given
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins=[]).get_taxes_for_order(order, app_identifier)
-
- # then
- assert tax_data is None
-
-
- "plugins",
- [
- # first plugin that raises an error
- [
- "saleor.plugins.webhook.plugin.WebhookPlugin",
- "saleor.plugins.tests.sample_plugins.PluginSample",
- ],
- # as a second plugin that raises an error
- [
- "saleor.plugins.tests.sample_plugins.PluginSample",
- "saleor.plugins.webhook.plugin.WebhookPlugin",
- ],
- ],
-)
-@patch(
- "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_order",
- side_effect=TaxDataError("test error"),
-)
-def test_manager_get_taxes_for_order_multiple_plugins(
- mocked_get_taxes_for_order,
- plugins,
- order,
-):
- # given
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins).get_taxes_for_order(order, app_identifier)
-
- # then
- assert tax_data == sample_tax_data(order)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 31ed1c3348..d642d9deb9 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -17,11 +17,10 @@ from ...checkout.models import Checkout
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ...core.notify import NotifyEventType
-from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxType
+from ...core.taxes import TaxData, TaxDataError, TaxType
from ...core.telemetry import get_task_context
from ...core.utils import build_absolute_uri, get_domain
from ...core.utils.json_serializer import CustomJsonEncoder
-from ...core.utils.text import safe_truncate
from ...csv.notifications import get_default_export_payload
from ...graphql.core.context import SaleorContext
from ...graphql.webhook.subscription_payload import (
@@ -61,6 +60,7 @@ from ...payment.utils import (
recalculate_refundable_for_checkout,
)
from ...settings import WEBHOOK_SYNC_TIMEOUT
+from ...tax.webhooks.parser import parse_tax_data
from ...thumbnail.models import Thumbnail
from ...webhook.const import WEBHOOK_CACHE_DEFAULT_TTL
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -76,7 +76,6 @@ from ...webhook.payloads import (
generate_meta,
generate_metadata_updated_payload,
generate_order_payload,
- generate_order_payload_for_tax_calculation,
generate_page_payload,
generate_payment_payload,
generate_product_deleted_payload,
@@ -94,7 +93,6 @@ from ...webhook.payloads import (
from ...webhook.response_schemas.transaction import (
PaymentGatewayInitializeSessionSchema,
)
-from ...webhook.response_schemas.utils.helpers import parse_validation_error
from ...webhook.transport.asynchronous.transport import (
WebhookPayloadData,
get_queue_name_for_webhook,
@@ -125,12 +123,6 @@ from ...webhook.transport.synchronous.transport import (
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
)
-from ...webhook.transport.taxes import (
- DEFAULT_TAX_CODE,
- DEFAULT_TAX_DESCRIPTION,
- get_current_tax_app,
- parse_tax_data,
-)
from ...webhook.transport.utils import (
delivery_update,
from_payment_app_id,
@@ -3563,19 +3555,7 @@ class WebhookPlugin(BasePlugin):
requestor=self.requestor,
pregenerated_subscription_payload=pregenerated_subscription_payload,
)
- try:
- tax_data = parse_tax_data(response, expected_lines_count)
- except ValidationError as e:
- errors = e.errors()
- logger.warning(
- "Webhook response for event %s is invalid: %s",
- event_type,
- str(e),
- extra={"errors": errors},
- )
- error_msg = safe_truncate(parse_validation_error(e), TAX_ERROR_FIELD_LENGTH)
- raise TaxDataError(error_msg, errors=errors) from e
- return tax_data
+ return parse_tax_data(event_type, response, expected_lines_count)
def get_taxes_for_checkout(
self,
@@ -3615,30 +3595,6 @@ class WebhookPlugin(BasePlugin):
pregenerated_subscription_payloads=pregenerated_subscription_payloads,
)
- def get_taxes_for_order(
- self, order: "Order", app_identifier, previous_value
- ) -> TaxData | None:
- event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
- lines_count = order.lines.count()
- if app_identifier:
- return self.__run_tax_webhook(
- event_type,
- app_identifier,
- lambda: generate_order_payload_for_tax_calculation(order),
- lines_count,
- order,
- )
- # This is deprecated flow, kept to maintain backward compatibility.
- # In Saleor 4.0 `tax_app_identifier` should be required and the flow should
- # be dropped.
- return trigger_taxes_all_webhooks_sync(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- lambda: generate_order_payload_for_tax_calculation(order),
- lines_count,
- order,
- self.requestor,
- )
-
def get_shipping_methods_for_checkout(
self,
checkout: "Checkout",
@@ -3682,14 +3638,21 @@ class WebhookPlugin(BasePlugin):
If there is no tax code defined for the product/product type,
then return dummy values.
"""
- if not (tax_app := get_current_tax_app()):
+ tax_app = (
+ App.objects.order_by("pk")
+ .filter(removed_at__isnull=True)
+ .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+ .last()
+ )
+ if not tax_app:
return previous_value
meta_code_key = get_meta_code_key(tax_app)
meta_description_key = get_meta_description_key(tax_app)
- default_tax_code = DEFAULT_TAX_CODE
- default_tax_description = DEFAULT_TAX_DESCRIPTION
+ default_tax_code = "UNMAPPED"
+ default_tax_description = "Unmapped Product/Product Type"
code = obj.get_value_from_metadata(meta_code_key, default_tax_code)
description = obj.get_value_from_metadata(
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index e7d7227e75..4a34bb9425 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -10,13 +10,8 @@ from ....core import EventDeliveryStatus
from ....core.models import EventDelivery
from ....core.taxes import TaxDataError, TaxType
from ....graphql.webhook.utils import get_subscription_query_hash
+from ....tax.webhooks.parser import parse_tax_data
from ....webhook.event_types import WebhookEventSyncType
-from ....webhook.payloads import generate_order_payload_for_tax_calculation
-from ....webhook.transport.taxes import (
- DEFAULT_TAX_CODE,
- DEFAULT_TAX_DESCRIPTION,
- parse_tax_data,
-)
from ...manager import get_plugins_manager
@@ -42,62 +37,6 @@ def test_get_taxes_for_checkout_no_permission(
assert tax_data is None
-@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_taxes_for_order(
- mock_request,
- mock_fetch,
- permission_handle_taxes,
- webhook_plugin,
- tax_data_response,
- order,
- tax_app,
-):
- # given
- mock_request.return_value = tax_data_response
- plugin = webhook_plugin()
- app_identifier = None
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = None
- webhook.save(update_fields=["subscription_query"])
-
- # when
- tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
-
- # then
- mock_request.assert_called_once()
- assert not EventDelivery.objects.exists()
-
- delivery = mock_request.mock_calls[0].args[0]
- assert delivery.payload.get_payload() == generate_order_payload_for_tax_calculation(
- order
- )
- assert delivery.status == EventDeliveryStatus.PENDING
- assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_taxes_for_order_no_permission(
- mock_request,
- webhook_plugin,
- order,
-):
- # given
- plugin = webhook_plugin()
- app_identifier = None
-
- # when
- tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
-
- # then
- assert mock_request.call_count == 0
- assert tax_data is None
-
-
@pytest.fixture
def tax_type():
return TaxType(
@@ -154,48 +93,9 @@ def test_get_tax_code_from_object_meta_default_code(
# then
assert fetched_tax_type == TaxType(
- code=DEFAULT_TAX_CODE,
- description=DEFAULT_TAX_DESCRIPTION,
- )
-
-
-@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_taxes_for_order_with_sync_subscription(
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- order,
- tax_app,
-):
- # given
- mock_request.return_value = tax_data_response
- plugin = webhook_plugin()
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = (
- "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ code="UNMAPPED",
+ description="Unmapped Product/Product Type",
)
- webhook.save(update_fields=["subscription_query"])
- app_identifier = None
-
- # when
- tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
-
- # then
- mock_request.assert_called_once()
- assert not EventDelivery.objects.exists()
-
- delivery = mock_request.mock_calls[0].args[0]
- assert delivery.payload.get_payload() == json.dumps(
- {"taxBase": {"currency": "USD"}}
- )
- assert delivery.status == EventDeliveryStatus.PENDING
- assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
@freeze_time()
@@ -246,7 +146,11 @@ def test_get_taxes_for_checkout_with_sync_subscription(
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ tax_data_response,
+ checkout.lines.count(),
+ )
@freeze_time()
@@ -301,7 +205,11 @@ def test_get_taxes_for_checkout_with_sync_subscription_with_pregenerated_payload
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ tax_data_response,
+ checkout.lines.count(),
+ )
def test_get_taxes_for_checkout_with_app_identifier_app_missing(
@@ -416,141 +324,11 @@ def test_get_taxes_for_checkout_with_app_identifier(
assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
assert delivery.webhook == webhook
mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, checkout.lines.count())
-
-
-def test_get_taxes_for_order_with_app_identifier_app_missing(order, webhook_plugin):
- # given
- app_identifier = "missing_app"
- plugin = webhook_plugin()
-
- # when & then
- with pytest.raises(TaxDataError, match="Configured tax app doesn't exist."):
- plugin.get_taxes_for_order(order, app_identifier, None)
-
-
-def test_get_taxes_for_order_with_app_identifier_webhook_is_missing(
- order, webhook_plugin, app
-):
- # given
- plugin = webhook_plugin()
-
- # when & then
- with pytest.raises(
- TaxDataError,
- match="Configured tax app's webhook for taxes calculation doesn't exists.",
- ):
- plugin.get_taxes_for_order(order, app.identifier, None)
-
-
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_get_taxes_for_order_with_app_identifier_invalid_response(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response_factory,
- order,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- # mock returning invalid data - tax_rate with negative value
- mock_request.return_value = tax_data_response_factory(shipping_tax_rate=-10)
- mock_generate_payload.return_value = expected_payload
- plugin = webhook_plugin()
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = subscription_query
- webhook.save(update_fields=["subscription_query"])
- app_identifier = tax_app.identifier
-
- # when & then
- with pytest.raises(TaxDataError):
- plugin.get_taxes_for_order(order, app_identifier, None)
-
-
-@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_get_taxes_for_order_with_app_identifier(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- order,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- mock_request.return_value = tax_data_response
- mock_generate_payload.return_value = expected_payload
- plugin = webhook_plugin()
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = subscription_query
- webhook.save(update_fields=["subscription_query"])
- app_identifier = tax_app.identifier
-
- # when
- tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
-
- # then
- mock_generate_payload.assert_called_once_with(
- event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- subscribable_object=order,
- subscription_query=subscription_query,
- request=ANY, # SaleorContext,
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ tax_data_response,
+ checkout.lines.count(),
)
- mock_request.assert_called_once()
- assert not EventDelivery.objects.exists()
-
- delivery = mock_request.mock_calls[0].args[0]
- assert delivery.payload.get_payload() == json.dumps(expected_payload)
- assert delivery.status == EventDeliveryStatus.PENDING
- assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(tax_data_response, order.lines.count())
-
-
-@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_get_taxes_for_order_with_app_identifier_empty_response(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- order,
- tax_app,
-):
- # given
- mock_request.return_value = None
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- mock_generate_payload.return_value = expected_payload
- plugin = webhook_plugin()
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = subscription_query
- webhook.save(update_fields=["subscription_query"])
- app_identifier = tax_app.identifier
-
- # when & then
- with pytest.raises(TaxDataError):
- plugin.get_taxes_for_order(order, app_identifier, None)
@freeze_time()
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index dbeeb59bf7..50262679e3 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -2465,25 +2465,20 @@ def test_is_event_active(settings, webhook, permission_manage_orders):
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.get_webhooks_for_event")
@mock.patch(
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
)
def test_trigger_webhook_sync_with_subscription_within_mutation_use_default_db(
mocked_generate_payload,
- mocked_get_webhooks_for_event,
mocked_request,
draft_order,
app_api_client,
permission_manage_orders,
settings,
- subscription_calculate_taxes_for_order,
+ tax_configuration_tax_app,
+ tax_app,
):
# given
- webhook = subscription_calculate_taxes_for_order
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
- mocked_get_webhooks_for_event.return_value = [webhook]
-
order_discount = draft_order.discounts.create(
value_type=DiscountValueType.FIXED,
value=Decimal(10),
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index 8ecc0f47f8..c42d982ec7 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -887,7 +887,9 @@ def test_use_default_country_rate_when_no_tax_class_was_set_before(
order.refresh_from_db()
# when
- fetch_order_prices_if_expired(order, manager, force_update=True)
+ fetch_order_prices_if_expired(
+ order, manager, requestor=None, force_update=True
+ ).get()
order.refresh_from_db()
# then
diff --git a/saleor/tax/tests/webhooks/__init__.py b/saleor/tax/tests/webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/tests/test_tax_webhook_utils.py b/saleor/tax/tests/webhooks/test_parser.py
similarity index 59%
rename from saleor/webhook/tests/test_tax_webhook_utils.py
rename to saleor/tax/tests/webhooks/test_parser.py
index 5b4426ba8b..e0d1e69b7e 100644
--- a/saleor/webhook/tests/test_tax_webhook_utils.py
+++ b/saleor/tax/tests/webhooks/test_parser.py
@@ -1,10 +1,8 @@
import pytest
-from pydantic import ValidationError
-from ...core.taxes import TaxData
-from ..transport.taxes import (
- parse_tax_data,
-)
+from ....core.taxes import TaxData, TaxDataError
+from ....webhook.event_types import WebhookEventSyncType
+from ...webhooks.parser import parse_tax_data
def test_parse_tax_data_success(tax_data_response):
@@ -12,7 +10,9 @@ def test_parse_tax_data_success(tax_data_response):
line_count = len(tax_data_response["lines"])
# when
- tax_data = parse_tax_data(tax_data_response, line_count)
+ tax_data = parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES, tax_data_response, line_count
+ )
# then
assert isinstance(tax_data, TaxData)
@@ -25,8 +25,10 @@ def test_parse_tax_data_keyerror(tax_data_response):
line_count = len(tax_data_response["lines"])
# when & then
- with pytest.raises(ValidationError):
- parse_tax_data(tax_data_response, line_count)
+ with pytest.raises(TaxDataError):
+ parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES, tax_data_response, line_count
+ )
def test_parse_tax_data_decimalexception(tax_data_response):
@@ -35,8 +37,10 @@ def test_parse_tax_data_decimalexception(tax_data_response):
line_count = len(tax_data_response["lines"])
# when & then
- with pytest.raises(ValidationError):
- parse_tax_data(tax_data_response, line_count)
+ with pytest.raises(TaxDataError):
+ parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES, tax_data_response, line_count
+ )
@pytest.mark.parametrize(
@@ -57,5 +61,5 @@ def test_parse_tax_data_decimalexception(tax_data_response):
],
)
def test_parse_tax_data_malformed(response_data):
- with pytest.raises(ValidationError):
- parse_tax_data(response_data, 1)
+ with pytest.raises(TaxDataError):
+ parse_tax_data(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES, response_data, 1)
diff --git a/saleor/tax/tests/webhooks/test_shared.py b/saleor/tax/tests/webhooks/test_shared.py
new file mode 100644
index 0000000000..dd7c84c5b8
--- /dev/null
+++ b/saleor/tax/tests/webhooks/test_shared.py
@@ -0,0 +1,434 @@
+import json
+from unittest import mock
+
+import graphene
+import pytest
+
+from saleor.core.taxes import TaxDataError
+
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook, WebhookEvent
+
+# from ....webhook.transport.synchronous import trigger_taxes_all_webhooks_sync
+from ...webhooks.parser import parse_tax_data
+from ...webhooks.shared import (
+ get_taxes,
+ get_taxes_for_app_identifier,
+ get_taxes_from_all_webhooks,
+)
+
+TAX_SUBSCRIPTION_QUERY = """
+ subscription {
+ event {
+ ... on CalculateTaxes {
+ taxBase {
+ sourceObject {
+ ...on Order{
+ id
+ lines{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def tax_webhooks(tax_app):
+ webhooks = [
+ Webhook(
+ name=f"Tax order webhook no {i}",
+ app=tax_app,
+ target_url=f"https://127.0.0.1/tax-order-{i}",
+ )
+ for i in range(3)
+ ]
+ webhooks = Webhook.objects.bulk_create(webhooks)
+ WebhookEvent.objects.bulk_create(
+ WebhookEvent(
+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ webhook=webhook,
+ )
+ for webhook in webhooks
+ )
+ return webhooks
+
+
+ "saleor.tax.webhooks.shared.get_taxes_from_all_webhooks",
+ wraps=get_taxes_from_all_webhooks,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_from_all_webhooks(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_from_all_webhooks,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = None
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.return_value = tax_data_response
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ tax_data = get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=None,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ mocked_send_webhook_request_sync.assert_called_once()
+ mocked_get_taxes_from_all_webhooks.assert_called_once()
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
+
+
+ "saleor.tax.webhooks.shared.get_taxes_from_all_webhooks",
+ wraps=get_taxes_from_all_webhooks,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_from_all_webhooks_multiple_webhooks(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_from_all_webhooks,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+ tax_webhooks,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = None
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.side_effect = [None, {}, tax_data_response, None]
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ tax_data = get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=None,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ assert mocked_send_webhook_request_sync.call_count == 4
+ assert mocked_get_taxes_from_all_webhooks.call_count == 1
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
+
+
+ "saleor.tax.webhooks.shared.get_taxes_from_all_webhooks",
+ wraps=get_taxes_from_all_webhooks,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_from_all_webhooks_multiple_invalid_webhooks(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_from_all_webhooks,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+ tax_webhooks,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = None
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.side_effect = [None, {}, None, None]
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ tax_data = get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=None,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ assert mocked_send_webhook_request_sync.call_count == 4
+ assert mocked_get_taxes_from_all_webhooks.call_count == 1
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
+ assert tax_data is None
+
+
+ "saleor.tax.webhooks.shared.get_taxes_for_app_identifier",
+ wraps=get_taxes_for_app_identifier,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_app_identifier(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_for_app_identifier,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = tax_app.identifier
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.return_value = tax_data_response
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ tax_data = get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=tax_app.identifier,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ mocked_send_webhook_request_sync.assert_called_once()
+ mocked_get_taxes_for_app_identifier.assert_called_once()
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
+
+
+ "saleor.tax.webhooks.shared.get_taxes_for_app_identifier",
+ wraps=get_taxes_for_app_identifier,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_app_identifier_multiple_webhooks(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_for_app_identifier,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+ tax_webhooks,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = tax_app.identifier
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.return_value = tax_data_response
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ tax_data = get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=tax_app.identifier,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ mocked_send_webhook_request_sync.assert_called_once()
+ mocked_get_taxes_for_app_identifier.assert_called_once()
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
+
+
+ "saleor.tax.webhooks.shared.get_taxes_for_app_identifier",
+ wraps=get_taxes_for_app_identifier,
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_for_app_identifier_invalid_response(
+ mocked_send_webhook_request_sync,
+ mocked_get_taxes_for_app_identifier,
+ tax_app,
+ tax_data_response,
+ tax_configuration_tax_app,
+ order_with_lines,
+ customer_user,
+ tax_webhooks,
+):
+ # given
+ tax_configuration_tax_app.tax_app_id = None
+ tax_configuration_tax_app.save(update_fields=["tax_app_id"])
+
+ mocked_send_webhook_request_sync.return_value = None
+
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ data = '{"key": "value"}'
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = TAX_SUBSCRIPTION_QUERY
+ webhook.save(update_fields=["subscription_query"])
+ lines_count = len(tax_data_response["lines"])
+
+ # when
+ with pytest.raises(TaxDataError):
+ get_taxes(
+ taxable_object=order_with_lines,
+ event_type=event_type,
+ app_identifier=tax_app.identifier,
+ static_payload=data,
+ lines_count=lines_count,
+ requestor=customer_user,
+ ).get()
+
+ # then
+ assert mocked_send_webhook_request_sync.call_count == 1
+ assert mocked_get_taxes_for_app_identifier.call_count == 1
+
+ assert not EventDelivery.objects.exists()
+ delivery = mocked_send_webhook_request_sync.mock_calls[0].args[0]
+
+ assert json.loads(delivery.payload.get_payload()) == {
+ "taxBase": {
+ "sourceObject": {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "lines": [
+ {"id": graphene.Node.to_global_id("OrderLine", line.pk)}
+ for line in order_with_lines.lines.all()
+ ],
+ }
+ }
+ }
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.webhook == webhook
diff --git a/saleor/tax/webhooks/__init__.py b/saleor/tax/webhooks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/tax/webhooks/parser.py b/saleor/tax/webhooks/parser.py
new file mode 100644
index 0000000000..98f134e3d0
--- /dev/null
+++ b/saleor/tax/webhooks/parser.py
@@ -0,0 +1,52 @@
+import logging
+from typing import Any
+
+from pydantic import ValidationError
+
+from ...core.taxes import TAX_ERROR_FIELD_LENGTH, TaxData, TaxDataError, TaxLineData
+from ...core.utils.text import safe_truncate
+from ...webhook.response_schemas.taxes import CalculateTaxesSchema
+from ...webhook.response_schemas.utils.helpers import parse_validation_error
+
+logger = logging.getLogger(__name__)
+
+
+def parse_tax_data(
+ event_type: str, response_data: Any, expected_lines_count: int
+) -> TaxData:
+ try:
+ tax_data = _parse_tax_data(response_data, expected_lines_count)
+ except ValidationError as e:
+ errors = e.errors()
+ logger.warning(
+ "Webhook response for event %s is invalid: %s",
+ event_type,
+ str(e),
+ extra={"errors": errors},
+ )
+ error_msg = safe_truncate(parse_validation_error(e), TAX_ERROR_FIELD_LENGTH)
+ raise TaxDataError(error_msg, errors=errors) from e
+ return tax_data
+
+
+def _parse_tax_data(
+ response_data: Any,
+ lines_count: int,
+) -> TaxData:
+ calculated_taxes_model = CalculateTaxesSchema.model_validate(
+ response_data,
+ context={"expected_line_count": lines_count},
+ )
+ return TaxData(
+ shipping_price_gross_amount=calculated_taxes_model.shipping_price_gross_amount,
+ shipping_price_net_amount=calculated_taxes_model.shipping_price_net_amount,
+ shipping_tax_rate=calculated_taxes_model.shipping_tax_rate,
+ lines=[
+ TaxLineData(
+ tax_rate=tax_line.tax_rate,
+ total_gross_amount=tax_line.total_gross_amount,
+ total_net_amount=tax_line.total_net_amount,
+ )
+ for tax_line in calculated_taxes_model.lines
+ ],
+ )
diff --git a/saleor/tax/webhooks/shared.py b/saleor/tax/webhooks/shared.py
new file mode 100644
index 0000000000..dfe6899afc
--- /dev/null
+++ b/saleor/tax/webhooks/shared.py
@@ -0,0 +1,139 @@
+import logging
+from typing import TYPE_CHECKING, Any, Union
+
+from django.conf import settings
+from promise import Promise
+
+from ...app.models import App
+from ...core.taxes import TaxData, TaxDataError
+from ...webhook.transport.synchronous.transport import (
+ trigger_webhook_sync_promise,
+)
+from ...webhook.utils import get_webhooks_for_event
+from .parser import parse_tax_data
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...app.models import App
+ from ...checkout.models import Checkout
+ from ...order.models import Order
+
+logger = logging.getLogger(__name__)
+
+
+def get_taxes(
+ taxable_object: Union["Checkout", "Order"],
+ event_type: str,
+ app_identifier: str | None,
+ static_payload: str,
+ lines_count: int,
+ requestor: Union["App", "User", None],
+) -> Promise[TaxData | None]:
+ if app_identifier:
+ return get_taxes_for_app_identifier(
+ event_type=event_type,
+ app_identifier=app_identifier,
+ expected_lines_count=lines_count,
+ subscribable_object=taxable_object,
+ requestor=requestor,
+ static_payload=static_payload,
+ )
+ return get_taxes_from_all_webhooks(
+ event_type=event_type,
+ expected_lines_count=lines_count,
+ static_payload=static_payload,
+ subscribable_object=taxable_object,
+ requestor=requestor,
+ )
+
+
+def get_taxes_for_app_identifier(
+ event_type: str,
+ app_identifier: str,
+ static_payload: str,
+ expected_lines_count: int,
+ subscribable_object: Union["Checkout", "Order"],
+ requestor: Union["App", "User", None],
+) -> Promise[TaxData | None]:
+ app = (
+ App.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .filter(
+ identifier=app_identifier,
+ is_active=True,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+
+ if app is None:
+ msg = "Configured tax app doesn't exist."
+ logger.warning(msg)
+ return Promise.reject(TaxDataError(msg))
+
+ webhook = get_webhooks_for_event(event_type, apps_ids=[app.id]).first()
+ if webhook is None:
+ msg = "Configured tax app's webhook for taxes calculation doesn't exists."
+ logger.warning(msg)
+ return Promise.reject(TaxDataError(msg))
+
+ tax_webhook_promise = trigger_webhook_sync_promise(
+ event_type=event_type,
+ webhook=webhook,
+ static_payload=static_payload,
+ allow_replica=False,
+ subscribable_object=subscribable_object,
+ requestor=requestor,
+ )
+
+ def process_response(response_data):
+ try:
+ tax_data = parse_tax_data(event_type, response_data, expected_lines_count)
+ return Promise.resolve(tax_data)
+ except TaxDataError as e:
+ return Promise.reject(e)
+
+ return tax_webhook_promise.then(process_response)
+
+
+def get_taxes_from_all_webhooks(
+ event_type: str,
+ static_payload: str,
+ expected_lines_count: int,
+ subscribable_object: Union["Checkout", "Order"],
+ requestor: Union["App", "User", None],
+) -> Promise[TaxData | None]:
+ webhooks = get_webhooks_for_event(event_type)
+
+ logger.warning(
+ "Missing tax configuration for channel: %s. All tax sync webhooks "
+ "will be triggered. This will stop working in future releases. "
+ "Make sure to configure tax webhooks for each channel.",
+ subscribable_object.channel.slug,
+ )
+
+ tax_webhook_promises = []
+ for webhook in webhooks:
+ tax_webhook_promises.append(
+ trigger_webhook_sync_promise(
+ event_type=event_type,
+ webhook=webhook,
+ static_payload=static_payload,
+ allow_replica=False,
+ subscribable_object=subscribable_object,
+ requestor=requestor,
+ )
+ )
+
+ def process_responses(response_data: list[Any]) -> TaxData | None:
+ for response in response_data:
+ try:
+ parsed_response = parse_tax_data(
+ event_type, response, expected_lines_count
+ )
+ return parsed_response
+
+ except TaxDataError:
+ continue
+ return None
+
+ return Promise.all(tax_webhook_promises).then(process_responses)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index aae6e8b0e1..905d401b3a 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1718,12 +1718,12 @@ def tax_configuration_flat_rates(channel_USD):
@pytest.fixture
-def tax_configuration_tax_app(channel_USD):
+def tax_configuration_tax_app(channel_USD, tax_app):
tc = channel_USD.tax_configuration
tc.country_exceptions.all().delete()
tc.prices_entered_with_tax = False
tc.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tc.tax_app_id = "avatax.app"
+ tc.tax_app_id = tax_app.identifier
tc.save()
return tc
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 3b3821fc35..4e1d2f8e79 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -26,7 +26,6 @@ from ..core.utils.anonymization import (
generate_fake_user,
)
from ..core.utils.json_serializer import CustomJsonEncoder
-from ..discount.utils.shared import is_order_level_discount
from ..discount.utils.voucher import is_order_level_voucher
from ..order import FulfillmentStatus, OrderStatus
from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
@@ -39,7 +38,6 @@ from ..product.models import Collection, Product, ProductMedia, ProductVariant
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod
from ..tax.models import TaxClassCountryRate
-from ..tax.utils import get_charge_taxes_for_order
from ..thumbnail.models import Thumbnail
from ..warehouse.models import Stock, Warehouse
from . import traced_payload_generator
@@ -1365,104 +1363,6 @@ def generate_checkout_payload_for_tax_calculation(
return checkout_data
-def _generate_order_lines_payload_for_tax_calculation(lines: QuerySet[OrderLine]):
- serializer = PayloadSerializer()
-
- charge_taxes = False
- if lines:
- charge_taxes = get_charge_taxes_for_order(lines[0].order)
-
- return serializer.serialize(
- lines,
- fields=("product_name", "variant_name", "quantity"),
- extra_dict_data={
- "variant_id": (lambda line: line.product_variant_id),
- "full_name": (
- lambda line: line.variant.display_product() if line.variant else None
- ),
- "product_metadata": (
- lambda line: line.variant.product.metadata if line.variant else {}
- ),
- "product_type_metadata": (
- lambda line: (
- line.variant.product.product_type.metadata if line.variant else {}
- )
- ),
- "charge_taxes": (lambda _line: charge_taxes),
- "sku": (lambda line: line.product_sku),
- "unit_amount": (
- lambda line: quantize_price(line.base_unit_price_amount, line.currency)
- ),
- "total_amount": (
- lambda line: quantize_price(
- line.base_unit_price_amount * line.quantity, line.currency
- )
- ),
- },
- )
-
-
-@allow_writer()
-@traced_payload_generator
-def generate_order_payload_for_tax_calculation(order: "Order"):
- serializer = PayloadSerializer()
-
- tax_configuration = order.channel.tax_configuration
- prices_entered_with_tax = tax_configuration.prices_entered_with_tax
-
- # Prepare Order data
- address = order.shipping_address or order.billing_address
- lines = order.lines.all()
-
- # Prepare user data
- user = order.user
- user_id = None
- user_public_metadata = {}
- if user:
- user_id = graphene.Node.to_global_id("User", user.id)
- user_public_metadata = user.metadata
-
- # Prepare discount data
- discounts = order.discounts.all()
- discounts_dict = []
- for discount in discounts:
- # Only order level discounts, like entire order vouchers,
- # order promotions and manual discounts should be taken into account
- if not is_order_level_discount(discount):
- continue
- quantize_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})
-
- # Prepare shipping data
- shipping_method_name = order.shipping_method_name
- shipping_method_amount = quantize_price(
- order.base_shipping_price_amount, order.currency
- )
-
- order_data = serializer.serialize(
- [order],
- fields=["currency", "metadata"],
- additional_fields={
- "channel": (lambda o: o.channel, CHANNEL_FIELDS),
- "address": (lambda o: address, ADDRESS_FIELDS),
- },
- extra_dict_data={
- "id": graphene.Node.to_global_id("Order", order.id),
- "user_id": user_id,
- "user_public_metadata": user_public_metadata,
- "discounts": discounts_dict,
- "included_taxes_in_prices": prices_entered_with_tax,
- "shipping_amount": shipping_method_amount,
- "shipping_name": shipping_method_name,
- "lines": json.loads(
- _generate_order_lines_payload_for_tax_calculation(lines)
- ),
- },
- )
- return order_data
-
-
@allow_writer()
@traced_payload_generator
def generate_transaction_action_request_payload(
diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.py
index 76906edaaa..6c6e0797bd 100644
--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py
+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py
@@ -1383,16 +1383,6 @@ def subscription_thumbnail_created_webhook(subscription_webhook):
)
-def subscription_calculate_taxes_for_order(
- subscription_webhook,
-):
- return subscription_webhook(
- queries.ORDER_CALCULATE_TAXES,
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- )
-
-
@pytest.fixture
def subscription_app_installed_webhook_removed_app(subscription_webhook, removed_app):
return subscription_webhook(
diff --git a/saleor/webhook/tests/fixtures/webhook.py b/saleor/webhook/tests/fixtures/webhook.py
index 4d39af5ed1..7d8bd1abc6 100644
--- a/saleor/webhook/tests/fixtures/webhook.py
+++ b/saleor/webhook/tests/fixtures/webhook.py
@@ -253,6 +253,9 @@ def setup_order_webhooks(
):
subscription_async_webhooks = """
fragment OrderFragment on Order {
+ shippingMethods {
+ id
+ }
shippingPrice {
gross {
amount
diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
index b27fa99619..0a5ef7d627 100644
--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -2391,124 +2391,6 @@ subscription {
}
"""
-CALCULATE_TAXES_SUBSCRIPTION_QUERY = """
-subscription CalculateTaxes {
- event {
- ...CalculateTaxesEvent
- }
-}
-
-fragment CalculateTaxesEvent on Event {
- __typename
- ... on CalculateTaxes {
- taxBase {
- ...TaxBase
- }
- recipient {
- privateMetadata {
- key
- value
- }
- }
- }
-}
-
-fragment TaxBase on TaxableObject {
- pricesEnteredWithTax
- currency
- channel {
- slug
- }
- discounts {
- ...TaxDiscount
- }
- address {
- ...Address
- }
- shippingPrice {
- amount
- }
- lines {
- ...TaxBaseLine
- }
- sourceObject {
- __typename
- ... on Checkout {
- avataxEntityCode: metafield(key: "avataxEntityCode")
- user {
- ...User
- }
- }
- ... on Order {
- avataxEntityCode: metafield(key: "avataxEntityCode")
- user {
- ...User
- }
- }
- }
-}
-
-fragment TaxDiscount on TaxableObjectDiscount {
- name
- amount {
- amount
- }
-}
-
-fragment Address on Address {
- streetAddress1
- streetAddress2
- city
- countryArea
- postalCode
- country {
- code
- }
-}
-
-fragment TaxBaseLine on TaxableObjectLine {
- sourceLine {
- __typename
- ... on CheckoutLine {
- id
- checkoutProductVariant: variant {
- id
- product {
- taxClass {
- id
- name
- }
- }
- }
- }
- ... on OrderLine {
- id
- orderProductVariant: variant {
- id
- product {
- taxClass {
- id
- name
- }
- }
- }
- }
- }
- quantity
- unitPrice {
- amount
- }
- totalPrice {
- amount
- }
-}
-
-fragment User on User {
- id
- email
- avataxCustomerCode: metafield(key: "avataxCustomerCode")
-}
-"""
TranslationTypes = Enum(
"TranslationTypes",
@@ -3423,27 +3305,6 @@ THUMBNAIL_CREATED = """
}
"""
-
-ORDER_CALCULATE_TAXES = """
- subscription {
- event {
- ... on CalculateTaxes {
- taxBase {
- sourceObject {
- ...on Order{
- discounts {
- amount {
- amount
- }
- }
- }
- }
- }
- }
- }
- }
-"""
-
CHECKOUT_SHIPPING_LIST_AND_FILTER = """
subscription {
event {
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.py
index 106ee1ebc5..e78d2036d6 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
@@ -1,29 +1,11 @@
import json
-from decimal import Decimal
-from unittest.mock import ANY, Mock
+from unittest.mock import ANY
import pytest
from freezegun import freeze_time
-from prices import Money, TaxedMoney
-from ....core.prices import quantize_price
-from ....discount import (
- DiscountType,
- DiscountValueType,
- RewardType,
- RewardValueType,
- VoucherType,
-)
from ....discount.models import PromotionRule
-from ....discount.utils.voucher import (
- create_or_update_voucher_discount_objects_for_order,
-)
from ....graphql.core.utils import to_global_id_or_none
-from ....order import OrderStatus
-from ....order.calculations import fetch_order_prices_if_expired
-from ....order.models import Order
-from ....order.utils import create_manual_order_discount, update_discount_for_order_line
-from ....plugins.manager import get_plugins_manager
from ....tax import TaxableObjectDiscountType
from ...event_types import WebhookEventSyncType
from ...models import Webhook
@@ -620,1237 +602,3 @@ def test_checkout_calculate_taxes_empty_checkout(
},
},
}
-
-
-@freeze_time("2020-03-18 12:00:00")
[email protected]("charge_taxes", [True, False])
-def test_order_calculate_taxes(order_line, tax_app, shipping_zone, charge_taxes):
- # 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.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_method
- webhook = Webhook.objects.create(
- name="Webhook",
- app=tax_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)
-
- tax_configuration = order.channel.tax_configuration
- tax_configuration.charge_taxes = charge_taxes
- tax_configuration.save(update_fields=["charge_taxes"])
- tax_configuration.country_exceptions.all().delete()
-
- # when
- deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)
-
- # then
- shipping_price_amount = shipping_method.channel_listings.get(
- channel=order.channel
- ).price.amount
- shipping_price_amount = quantize_price(shipping_price_amount, order.currency)
- assert expected_shipping_price != shipping_price_amount
- assert json.loads(deliveries.payload.get_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": charge_taxes,
- "productName": "Test product",
- "productSku": "SKU_A",
- "quantity": 3,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(order_line),
- },
- "totalPrice": {"amount": 36.9},
- "unitPrice": {"amount": 12.3},
- "variantName": "SKU_A",
- }
- ],
- "pricesEnteredWithTax": True,
- "shippingPrice": {"amount": expected_shipping_price.amount},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@freeze_time("2020-03-18 12:00:00")
-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.undiscounted_base_shipping_price = expected_shipping_price
- 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",
- "undiscounted_base_shipping_price_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.get_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),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@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)
- channel_listing = voucher.channel_listings.get()
- channel_listing.discount_value = discount_amount
- channel_listing.save(update_fields=["discount_value"])
-
- order_discount = order.discounts.first()
- order_discount.value = discount_amount
- order_discount.save(update_fields=["value"])
-
- order.undiscounted_base_shipping_price = expected_shipping_price
- 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",
- "undiscounted_base_shipping_price_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.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": float(discount_amount)},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- }
- ],
- "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),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@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.undiscounted_base_shipping_price = expected_shipping_price
- 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",
- "undiscounted_base_shipping_price_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.get_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": line.product_name,
- "productSku": line.product_sku,
- "quantity": line.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line),
- },
- "totalPrice": {
- "amount": float(
- round(line.base_unit_price_amount * line.quantity, 2)
- )
- },
- "unitPrice": {
- "amount": float(round(line.base_unit_price_amount, 2))
- },
- "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),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@freeze_time("2020-03-18 12:00:00")
-def test_order_calculate_taxes_specific_product_voucher(
- order_line,
- subscription_calculate_taxes_for_order,
- shipping_zone,
- voucher_specific_product_type,
-):
- # given
- order = order_line.order
- webhook = subscription_calculate_taxes_for_order
- expected_shipping_price = Money("2.00", order.currency)
- order.undiscounted_base_shipping_price = expected_shipping_price
- order.base_shipping_price = expected_shipping_price
- order.shipping_price = TaxedMoney(
- net=expected_shipping_price, gross=expected_shipping_price
- )
- order.status = OrderStatus.DRAFT
- order.voucher = voucher_specific_product_type
- order.voucher_code = voucher_specific_product_type.codes.first().code
- order.save(
- update_fields=[
- "base_shipping_price_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "undiscounted_base_shipping_price_amount",
- "voucher_code",
- "voucher",
- "status",
- ]
- )
-
- voucher_specific_product_type.discount_value_type = DiscountValueType.FIXED
- voucher_specific_product_type.save(update_fields=["discount_value_type"])
-
- voucher_listing = voucher_specific_product_type.channel_listings.get(
- channel=order.channel
- )
- unit_discount_amount = Decimal(2)
- voucher_listing.discount_value = unit_discount_amount
- voucher_listing.save(update_fields=["discount_value"])
- voucher_specific_product_type.variants.add(order_line.variant)
- create_or_update_voucher_discount_objects_for_order(order)
-
- 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
- expected_total_price_amount = (
- order_line.undiscounted_base_unit_price_amount - unit_discount_amount
- ) * order_line.quantity
- assert json.loads(deliveries.payload.get_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),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@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.get_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),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@freeze_time("2020-03-18 12:00:00")
-def test_order_calculate_taxes_with_manual_discount(
- order_with_lines,
- subscription_calculate_taxes_for_order,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- shipping_price_amount = order.base_shipping_price_amount
-
- discount_value = Decimal(20)
- order.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=discount_value,
- reason="Discount reason",
- )
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
- subtotal_amount = (
- line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
- )
- total_amount = subtotal_amount + shipping_price_amount
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
- fetch_order_prices_if_expired(order, manager, [line_1, line_2], True)
-
- webhook = subscription_calculate_taxes_for_order
- webhook.subscription_query = TAXES_SUBSCRIPTION_QUERY
- webhook.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.
- manual_discount_subtotal_portion = subtotal_amount / total_amount * discount_value
- manual_discount_shipping_portion = discount_value - manual_discount_subtotal_portion
-
- # when
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "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": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {
- "amount": float(line_1_unit_price * line_1.quantity)
- },
- "unitPrice": {"amount": float(line_1_unit_price)},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {
- "amount": float(line_2_unit_price * line_2.quantity)
- },
- "unitPrice": {"amount": float(line_2_unit_price)},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": float(shipping_price_amount)},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-@freeze_time("2020-03-18 12:00:00")
-def test_order_calculate_taxes_empty_order(
- order, webhook_app, permission_handle_taxes, channel_USD
-):
- # given
- order = Order.objects.create(channel=channel_USD, currency="USD", lines_count=0)
- 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
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": None,
- "currency": "USD",
- "discounts": [],
- "lines": [],
- "pricesEnteredWithTax": True,
- "shippingPrice": {"amount": 0.0},
- "channel": {"id": to_global_id_or_none(order.channel)},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": None,
- },
- },
- }
-
-
-def test_order_calculate_taxes_order_promotion(
- order_with_lines,
- order_promotion_with_rule,
- subscription_order_calculate_taxes,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- webhook = subscription_order_calculate_taxes
- channel = order.channel
- shipping_price_amount = order.base_shipping_price_amount
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
-
- promotion = order_promotion_with_rule
- rule = promotion.rules.get()
- rule.order_predicate = {
- "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
- }
- rule.save(update_fields=["order_predicate"])
- reward_value = Decimal(5)
- assert rule.reward_value == reward_value
- assert rule.reward_value_type == RewardValueType.FIXED
- assert rule.reward_type == RewardType.SUBTOTAL_DISCOUNT
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
-
- # when
- fetch_order_prices_if_expired(order, manager, None, True)
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": reward_value},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- }
- ],
- "channel": {"id": to_global_id_or_none(channel)},
- "lines": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
- "unitPrice": {"amount": line_1_unit_price},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
- "unitPrice": {"amount": line_2_unit_price},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": shipping_price_amount},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-def test_order_calculate_taxes_order_voucher_and_manual_discount(
- order_with_lines,
- voucher,
- subscription_order_calculate_taxes,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- webhook = subscription_order_calculate_taxes
- channel = order.channel
- shipping_price_amount = order.base_shipping_price_amount
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
- subtotal_amount = (
- line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
- )
- total_amount = subtotal_amount + shipping_price_amount
-
- assert voucher.type == VoucherType.ENTIRE_ORDER
- order.voucher = voucher
- order.save(update_fields=["voucher_id"])
-
- manual_reward = Decimal(10)
- create_manual_order_discount(
- order=order,
- reason="Manual discount",
- value_type=DiscountValueType.FIXED,
- value=manual_reward,
- )
-
- subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward
- shipping_manual_reward_portion = manual_reward - subtotal_manual_reward_portion
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
-
- # when
- fetch_order_prices_if_expired(order, manager, None, True)
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- manual_discount = order.discounts.get(type=DiscountType.MANUAL)
- assert manual_discount.amount_value == manual_reward
- assert not order.discounts.filter(type=DiscountType.VOUCHER).first()
-
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": subtotal_manual_reward_portion},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- },
- {
- "amount": {"amount": shipping_manual_reward_portion},
- "type": TaxableObjectDiscountType.SHIPPING,
- },
- ],
- "channel": {"id": to_global_id_or_none(channel)},
- "lines": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
- "unitPrice": {"amount": line_1_unit_price},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
- "unitPrice": {"amount": line_2_unit_price},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": shipping_price_amount},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-def test_order_calculate_taxes_order_promotion_and_manual_discount(
- order_with_lines,
- order_promotion_with_rule,
- subscription_order_calculate_taxes,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- webhook = subscription_order_calculate_taxes
- channel = order.channel
- shipping_price_amount = order.base_shipping_price_amount
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
- subtotal_amount = (
- line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
- )
- total_amount = subtotal_amount + shipping_price_amount
-
- promotion = order_promotion_with_rule
- rule = promotion.rules.get()
- rule.order_predicate = {
- "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
- }
- rule.save(update_fields=["order_predicate"])
- assert rule.reward_type == RewardType.SUBTOTAL_DISCOUNT
-
- manual_reward = Decimal(10)
- create_manual_order_discount(
- order=order,
- reason="Manual discount",
- value_type=DiscountValueType.FIXED,
- value=manual_reward,
- )
-
- subtotal_manual_reward_portion = (subtotal_amount / total_amount) * manual_reward
- shipping_manual_reward_portion = manual_reward - subtotal_manual_reward_portion
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
-
- # when
- fetch_order_prices_if_expired(order, manager, None, True)
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- manual_discount = order.discounts.get(type=DiscountType.MANUAL)
- assert manual_discount.amount_value == manual_reward
- assert not order.discounts.filter(type=DiscountType.ORDER_PROMOTION).first()
-
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": subtotal_manual_reward_portion},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- },
- {
- "amount": {"amount": shipping_manual_reward_portion},
- "type": TaxableObjectDiscountType.SHIPPING,
- },
- ],
- "channel": {"id": to_global_id_or_none(channel)},
- "lines": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
- "unitPrice": {"amount": line_1_unit_price},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
- "unitPrice": {"amount": line_2_unit_price},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": shipping_price_amount},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_fixed(
- order_with_lines,
- voucher_free_shipping,
- subscription_order_calculate_taxes,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_free_shipping
- webhook = subscription_order_calculate_taxes
- channel = order.channel
- shipping_price_amount = order.base_shipping_price_amount
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
-
- assert voucher.type == VoucherType.SHIPPING
- order.voucher = voucher
- order.save(update_fields=["voucher_id"])
- create_or_update_voucher_discount_objects_for_order(order)
-
- manual_reward = Decimal(10)
- create_manual_order_discount(
- order=order,
- reason="Manual discount",
- value_type=DiscountValueType.FIXED,
- value=manual_reward,
- )
-
- # Since shipping is free, whole manual discount should be applied to subtotal
- subtotal_manual_reward_portion = manual_reward
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
-
- # when
- fetch_order_prices_if_expired(order, manager, None, True)
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- manual_discount = order.discounts.get(type=DiscountType.MANUAL)
- assert manual_discount.amount_value == subtotal_manual_reward_portion
- voucher_discount = order.discounts.get(type=DiscountType.VOUCHER)
- assert voucher_discount.amount_value == shipping_price_amount
-
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": subtotal_manual_reward_portion},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- },
- ],
- "channel": {"id": to_global_id_or_none(channel)},
- "lines": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
- "unitPrice": {"amount": line_1_unit_price},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
- "unitPrice": {"amount": line_2_unit_price},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": 0},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
-
-
-def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_percentage(
- order_with_lines,
- voucher_free_shipping,
- subscription_order_calculate_taxes,
- tax_configuration_tax_app,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_free_shipping
- webhook = subscription_order_calculate_taxes
- channel = order.channel
- shipping_price_amount = order.base_shipping_price_amount
-
- line_1, line_2 = order.lines.all()
- line_1_unit_price = line_1.base_unit_price_amount
- line_2_unit_price = line_2.base_unit_price_amount
-
- subtotal_amount = (
- line_1_unit_price * line_1.quantity + line_2_unit_price * line_2.quantity
- )
- total_amount = subtotal_amount + shipping_price_amount
-
- assert voucher.type == VoucherType.SHIPPING
- order.voucher = voucher
- order.save(update_fields=["voucher_id"])
- create_or_update_voucher_discount_objects_for_order(order)
- total_amount -= shipping_price_amount
-
- manual_reward = Decimal(10)
- create_manual_order_discount(
- order=order,
- reason="Manual discount",
- value_type=DiscountValueType.PERCENTAGE,
- value=manual_reward,
- )
-
- # Since shipping is free, whole manual discount should be applied to subtotal
- subtotal_manual_reward_portion = manual_reward / 100 * total_amount
-
- manager = Mock(get_taxes_for_order=Mock(return_value={}))
-
- # when
- fetch_order_prices_if_expired(order, manager, None, True)
- deliveries = create_delivery_for_subscription_sync_event(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES, order, webhook
- )
-
- # then
- manual_discount = order.discounts.get(type=DiscountType.MANUAL)
- assert manual_discount.amount_value == subtotal_manual_reward_portion
- voucher_discount = order.discounts.get(type=DiscountType.VOUCHER)
- assert voucher_discount.amount_value == shipping_price_amount
-
- assert json.loads(deliveries.payload.get_payload()) == {
- "__typename": "CalculateTaxes",
- "taxBase": {
- "address": {"id": to_global_id_or_none(order.shipping_address)},
- "currency": "USD",
- "discounts": [
- {
- "amount": {"amount": subtotal_manual_reward_portion},
- "type": TaxableObjectDiscountType.SUBTOTAL,
- },
- ],
- "channel": {"id": to_global_id_or_none(channel)},
- "lines": [
- {
- "chargeTaxes": True,
- "productName": line_1.product_name,
- "productSku": line_1.product_sku,
- "quantity": line_1.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_1),
- },
- "totalPrice": {"amount": line_1_unit_price * line_1.quantity},
- "unitPrice": {"amount": line_1_unit_price},
- "variantName": line_1.variant_name,
- },
- {
- "chargeTaxes": True,
- "productName": line_2.product_name,
- "productSku": line_2.product_sku,
- "quantity": line_2.quantity,
- "sourceLine": {
- "__typename": "OrderLine",
- "id": to_global_id_or_none(line_2),
- },
- "totalPrice": {"amount": line_2_unit_price * line_2.quantity},
- "unitPrice": {"amount": line_2_unit_price},
- "variantName": line_2.variant_name,
- },
- ],
- "pricesEnteredWithTax": False,
- "shippingPrice": {"amount": 0},
- "sourceObject": {
- "__typename": "Order",
- "id": to_global_id_or_none(order),
- "metadata": [
- {"key": key, "value": value}
- for key, value in order.metadata.items()
- ],
- "privateMetadata": [
- {"key": key, "value": value}
- for key, value in order.private_metadata.items()
- ],
- "user": {"id": to_global_id_or_none(order.user)},
- },
- },
- }
diff --git a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py b/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py
deleted file mode 100644
index 557b006842..0000000000
--- a/saleor/webhook/tests/test_sync_webhooks_for_removed_app.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from unittest import mock
-
-from django.utils import timezone
-
-from ...core.models import EventDelivery, EventPayload
-from ..event_types import WebhookEventSyncType
-from ..transport.synchronous.transport import trigger_taxes_all_webhooks_sync
-from ..transport.taxes import parse_tax_data
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_not_trigger_sync_webhook_for_removed_app(
- mock_request,
- tax_app,
-):
- # given
- tax_app.removed_at = timezone.now()
- tax_app.save(update_fields=["removed_at"])
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- data = '{"key": "value"}'
-
- # when
- trigger_taxes_all_webhooks_sync(event_type, lambda: data, parse_tax_data, [0])
-
- # then
- assert EventPayload.objects.count() == 0
- assert EventDelivery.objects.count() == 0
- mock_request.assert_not_called()
diff --git a/saleor/webhook/tests/test_tax_webhook_tasks.py b/saleor/webhook/tests/test_tax_webhook_tasks.py
index 38eec92311..bc3cc7ec94 100644
--- a/saleor/webhook/tests/test_tax_webhook_tasks.py
+++ b/saleor/webhook/tests/test_tax_webhook_tasks.py
@@ -4,10 +4,10 @@ import pytest
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
+from ...tax.webhooks.parser import parse_tax_data
from ..event_types import WebhookEventSyncType
from ..models import Webhook, WebhookEvent
from ..transport.synchronous import trigger_taxes_all_webhooks_sync
-from ..transport.taxes import parse_tax_data
@pytest.fixture
@@ -64,7 +64,7 @@ def test_trigger_tax_webhook_sync(
assert delivery.status == EventDeliveryStatus.PENDING
assert delivery.event_type == event_type
assert delivery.webhook == webhook
- assert tax_data == parse_tax_data(tax_data_response, lines_count)
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -91,7 +91,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_first(
assert delivery.status == EventDeliveryStatus.PENDING
assert delivery.event_type == event_type
assert delivery.webhook == successful_webhook
- assert tax_data == parse_tax_data(tax_data_response, lines_count)
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -122,7 +122,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_last(
assert delivery.payload.get_payload() == data
assert delivery.webhook == webhook
- assert tax_data == parse_tax_data(tax_data_response, lines_count)
+ assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 58e7885a04..831ba7c19f 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -20,7 +20,7 @@ from ...checkout.models import CheckoutLine
from ...checkout.utils import add_voucher_to_checkout
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
-from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from ...discount import DiscountType, DiscountValueType, RewardValueType
from ...discount.models import CheckoutDiscount, CheckoutLineDiscount
from ...graphql.utils import get_user_or_app_from_context
from ...order import FulfillmentLineData, OrderOrigin
@@ -49,7 +49,6 @@ from ..payloads import (
generate_meta,
generate_metadata_updated_payload,
generate_order_payload,
- generate_order_payload_for_tax_calculation,
generate_payment_payload,
generate_product_media_payload,
generate_product_payload,
@@ -302,201 +301,6 @@ def test_generate_order_payload(
mocked_fulfillment_lines.assert_called_with(fulfillment)
-@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
[email protected]("saleor.webhook.payloads._generate_order_lines_payload_for_tax_calculation")
-def test_generate_order_payload_for_tax_calculation(
- mocked_order_lines,
- order_for_payload,
- prices_entered_with_tax,
-):
- # given
- order = order_for_payload
-
- tax_configuration = order.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()
-
- order_lines = '"order_lines"'
- mocked_order_lines.return_value = order_lines
-
- order = order_for_payload
- discount_1, discount_2 = list(order.discounts.all())
- user = order.user
-
- # when
- payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
-
- # then
- currency = order.currency
-
- assert payload == {
- "type": "Order",
- "id": graphene.Node.to_global_id("Order", order.id),
- "channel": {
- "id": graphene.Node.to_global_id("Channel", order.channel_id),
- "type": "Channel",
- "slug": order.channel.slug,
- "currency_code": order.channel.currency_code,
- },
- "address": {
- "id": graphene.Node.to_global_id("Address", order.shipping_address_id),
- "type": "Address",
- "first_name": order.shipping_address.first_name,
- "last_name": order.shipping_address.last_name,
- "company_name": order.shipping_address.company_name,
- "street_address_1": order.shipping_address.street_address_1,
- "street_address_2": order.shipping_address.street_address_2,
- "city": order.shipping_address.city,
- "city_area": order.shipping_address.city_area,
- "postal_code": order.shipping_address.postal_code,
- "country": order.shipping_address.country.code,
- "country_area": order.shipping_address.country_area,
- "phone": str(order.shipping_address.phone),
- },
- "user_id": graphene.Node.to_global_id("User", user.pk),
- "user_public_metadata": user.metadata,
- "included_taxes_in_prices": prices_entered_with_tax,
- "currency": order.currency,
- "shipping_name": order.shipping_method.name,
- "shipping_amount": str(
- quantize_price(order.base_shipping_price_amount, currency)
- ),
- "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)),
- },
- ],
- "lines": json.loads(order_lines),
- }
- mocked_order_lines.assert_called_once()
-
-
-@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
[email protected]("saleor.webhook.payloads._generate_order_lines_payload_for_tax_calculation")
-def test_generate_order_payload_for_tax_calculation_entire_order_voucher(
- mocked_order_lines, order_for_payload, prices_entered_with_tax, voucher
-):
- # given
- order = order_for_payload
-
- tax_configuration = order.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()
-
- order_lines = '"order_lines"'
- mocked_order_lines.return_value = order_lines
-
- order = order_for_payload
- discount_1, discount_2 = list(order.discounts.all())
- voucher.type = VoucherType.ENTIRE_ORDER
- voucher.apply_once_per_order = False
- voucher.save()
- discount_2.voucher = voucher
- discount_2.save()
- user = order.user
-
- # when
- payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
-
- # then
- currency = order.currency
-
- assert payload == {
- "type": "Order",
- "id": graphene.Node.to_global_id("Order", order.id),
- "channel": {
- "id": graphene.Node.to_global_id("Channel", order.channel_id),
- "type": "Channel",
- "slug": order.channel.slug,
- "currency_code": order.channel.currency_code,
- },
- "address": {
- "id": graphene.Node.to_global_id("Address", order.shipping_address_id),
- "type": "Address",
- "first_name": order.shipping_address.first_name,
- "last_name": order.shipping_address.last_name,
- "company_name": order.shipping_address.company_name,
- "street_address_1": order.shipping_address.street_address_1,
- "street_address_2": order.shipping_address.street_address_2,
- "city": order.shipping_address.city,
- "city_area": order.shipping_address.city_area,
- "postal_code": order.shipping_address.postal_code,
- "country": order.shipping_address.country.code,
- "country_area": order.shipping_address.country_area,
- "phone": str(order.shipping_address.phone),
- },
- "user_id": graphene.Node.to_global_id("User", user.pk),
- "user_public_metadata": user.metadata,
- "included_taxes_in_prices": prices_entered_with_tax,
- "currency": order.currency,
- "shipping_name": order.shipping_method.name,
- "shipping_amount": str(
- quantize_price(order.base_shipping_price_amount, currency)
- ),
- "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)),
- },
- ],
- "lines": json.loads(order_lines),
- }
- mocked_order_lines.assert_called_once()
-
-
-@freeze_time()
[email protected]("prices_entered_with_tax", [True, False])
[email protected]("saleor.webhook.payloads._generate_order_lines_payload_for_tax_calculation")
-def test_generate_order_payload_for_tax_calculation_line_level_voucher_excluded(
- mocked_order_lines, order_for_payload, prices_entered_with_tax, voucher
-):
- # given
- order = order_for_payload
-
- tax_configuration = order.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
-
- order_lines = '"order_lines"'
- mocked_order_lines.return_value = order_lines
-
- order = order_for_payload
- discount_1, discount_2 = list(order.discounts.all())
- voucher.type = VoucherType.ENTIRE_ORDER
- # line level vouchers should be excluded from discounts
- voucher.apply_once_per_order = True
- voucher.save()
- discount_2.voucher = voucher
- discount_2.save()
-
- # when
- payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
-
- # then
- assert payload["discounts"] == [
- {
- "name": discount_1.name,
- "amount": str(quantize_price(discount_1.amount_value, order.currency)),
- },
- ]
- mocked_order_lines.assert_called_once()
-
-
@freeze_time()
@mock.patch("saleor.webhook.payloads.generate_order_lines_payload")
@mock.patch("saleor.webhook.payloads.generate_fulfillment_lines_payload")
@@ -737,112 +541,6 @@ def test_order_lines_have_all_required_fields(
}
- ("charge_taxes", "prices_entered_with_tax"),
- [(False, False), (False, True), (True, False), (True, True)],
-)
-def test_order_lines_for_tax_calculation_have_all_required_fields(
- order,
- order_line_with_one_allocation,
- charge_taxes,
- prices_entered_with_tax,
-):
- tax_configuration = order.channel.tax_configuration
- tax_configuration.charge_taxes = charge_taxes
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- order.lines.add(order_line_with_one_allocation)
- currency = order.currency
- line = order_line_with_one_allocation
- line.voucher_code = "Voucher001"
- line.unit_discount_amount = Decimal("10.0")
- line.unit_discount_type = DiscountValueType.FIXED
- line.undiscounted_unit_price = line.unit_price + line.unit_discount
- line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
- line.sale_id = graphene.Node.to_global_id("Sale", 1)
- line.save()
- variant = line.variant
- product = variant.product
- product_type = product.product_type
- product.metadata = {"product_meta": "value"}
- product.save()
- product_type.metadata = {"product_type_meta": "value"}
- product_type.save()
-
- payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
- lines_payload = payload.get("lines")
-
- assert len(lines_payload) == 1
- line_id = graphene.Node.to_global_id("OrderLine", line.id)
- line_payload = lines_payload[0]
- assert line_payload == {
- "type": "OrderLine",
- "id": line_id,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "full_name": variant.display_product(),
- "product_name": line.product_name,
- "variant_name": line.variant_name,
- "product_metadata": {"product_meta": "value"},
- "product_type_metadata": {"product_type_meta": "value"},
- "quantity": line.quantity,
- "sku": line.product_sku,
- "charge_taxes": charge_taxes,
- "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
- "total_amount": str(
- quantize_price(line.base_unit_price_amount * line.quantity, currency)
- ),
- }
-
-
[email protected]("charge_taxes", [True, False])
-def test_order_lines_for_tax_calculation_with_removed_variant(
- order, order_line_with_one_allocation, charge_taxes
-):
- tax_configuration = order.channel.tax_configuration
- tax_configuration.charge_taxes = charge_taxes
- tax_configuration.save(update_fields=["charge_taxes"])
- tax_configuration.country_exceptions.all().delete()
-
- order.lines.add(order_line_with_one_allocation)
- currency = order.currency
- line = order_line_with_one_allocation
- line.voucher_code = "Voucher001"
- line.unit_discount_amount = Decimal("10.0")
- line.unit_discount_type = DiscountValueType.FIXED
- line.undiscounted_unit_price = line.unit_price + line.unit_discount
- line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
- line.sale_id = graphene.Node.to_global_id("Sale", 1)
- variant = line.variant
- line.variant = None
- line.save()
-
- payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
- lines_payload = payload.get("lines")
-
- assert len(lines_payload) == 1
- line_id = graphene.Node.to_global_id("OrderLine", line.id)
- line_payload = lines_payload[0]
- assert line_payload == {
- "type": "OrderLine",
- "id": line_id,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "full_name": None,
- "product_name": line.product_name,
- "variant_name": line.variant_name,
- "product_metadata": {},
- "product_type_metadata": {},
- "quantity": line.quantity,
- "sku": line.product_sku,
- "charge_taxes": charge_taxes,
- "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
- "total_amount": str(
- quantize_price(line.base_unit_price_amount * line.quantity, currency)
- ),
- }
-
-
def test_order_line_without_sku_still_has_id(order, order_line_with_one_allocation):
order.lines.add(order_line_with_one_allocation)
line = order_line_with_one_allocation
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 00358a8dd8..757c988dbb 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -10,13 +10,12 @@ from django.core.cache import cache
from django.db import transaction
from opentelemetry.trace import StatusCode
from promise import Promise
-from pydantic import ValidationError
from ....celeryconf import app
from ....core import EventDeliveryStatus
from ....core.db.connection import allow_writer
from ....core.models import EventDelivery, EventPayload
-from ....core.taxes import TaxData
+from ....core.taxes import TaxData, TaxDataError
from ....core.tracing import webhooks_otel_trace
from ....core.utils import get_domain
from ....core.utils.events import call_event
@@ -36,6 +35,7 @@ from ....payment.utils import (
create_transaction_event_from_request_and_webhook_response,
recalculate_refundable_for_checkout,
)
+from ....tax.webhooks.parser import parse_tax_data
from ....webhook.circuit_breaker.breaker_board import (
initialize_breaker_board,
)
@@ -45,7 +45,6 @@ from ...payloads import generate_transaction_action_request_payload
from ...utils import get_webhooks_for_event
from .. import signature_for_payload
from ..metrics import record_external_request
-from ..taxes import parse_tax_data
from ..utils import (
WebhookResponse,
WebhookSchemes,
@@ -208,7 +207,7 @@ def send_webhook_request_sync(
def trigger_webhook_sync_promise_if_not_cached(
event_type: str,
- payload: str,
+ static_payload: str,
webhook: "Webhook",
cache_data: dict,
allow_replica: bool,
@@ -258,9 +257,9 @@ def trigger_webhook_sync_promise_if_not_cached(
return trigger_webhook_sync_promise(
event_type,
- payload,
webhook,
allow_replica,
+ static_payload=static_payload,
subscribable_object=subscribable_object,
timeout=request_timeout,
request=request,
@@ -508,9 +507,9 @@ def trigger_webhook_sync(
def trigger_webhook_sync_promise(
event_type: str,
- payload: str,
webhook: "Webhook",
allow_replica,
+ static_payload: str,
subscribable_object=None,
timeout=None,
request=None,
@@ -545,7 +544,7 @@ def trigger_webhook_sync_promise(
EventDelivery(
status=EventDeliveryStatus.PENDING,
event_type=event_type,
- payload=EventPayload(payload=payload),
+ payload=EventPayload(payload=static_payload),
webhook=webhook,
)
)
@@ -623,14 +622,10 @@ def trigger_taxes_all_webhooks_sync(
response_data = send_webhook_request_sync(delivery)
try:
- parsed_response = parse_tax_data(response_data, expected_lines_count)
- except ValidationError as e:
- logger.warning(
- "Webhook response for event %s is invalid: %s",
- event_type,
- str(e),
- extra={"errors": e.errors()},
+ parsed_response = parse_tax_data(
+ event_type, response_data, expected_lines_count
)
+ except TaxDataError:
continue
return parsed_response
return None
diff --git a/saleor/webhook/transport/taxes.py b/saleor/webhook/transport/taxes.py
deleted file mode 100644
index 2a21629402..0000000000
--- a/saleor/webhook/transport/taxes.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from typing import Any
-
-from ...app.models import App
-from ...core.taxes import TaxData, TaxLineData
-from ..event_types import WebhookEventSyncType
-from ..response_schemas.taxes import CalculateTaxesSchema
-
-DEFAULT_TAX_CODE = "UNMAPPED"
-DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"
-
-
-def get_current_tax_app() -> App | None:
- """Return currently used tax app or None, if there aren't any."""
- return (
- App.objects.order_by("pk")
- .filter(removed_at__isnull=True)
- .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
- .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
- .last()
- )
-
-
-def parse_tax_data(
- response_data: Any,
- lines_count: int,
-) -> TaxData:
- calculated_taxes_model = CalculateTaxesSchema.model_validate(
- response_data,
- context={"expected_line_count": lines_count},
- )
- return TaxData(
- shipping_price_gross_amount=calculated_taxes_model.shipping_price_gross_amount,
- shipping_price_net_amount=calculated_taxes_model.shipping_price_net_amount,
- shipping_tax_rate=calculated_taxes_model.shipping_tax_rate,
- lines=[
- TaxLineData(
- tax_rate=tax_line.tax_rate,
- total_gross_amount=tax_line.total_gross_amount,
- total_net_amount=tax_line.total_net_amount,
- )
- for tax_line in calculated_taxes_model.lines
- ],
- )