Skip to content

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

Promisify checkout calculate taxes webhook (#19067)

Maciej Korycinski6e3ac84d57a5
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index 62222f28ec..81bd6f9bad 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -1,16 +1,12 @@
-import datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
-from django.utils import timezone
-
from ..core.taxes import zero_money
from ..core.utils.events import (
- call_event_including_protected_events,
- webhook_async_event_requires_sync_webhooks_to_trigger,
+ call_event,
)
from ..payment.models import TransactionItem
-from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ..webhook.event_types import WebhookEventAsyncType
from ..webhook.utils import get_webhooks_for_multiple_events
from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .calculations import fetch_checkout_data
@@ -50,58 +46,11 @@ def call_checkout_event(
if event_name not in CHECKOUT_WEBHOOK_EVENT_MAP:
raise ValueError(f"Event {event_name} not found in CHECKOUT_WEBHOOK_EVENT_MAP.")
- webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
+ webhook_event_map = get_webhooks_for_multiple_events([event_name])
webhooks = webhook_event_map.get(event_name, set())
- if not webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name,
- webhook_event_map,
- possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
- ):
- plugin_manager_method_name = CHECKOUT_WEBHOOK_EVENT_MAP[event_name]
- event_func = getattr(manager, plugin_manager_method_name)
- call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
- return
-
- lines_info, _ = fetch_checkout_lines(
- checkout,
- )
- checkout_info = fetch_checkout_info(
- checkout,
- lines_info,
- manager,
- )
- call_checkout_info_event(
- manager=manager,
- event_name=event_name,
- checkout_info=checkout_info,
- lines=lines_info,
- webhook_event_map=webhook_event_map,
- )
- return
-
-
-def _trigger_checkout_sync_webhooks(
- manager: "PluginsManager",
- checkout_info: "CheckoutInfo",
- lines: list["CheckoutLineInfo"],
- webhook_event_map: dict[str, set["Webhook"]],
- address: Optional["Address"] = None,
-):
- # + timedelta(seconds=10) to confirm that triggered webhooks will still have
- # valid prices. Triggered only when we have active sync tax webhook.
- if webhook_event_map.get(
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- ) and checkout_info.checkout.price_expiration < timezone.now() + datetime.timedelta(
- seconds=10
- ):
- fetch_checkout_data(
- checkout_info=checkout_info,
- manager=manager,
- lines=lines,
- force_update=True,
- )
+ plugin_manager_method_name = CHECKOUT_WEBHOOK_EVENT_MAP[event_name]
+ event_func = getattr(manager, plugin_manager_method_name)
+ call_event(event_func, checkout, webhooks=webhooks)
def call_checkout_events(
@@ -115,35 +64,13 @@ def call_checkout_events(
f"Events {missing_events} not found in CHECKOUT_WEBHOOK_EVENT_MAP."
)
- webhook_event_map = get_webhooks_for_multiple_events(
- [*event_names, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
- any_event_requires_sync_webhooks = any(
- webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name,
- webhook_event_map,
- possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
- )
- for event_name in event_names
- )
- if any_event_requires_sync_webhooks:
- lines_info, _ = fetch_checkout_lines(
- checkout,
- )
- checkout_info = fetch_checkout_info(
- checkout,
- lines_info,
- manager,
- )
- _trigger_checkout_sync_webhooks(
- manager, checkout_info, lines_info, webhook_event_map=webhook_event_map
- )
+ webhook_event_map = get_webhooks_for_multiple_events(event_names)
for event_name in event_names:
plugin_manager_method_name = CHECKOUT_WEBHOOK_EVENT_MAP[event_name]
webhooks = webhook_event_map.get(event_name, set())
event_func = getattr(manager, plugin_manager_method_name)
- call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
+ call_event(event_func, checkout, webhooks=webhooks)
def call_checkout_info_event(
@@ -156,9 +83,7 @@ def call_checkout_info_event(
) -> None:
checkout = checkout_info.checkout
if webhook_event_map is None:
- webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
+ webhook_event_map = get_webhooks_for_multiple_events([event_name])
if event_name not in CHECKOUT_WEBHOOK_EVENT_MAP:
raise ValueError(f"Event {event_name} not found in CHECKOUT_WEBHOOK_EVENT_MAP.")
@@ -166,27 +91,7 @@ def call_checkout_info_event(
plugin_manager_method_name = CHECKOUT_WEBHOOK_EVENT_MAP[event_name]
event_func = getattr(manager, plugin_manager_method_name)
-
- # No need to trigger additional sync webhook when we don't have active webhook or
- # we don't have active sync checkout webhooks
- if not webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name,
- webhook_event_map,
- possible_sync_events=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
- ):
- call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
- return
-
- _trigger_checkout_sync_webhooks(
- manager,
- checkout_info,
- lines,
- address=address,
- webhook_event_map=webhook_event_map,
- )
-
- call_event_including_protected_events(event_func, checkout, webhooks=webhooks)
- return
+ call_event(event_func, checkout, webhooks=webhooks)
def update_last_transaction_modified_at_for_checkout(
@@ -211,7 +116,9 @@ def transaction_amounts_for_checkout_updated(
checkout_info = fetch_checkout_info(checkout, lines, manager)
previous_charge_status = checkout_info.checkout.charge_status
previous_authorize_status = checkout_info.checkout.authorize_status
- fetch_checkout_data(checkout_info, manager, lines, force_status_update=True)
+ fetch_checkout_data(
+ checkout_info, manager, lines, force_status_update=True, requestor=user or app
+ ).get()
_transaction_amounts_for_checkout_updated(
transaction,
previous_charge_status,
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index a41a39d5bc..fd673963cf 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,14 +1,18 @@
import logging
from collections.abc import Iterable
from decimal import Decimal
-from typing import TYPE_CHECKING, Optional, cast
+from typing import TYPE_CHECKING, Union, cast
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,
@@ -37,7 +41,8 @@ from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
if TYPE_CHECKING:
- from ..account.models import Address
+ from ..account.models import User
+ from ..app.models import App
from ..plugins.manager import PluginsManager
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -49,26 +54,22 @@ def checkout_shipping_price(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
allow_sync_webhooks: bool = True,
) -> "TaxedMoney":
"""Return checkout shipping price.
It takes in account all plugins.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
currency = checkout_info.checkout.currency
checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
return quantize_price(checkout_info.checkout.shipping_price, currency)
@@ -77,7 +78,6 @@ def checkout_shipping_tax_rate(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
) -> Decimal:
@@ -91,7 +91,8 @@ def checkout_shipping_tax_rate(
lines=lines,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
return checkout_info.checkout.shipping_tax_rate
@@ -100,26 +101,22 @@ def checkout_subtotal(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
allow_sync_webhooks: bool = True,
) -> "TaxedMoney":
"""Return the total cost of all the checkout lines, taxes included.
It takes in account all plugins.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
currency = checkout_info.checkout.currency
checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
return quantize_price(checkout_info.checkout.subtotal, currency)
@@ -127,9 +124,7 @@ def calculate_checkout_total_with_gift_cards(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
force_update: bool = False,
allow_sync_webhooks: bool = True,
) -> "TaxedMoney":
@@ -138,15 +133,11 @@ def calculate_checkout_total_with_gift_cards(
Gift cards total is subtracted from total gross amount and subtracted proportionally
from total net amount.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
total = calculate_checkout_total(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
force_update=force_update,
allow_sync_webhooks=allow_sync_webhooks,
)
@@ -176,9 +167,7 @@ def calculate_checkout_total(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- address: Optional["Address"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
force_update: bool = False,
allow_sync_webhooks: bool = True,
) -> "TaxedMoney":
@@ -189,18 +178,16 @@ def calculate_checkout_total(
It takes in account all plugins.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
currency = checkout_info.checkout.currency
checkout_info, _ = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
force_update=force_update,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
return quantize_price(checkout_info.checkout.total, currency)
@@ -211,24 +198,21 @@ def checkout_line_total(
lines: list["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
allow_sync_webhooks: bool = True,
) -> TaxedMoney:
"""Return the total price of provided line, taxes included.
It takes in account all plugins.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
currency = checkout_info.checkout.currency
_, lines = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
return quantize_price(checkout_line.total_price, currency)
@@ -240,24 +224,21 @@ def checkout_line_unit_price(
lines: list["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
allow_sync_webhooks: bool = True,
) -> TaxedMoney:
"""Return the unit price of provided line, taxes included.
It takes in account all plugins.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
currency = checkout_info.checkout.currency
_, lines = fetch_checkout_data(
checkout_info,
manager=manager,
lines=lines,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
unit_price = checkout_line.total_price / checkout_line.quantity
return quantize_price(unit_price, currency)
@@ -282,7 +263,8 @@ def checkout_line_tax_rate(
lines=lines,
database_connection_name=database_connection_name,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
checkout_line_info = find_checkout_line_info(lines, checkout_line_info.line.id)
return checkout_line_info.line.tax_rate
@@ -343,15 +325,54 @@ def update_prior_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
line_info.line.prior_unit_price_amount = line_info.prior_unit_price_amount
+@allow_writer()
+def promise_calculate_taxes_with_error_handling(
+ tax_calculation_strategy: str,
+ tax_app_identifier: str | None,
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: list["CheckoutLineInfo"],
+ prices_entered_with_tax: bool,
+ requestor: Union["App", "User", None],
+ database_connection_name: str,
+) -> Promise[None]:
+ from .utils import checkout_info_for_logs
+
+ checkout = checkout_info.checkout
+
+ @allow_writer_for_default_connection(database_connection_name)
+ def process_error(e: Exception):
+ if not isinstance(e, TaxDataError):
+ raise e
+ if str(e) != TaxDataErrorMessage.EMPTY:
+ extra = checkout_info_for_logs(checkout_info, lines)
+ if getattr(e, "errors", None):
+ extra["errors"] = e.errors
+ logger.warning(str(e), extra=extra)
+ _set_checkout_base_prices(checkout, checkout_info, lines)
+ checkout.tax_error = str(e)
+
+ return _calculate_and_add_tax(
+ tax_calculation_strategy=tax_calculation_strategy,
+ tax_app_identifier=tax_app_identifier,
+ checkout_info=checkout_info,
+ lines=lines,
+ manager=manager,
+ prices_entered_with_tax=prices_entered_with_tax,
+ requestor=requestor,
+ database_connection_name=database_connection_name,
+ ).catch(process_error)
+
+
def _fetch_checkout_prices_if_expired(
checkout_info: "CheckoutInfo",
manager: "PluginsManager",
lines: list["CheckoutLineInfo"],
allow_sync_webhooks: bool,
+ requestor: Union["App", "User", None],
force_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
-) -> tuple["CheckoutInfo", list["CheckoutLineInfo"]]:
+) -> Promise[tuple["CheckoutInfo", list["CheckoutLineInfo"]]]:
"""Fetch checkout prices with taxes.
First calculate and apply all checkout prices with taxes separately,
@@ -360,137 +381,132 @@ def _fetch_checkout_prices_if_expired(
Prices can be updated only if force_update == True, or if time elapsed from the
last price update is greater than settings.CHECKOUT_PRICES_TTL.
"""
- from .utils import checkout_info_for_logs
-
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
-
checkout = checkout_info.checkout
if not force_update and checkout.price_expiration > timezone.now():
- return checkout_info, lines
+ return Promise.resolve((checkout_info, lines))
tax_configuration = checkout_info.tax_configuration
- tax_calculation_strategy = get_tax_calculation_strategy_for_checkout(
- checkout_info, database_connection_name=database_connection_name
- )
-
- if (
- tax_calculation_strategy == TaxCalculationStrategy.TAX_APP
- and not allow_sync_webhooks
- ):
- return checkout_info, lines
+ with allow_writer_for_default_connection(database_connection_name):
+ tax_calculation_strategy = get_tax_calculation_strategy_for_checkout(
+ checkout_info, database_connection_name=database_connection_name
+ )
- prices_entered_with_tax = tax_configuration.prices_entered_with_tax
- charge_taxes = get_charge_taxes_for_checkout(
- checkout_info, database_connection_name=database_connection_name
- )
- should_charge_tax = charge_taxes and not checkout.tax_exemption
- tax_app_identifier = get_tax_app_identifier_for_checkout(
- checkout_info, database_connection_name
- )
+ if (
+ tax_calculation_strategy == TaxCalculationStrategy.TAX_APP
+ and not allow_sync_webhooks
+ ):
+ return Promise.resolve((checkout_info, lines))
- try:
- recalculate_discounts(
- checkout_info,
- lines,
- database_connection_name=database_connection_name,
- force_update=force_update,
+ prices_entered_with_tax = tax_configuration.prices_entered_with_tax
+ charge_taxes = get_charge_taxes_for_checkout(
+ checkout_info, database_connection_name=database_connection_name
+ )
+ should_charge_tax = charge_taxes and not checkout.tax_exemption
+ tax_app_identifier = get_tax_app_identifier_for_checkout(
+ checkout_info, database_connection_name
)
- except Checkout.DoesNotExist:
- # Checkout was removed or converted to a order. Return data without saving.
- return checkout_info, lines
-
- checkout.tax_error = None
- no_need_to_calculate_taxes = not prices_entered_with_tax and not should_charge_tax
- if no_need_to_calculate_taxes:
- # Calculate net prices without taxes.
- _set_checkout_base_prices(checkout, checkout_info, lines)
- else:
try:
- _calculate_and_add_tax(
- tax_calculation_strategy,
- tax_app_identifier,
- checkout,
- manager,
+ recalculate_discounts(
checkout_info,
lines,
- prices_entered_with_tax,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
+ force_update=force_update,
)
- except TaxDataError as e:
- if str(e) != TaxDataErrorMessage.EMPTY:
- extra = checkout_info_for_logs(checkout_info, lines)
- if e.errors:
- extra["errors"] = e.errors
- logger.warning(str(e), extra=extra)
- _set_checkout_base_prices(checkout, checkout_info, lines)
- checkout.tax_error = str(e)
-
- if not should_charge_tax:
- # If charge_taxes is disabled or checkout is exempt from taxes, remove the
- # tax from the original gross prices.
- _remove_tax(checkout, lines)
-
- price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
- checkout.price_expiration = price_expiration
- checkout.discount_expiration = price_expiration
-
- with allow_writer():
- with transaction.atomic():
- try:
- locked_checkout = (
- checkout_qs_select_for_update()
- .only("last_change")
- .get(token=checkout.token)
- )
- except Checkout.DoesNotExist:
- # Checkout was removed or converted to a order. Return data without saving.
+ except Checkout.DoesNotExist:
+ # Checkout was removed or converted to a order. Return data without saving.
+ return Promise.resolve((checkout_info, lines))
+
+ checkout.tax_error = None
+
+ def remove_tax_if_needed(_):
+ if should_charge_tax:
+ return
+ # If charge_taxes is disabled or checkout is exempt from taxes, remove the
+ # tax from the original gross prices.
+ _remove_tax(checkout, lines)
+ return
+
+ def process_calculation_result(_):
+ price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
+ checkout.price_expiration = price_expiration
+ checkout.discount_expiration = price_expiration
+
+ with allow_writer():
+ with transaction.atomic():
+ try:
+ locked_checkout = (
+ checkout_qs_select_for_update()
+ .only("last_change")
+ .get(token=checkout.token)
+ )
+ except Checkout.DoesNotExist:
+ # Checkout was removed or converted to a order. Return data without saving.
+ return checkout_info, lines
+
+ # Check whether the checkout has been modified during the recalculation process by another process.
+ # If so, we should skip saving. The same applies if the checkout 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 checkout and line info objects.
+ if checkout.last_change == locked_checkout.last_change:
+ checkout_update_fields = [
+ "voucher_code",
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "undiscounted_base_shipping_price_amount",
+ "shipping_tax_rate",
+ "translated_discount_name",
+ "discount_amount",
+ "discount_name",
+ "currency",
+ "price_expiration",
+ "discount_expiration",
+ "tax_error",
+ ]
+
+ from .utils import checkout_lines_bulk_update
+
+ checkout.save(
+ update_fields=checkout_update_fields,
+ using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ )
+ checkout_lines_bulk_update(
+ [line_info.line for line_info in lines],
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "tax_rate",
+ "undiscounted_unit_price_amount",
+ "prior_unit_price_amount",
+ ],
+ )
return checkout_info, lines
- # Check whether the checkout has been modified during the recalculation process by another process.
- # If so, we should skip saving. The same applies if the checkout 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 checkout and line info objects.
- if checkout.last_change == locked_checkout.last_change:
- checkout_update_fields = [
- "voucher_code",
- "total_net_amount",
- "total_gross_amount",
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "undiscounted_base_shipping_price_amount",
- "shipping_tax_rate",
- "translated_discount_name",
- "discount_amount",
- "discount_name",
- "currency",
- "price_expiration",
- "discount_expiration",
- "tax_error",
- ]
-
- from .utils import checkout_lines_bulk_update
-
- checkout.save(
- update_fields=checkout_update_fields,
- using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
- )
- checkout_lines_bulk_update(
- [line_info.line for line_info in lines],
- [
- "total_price_net_amount",
- "total_price_gross_amount",
- "tax_rate",
- "undiscounted_unit_price_amount",
- "prior_unit_price_amount",
- ],
- )
- return checkout_info, lines
+ no_need_to_calculate_taxes = not prices_entered_with_tax and not should_charge_tax
+ if no_need_to_calculate_taxes:
+ # Calculate net prices without taxes.
+ _set_checkout_base_prices(checkout, checkout_info, lines)
+ return Promise.resolve(None).then(process_calculation_result)
+
+ return (
+ promise_calculate_taxes_with_error_handling(
+ tax_calculation_strategy=tax_calculation_strategy,
+ tax_app_identifier=tax_app_identifier,
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ prices_entered_with_tax=prices_entered_with_tax,
+ requestor=requestor,
+ database_connection_name=database_connection_name,
+ )
+ .then(remove_tax_if_needed)
+ .then(process_calculation_result)
+ )
@allow_writer()
@@ -540,21 +556,21 @@ def recalculate_discounts(
return checkout_info, lines
+@allow_writer()
def _calculate_and_add_tax(
tax_calculation_strategy: str,
tax_app_identifier: str | None,
- checkout: "Checkout",
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
prices_entered_with_tax: bool,
+ requestor: Union["App", "User", None],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
):
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
+ checkout = checkout_info.checkout
- if tax_calculation_strategy != TaxCalculationStrategy.TAX_APP:
+ @allow_writer_for_default_connection(database_connection_name)
+ def process_flat_taxes(_):
# Get taxes calculated with flat rates and apply to checkout.
update_checkout_prices_with_flat_rates(
checkout,
@@ -563,49 +579,48 @@ def _calculate_and_add_tax(
prices_entered_with_tax,
database_connection_name=database_connection_name,
)
- return
+
+ 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=tax_app_identifier,
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ requestor=requestor,
+ )
+
+ # Deprecated flow when no tax app identifier is provided.
+ def recalculate_with_tax_app_data(tax_data: TaxData | None):
+ _apply_tax_data(checkout, lines, tax_data)
+
+ # Call the tax plugins.
+ _apply_tax_data_from_plugins(checkout, manager, checkout_info, lines)
# 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:
- # Call the tax plugins.
- _apply_tax_data_from_plugins(checkout, manager, checkout_info, lines)
- # Get the taxes calculated with apps and apply to checkout.
- # 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_checkout(
- checkout_info,
- lines,
- tax_app_identifier,
- manager,
- pregenerated_subscription_payloads,
- allowed_empty_tax_data=True,
- )
- _apply_tax_data(checkout, lines, tax_data)
- else:
- _call_plugin_or_tax_app(
- tax_app_identifier,
- checkout,
- manager,
- checkout_info,
- lines,
- pregenerated_subscription_payloads,
- )
+ return _get_promised_taxes_for_checkout(
+ checkout_info=checkout_info,
+ lines=lines,
+ tax_app_identifier=tax_app_identifier,
+ requestor=requestor,
+ allowed_empty_tax_data=True,
+ ).then(recalculate_with_tax_app_data)
def _call_plugin_or_tax_app(
tax_app_identifier: str,
- checkout: "Checkout",
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- pregenerated_subscription_payloads: dict | None = None,
-):
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
+ requestor: Union["App", "User", None],
+) -> Promise[None]:
+ checkout = checkout_info.checkout
- if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ def recalculate_with_plugins(_):
plugin_ids = [tax_app_identifier.replace(PLUGIN_IDENTIFIER_PREFIX, "")]
plugins = manager.get_plugins(
checkout_info.channel.slug,
@@ -613,7 +628,7 @@ def _call_plugin_or_tax_app(
plugin_ids=plugin_ids,
)
if not plugins:
- raise TaxDataError(TaxDataErrorMessage.EMPTY)
+ return Promise.reject(TaxDataError(TaxDataErrorMessage.EMPTY))
_apply_tax_data_from_plugins(
checkout,
manager,
@@ -622,54 +637,59 @@ def _call_plugin_or_tax_app(
plugin_ids=plugin_ids,
)
if checkout.tax_error:
- raise TaxDataError(checkout.tax_error)
- else:
- tax_data = _get_taxes_for_checkout(
- checkout_info,
- lines,
- tax_app_identifier,
- manager,
- pregenerated_subscription_payloads,
- )
+ return Promise.reject(TaxDataError(checkout.tax_error))
+ return Promise.resolve(None)
+
+ if tax_app_identifier.startswith(PLUGIN_IDENTIFIER_PREFIX):
+ return Promise.resolve(None).then(recalculate_with_plugins)
+
+ def recalculate_with_tax_app_data(tax_data: TaxData | None):
_apply_tax_data(checkout, lines, tax_data)
+ return _get_promised_taxes_for_checkout(
+ checkout_info=checkout_info,
+ lines=lines,
+ tax_app_identifier=tax_app_identifier,
+ requestor=requestor,
+ ).then(recalculate_with_tax_app_data)
+
-def _get_taxes_for_checkout(
+def _get_promised_taxes_for_checkout(
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
tax_app_identifier: str | None,
- manager: "PluginsManager",
- pregenerated_subscription_payloads: dict | None = None,
+ requestor: Union["App", "User", None],
allowed_empty_tax_data: bool = False,
-):
+) -> Promise[TaxData | None]:
"""Get taxes for checkout 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.
"""
from .utils import log_address_if_validation_skipped_for_checkout
+ from .webhooks import calculate_taxes as checkout_calculate_taxes
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
- tax_data = None
- try:
- tax_data = manager.get_taxes_for_checkout(
- checkout_info,
- lines,
- tax_app_identifier,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- )
- except TaxDataError as e:
- raise e from e
- finally:
- # log in case the tax_data is missing
+ def process_error(e: Exception):
+ if isinstance(e, TaxDataError):
+ log_address_if_validation_skipped_for_checkout(checkout_info, 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_checkout(checkout_info, 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 tax_data
+ return Promise.resolve(tax_data)
+
+ return (
+ checkout_calculate_taxes.get_taxes(
+ checkout_info, lines, tax_app_identifier, requestor=requestor
+ )
+ .then(process_response)
+ .catch(process_error)
+ )
def _remove_tax(checkout, lines_info):
@@ -824,57 +844,63 @@ def fetch_checkout_data(
checkout_info: "CheckoutInfo",
manager: "PluginsManager",
lines: list["CheckoutLineInfo"],
+ requestor: Union["App", "User", None],
force_update: bool = False,
checkout_transactions: Iterable["TransactionItem"] | None = None,
force_status_update: bool = False,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
- pregenerated_subscription_payloads: dict | None = None,
allow_sync_webhooks: bool = True,
-):
+) -> Promise[tuple["CheckoutInfo", list["CheckoutLineInfo"]]]:
"""Fetch checkout data.
This function refreshes prices if they have expired. If the checkout total has
changed as a result, it will update the payment statuses accordingly.
"""
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
previous_checkout_price_expiration = checkout_info.checkout.price_expiration
- checkout_info, lines = _fetch_checkout_prices_if_expired(
+
+ @allow_writer_for_default_connection(database_connection_name)
+ def process_refreshed_prices(
+ data: tuple["CheckoutInfo", list["CheckoutLineInfo"]],
+ ):
+ checkout_info, lines = data
+ current_total_gross = checkout_info.checkout.total.gross
+ if (
+ checkout_info.checkout.price_expiration
+ != previous_checkout_price_expiration
+ or force_status_update
+ or (
+ # Checkout with total being zero is fully authorized therefore
+ # if authorized status was not yet updated, do it now.
+ current_total_gross == zero_money(current_total_gross.currency)
+ and checkout_info.checkout.authorize_status
+ != CheckoutAuthorizeStatus.FULL
+ and bool(lines)
+ )
+ ):
+ current_total_gross = (
+ checkout_info.checkout.total.gross
+ - checkout_info.checkout.get_total_gift_cards_balance(
+ database_connection_name
+ )
+ )
+ current_total_gross = max(
+ current_total_gross, zero_money(current_total_gross.currency)
+ )
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=current_total_gross,
+ checkout_has_lines=bool(lines),
+ checkout_transactions=checkout_transactions,
+ database_connection_name=database_connection_name,
+ )
+ return checkout_info, lines
+
+ return _fetch_checkout_prices_if_expired(
checkout_info=checkout_info,
manager=manager,
lines=lines,
force_update=force_update,
database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
+ requestor=requestor,
allow_sync_webhooks=allow_sync_webhooks,
- )
- current_total_gross = checkout_info.checkout.total.gross
- if (
- checkout_info.checkout.price_expiration != previous_checkout_price_expiration
- or force_status_update
- or (
- # Checkout with total being zero is fully authorized therefore
- # if authorized status was not yet updated, do it now.
- current_total_gross == zero_money(current_total_gross.currency)
- and checkout_info.checkout.authorize_status != CheckoutAuthorizeStatus.FULL
- and bool(lines)
- )
- ):
- current_total_gross = (
- checkout_info.checkout.total.gross
- - checkout_info.checkout.get_total_gift_cards_balance(
- database_connection_name
- )
- )
- current_total_gross = max(
- current_total_gross, zero_money(current_total_gross.currency)
- )
- update_checkout_payment_statuses(
- checkout=checkout_info.checkout,
- checkout_total_gross=current_total_gross,
- checkout_has_lines=bool(lines),
- checkout_transactions=checkout_transactions,
- database_connection_name=database_connection_name,
- )
-
- return checkout_info, lines
+ ).then(process_refreshed_prices)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index b606f02c74..8949b2355c 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -667,15 +667,10 @@ def _prepare_order_data(
"""
checkout = checkout_info.checkout
order_data = {}
- address = (
- checkout_info.shipping_address or checkout_info.billing_address
- ) # FIXME: check which address we need here
-
taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
undiscounted_base_shipping_price = base_checkout_undiscounted_delivery_price(
@@ -686,13 +681,11 @@ def _prepare_order_data(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
order_data.update(
_process_shipping_data_for_order(
@@ -751,7 +744,6 @@ def _prepare_order_data(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
).gross
try:
@@ -1096,7 +1088,8 @@ def complete_checkout_pre_payment_part(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
- user,
+ user: Optional["User"],
+ app: Optional["App"],
site_settings=None,
redirect_url=None,
) -> tuple[Payment | None, str | None, dict]:
@@ -1109,7 +1102,7 @@ def complete_checkout_pre_payment_part(
if site_settings is None:
site_settings = Site.objects.get_current().settings
- fetch_checkout_data(checkout_info, manager, lines)
+ fetch_checkout_data(checkout_info, manager, lines, requestor=app or user).get()
checkout = checkout_info.checkout
payment = checkout.get_last_active_payment()
@@ -1393,8 +1386,6 @@ def _create_order_from_checkout(
site_settings = Site.objects.get_current().settings
- address = checkout_info.shipping_address or checkout_info.billing_address
-
reservation_enabled = is_reservation_enabled(site_settings)
tax_configuration = checkout_info.tax_configuration
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
@@ -1404,7 +1395,6 @@ def _create_order_from_checkout(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
- address=address,
force_update=force_update,
)
@@ -1425,13 +1415,11 @@ def _create_order_from_checkout(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
- address=address,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
- address=address,
)
# status
@@ -1534,7 +1522,6 @@ def _create_order_from_checkout(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
- address=address,
).gross
add_gift_cards_to_order(checkout_info, order, total_without_giftcard, user, app)
@@ -1724,11 +1711,8 @@ def complete_checkout(
force_update = checkout_info.checkout.tax_error is not None
fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- force_update=force_update,
- )
+ checkout_info, manager, lines, force_update=force_update, requestor=app or user
+ ).get()
if checkout_info.checkout.tax_error is not None:
raise ValidationError(
"Configured Tax App returned invalid response.",
@@ -1872,6 +1856,7 @@ def complete_checkout_with_payment(
checkout_info=checkout_info,
lines=lines,
user=user,
+ app=app,
site_settings=site_settings,
redirect_url=redirect_url,
)
diff --git a/saleor/checkout/tests/fixtures/checkout_with_payment.py b/saleor/checkout/tests/fixtures/checkout_with_payment.py
index e15c366682..b1fea743b9 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_payment.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_payment.py
@@ -33,7 +33,6 @@ def checkout_with_charged_payment(checkout_with_billing_address):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = Payment.objects.create(
gateway="mirumee.payments.dummy",
@@ -68,7 +67,6 @@ def checkout_with_charged_payment_for_cc(checkout_with_billing_address_for_cc):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = Payment.objects.create(
gateway="mirumee.payments.dummy",
@@ -111,7 +109,6 @@ def checkout_preorder_with_charged_payment(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = Payment.objects.create(
gateway="mirumee.payments.dummy",
diff --git a/saleor/checkout/tests/test_actions.py b/saleor/checkout/tests/test_actions.py
index 581a1623b4..ae7d67e76b 100644
--- a/saleor/checkout/tests/test_actions.py
+++ b/saleor/checkout/tests/test_actions.py
@@ -1,6 +1,6 @@
import datetime
from decimal import Decimal
-from unittest.mock import ANY, call, patch
+from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
@@ -8,10 +8,6 @@ from django.utils import timezone
from freezegun import freeze_time
from ...core.models import EventDelivery
-from ...core.utils.events import call_event_including_protected_events
-from ...graphql.webhook.dataloaders.pregenerated_payload_for_checkout_tax import (
- PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,
-)
from ...plugins.manager import get_plugins_manager
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from .. import CheckoutAuthorizeStatus, CheckoutChargeStatus
@@ -42,7 +38,9 @@ def test_transaction_amounts_for_checkout_updated_fully_paid(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
@@ -79,7 +77,9 @@ def test_transaction_amounts_for_checkout_updated_not_fully_paid_no_automatic_co
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk,
charged_value=checkout_info.checkout.total.gross.amount / 2,
@@ -119,13 +119,17 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_paid(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
assert checkout_info.channel.automatically_complete_fully_paid_checkouts is False
- fetch_checkout_data(checkout_info, plugins_manager, lines, force_status_update=True)
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, force_status_update=True, requestor=None
+ ).get()
second_transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
@@ -161,9 +165,11 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_authorized(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
total = calculate_checkout_total(
- manager=plugins_manager, checkout_info=checkout_info, lines=lines, address=None
+ manager=plugins_manager, checkout_info=checkout_info, lines=lines
)
first_authorized_amount = total.gross.amount - 1
@@ -177,7 +183,9 @@ def test_transaction_amounts_for_checkout_updated_with_already_fully_authorized(
checkout_id=checkout.pk, authorized_value=second_authorized_amount
)
- fetch_checkout_data(checkout_info, plugins_manager, lines, force_status_update=True)
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, force_status_update=True, requestor=None
+ ).get()
assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
assert checkout.charge_status == CheckoutChargeStatus.NONE
@@ -213,7 +221,9 @@ def test_transaction_amounts_for_checkout_updated_fully_authorized(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk,
authorized_value=checkout_info.checkout.total.gross.amount,
@@ -255,10 +265,8 @@ def test_transaction_amounts_for_checkout_updated_updates_last_transaction_modif
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
@@ -285,10 +293,8 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_success(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(10.0)
)
@@ -316,10 +322,8 @@ def test_get_checkout_refundable_with_transaction_and_last_refund_failure(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(10.0), last_refund_success=False
)
@@ -347,10 +351,8 @@ def test_get_checkout_refundable_with_transaction_without_funds(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(0)
)
@@ -378,10 +380,8 @@ def test_get_checkout_refundable_with_multiple_transactions_without_funds(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
first_transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(0)
)
@@ -410,10 +410,8 @@ def test_get_checkout_refundable_with_multiple_transactions_with_failure_refund(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
first_transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=False
)
@@ -444,10 +442,8 @@ def test_get_checkout_refundable_with_multiple_active_transactions(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
first_transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=Decimal(10), last_refund_success=False
)
@@ -513,13 +509,8 @@ def test_call_checkout_event_incorrect_webhook_event(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_event_triggers_sync_webhook_when_needed(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -609,25 +600,14 @@ def test_call_checkout_event_triggers_sync_webhook_when_needed(
tax_delivery = tax_delivery_call.args[0]
assert tax_delivery.webhook_id == tax_webhook.id
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_event_skips_tax_webhook_when_not_expired(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -709,12 +689,6 @@ def test_call_checkout_event_skips_tax_webhook_when_not_expired(
== WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
)
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -749,7 +723,6 @@ def test_call_checkout_event_skip_sync_webhooks_when_async_missing(
)
# then
-
assert not mocked_send_webhook_request_async.called
assert not mocked_send_webhook_request_sync.called
@@ -759,13 +732,8 @@ def test_call_checkout_event_skip_sync_webhooks_when_async_missing(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_event_only_async_when_sync_missing(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -792,7 +760,6 @@ def test_call_checkout_event_only_async_when_sync_missing(
)
# then
-
# confirm that event delivery was generated for each async webhook.
checkout_create_delivery = EventDelivery.objects.get(webhook_id=webhook.id)
@@ -805,9 +772,6 @@ def test_call_checkout_event_only_async_when_sync_missing(
MessageGroupId="example.com:saleorapptest",
)
assert not mocked_send_webhook_request_sync.called
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created, checkout_with_items, webhooks={webhook}
- )
@freeze_time("2023-05-31 12:00:01")
@@ -864,13 +828,8 @@ def test_call_checkout_info_event_incorrect_webhook_event(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_info_event_triggers_sync_webhook_when_needed(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -972,25 +931,14 @@ def test_call_checkout_info_event_triggers_sync_webhook_when_needed(
tax_delivery = tax_delivery_call.args[0]
assert tax_delivery.webhook_id == tax_webhook.id
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_info_event_skips_tax_webhook_when_not_expired(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -1083,25 +1031,14 @@ def test_call_checkout_info_event_skips_tax_webhook_when_not_expired(
== WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
)
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_info_event_only_async_when_sync_missing(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -1151,9 +1088,6 @@ def test_call_checkout_info_event_only_async_when_sync_missing(
MessageGroupId="example.com:saleorapptest",
)
assert not mocked_send_webhook_request_sync.called
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_created, checkout_with_items, webhooks={webhook}
- )
@freeze_time("2023-05-31 12:00:01")
@@ -1213,13 +1147,8 @@ def test_call_checkout_info_event_skip_sync_webhooks_when_async_missing(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1252,7 +1181,9 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk, charged_value=checkout_info.checkout.total.gross.amount
)
@@ -1318,18 +1249,6 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
assert wrapped_call_checkout_info_event.called
- assert mocked_call_event_including_protected_events.call_count == 2
- mocked_call_event_including_protected_events.assert_any_call(
- plugins_manager.checkout_fully_paid,
- checkout_with_items,
- webhooks={checkout_fully_paid_webhook},
- )
- mocked_call_event_including_protected_events.assert_any_call(
- plugins_manager.checkout_fully_authorized,
- checkout_with_items,
- webhooks=set(),
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch(
@@ -1340,13 +1259,8 @@ def test_transaction_amounts_for_checkout_fully_paid_triggers_sync_webhook(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_transaction_amounts_for_checkout_fully_authorized_triggers_sync_webhook(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
wrapped_call_checkout_info_event,
@@ -1379,7 +1293,9 @@ def test_transaction_amounts_for_checkout_fully_authorized_triggers_sync_webhook
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=None
+ ).get()
transaction = transaction_item_generator(
checkout_id=checkout.pk,
@@ -1448,12 +1364,6 @@ def test_transaction_amounts_for_checkout_fully_authorized_triggers_sync_webhook
assert wrapped_call_checkout_info_event.called
- mocked_call_event_including_protected_events.assert_called_once_with(
- plugins_manager.checkout_fully_authorized,
- checkout_with_items,
- webhooks={checkout_fully_authorized_webhook},
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1500,13 +1410,8 @@ def test_call_checkout_events_incorrect_webhook_event(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_events_triggers_sync_webhook_when_needed(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -1600,30 +1505,14 @@ def test_call_checkout_events_triggers_sync_webhook_when_needed(
tax_delivery = tax_delivery_call.args[0]
assert tax_delivery.webhook_id == tax_webhook.id
- mocked_call_event_including_protected_events.assert_has_calls(
- [
- call(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- ),
- call(plugins_manager.checkout_updated, checkout_with_items, webhooks=set()),
- ]
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_events_skips_tax_webhook_when_not_expired(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -1707,17 +1596,6 @@ def test_call_checkout_events_skips_tax_webhook_when_not_expired(
== WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS
)
- mocked_call_event_including_protected_events.assert_has_calls(
- [
- call(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={checkout_created_webhook},
- ),
- call(plugins_manager.checkout_updated, checkout_with_items, webhooks=set()),
- ]
- )
-
@freeze_time("2023-05-31 12:00:01")
@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@@ -1765,13 +1643,8 @@ def test_call_checkout_events_skip_sync_webhooks_when_async_missing(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_checkout_events_only_async_when_sync_missing(
- mocked_call_event_including_protected_events,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
checkout_with_items,
@@ -1814,16 +1687,6 @@ def test_call_checkout_events_only_async_when_sync_missing(
MessageGroupId="example.com:saleorapptest",
)
assert not mocked_send_webhook_request_sync.called
- mocked_call_event_including_protected_events.assert_has_calls(
- [
- call(
- plugins_manager.checkout_created,
- checkout_with_items,
- webhooks={webhook},
- ),
- call(plugins_manager.checkout_updated, checkout_with_items, webhooks=set()),
- ]
- )
@pytest.mark.parametrize(
@@ -1852,7 +1715,6 @@ def test_transaction_amounts_for_checkout_updated_without_price_recalculation_co
lines, _ = fetch_checkout_lines(checkout)
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- address = checkout.shipping_address or checkout.billing_address
assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
assert checkout.charge_status == CheckoutChargeStatus.NONE
@@ -1863,7 +1725,7 @@ def test_transaction_amounts_for_checkout_updated_without_price_recalculation_co
)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
assert total.gross.amount == Decimal(30)
@@ -1876,64 +1738,3 @@ def test_transaction_amounts_for_checkout_updated_without_price_recalculation_co
checkout.refresh_from_db()
assert checkout.authorize_status == expected_authorize_status
assert checkout.charge_status == expected_charge_status
-
-
-@freeze_time("2023-05-31 12:00:01")
-@patch(
- "saleor.graphql.checkout.types.PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader",
- wraps=PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,
-)
-@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-@patch(
- "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
-)
-@patch(
- "saleor.checkout.actions.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
-def test_call_checkout_events_skips_pregenerated_payloads_in_non_deferred_async_webhooks(
- mocked_call_event_including_protected_events,
- mocked_send_webhook_request_async,
- mocked_send_webhook_request_sync,
- mocked_pregenerated_tax_payload_loader,
- checkout_with_items,
- setup_checkout_webhooks,
- settings,
- django_capture_on_commit_callbacks,
- address,
- caplog,
-):
- # given
- plugins_manager = get_plugins_manager(allow_replica=False)
- checkout_with_items.price_expiration = timezone.now()
-
- # Ensure shipping is set so shipping webhooks are emitted
- checkout_with_items.shipping_address = address
- checkout_with_items.billing_address = address
-
- checkout_with_items.save(
- update_fields=["price_expiration", "shipping_address", "billing_address"]
- )
-
- mocked_send_webhook_request_sync.return_value = []
- setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED)
-
- # when
- with django_capture_on_commit_callbacks(execute=True):
- with freeze_time("2023-06-01 12:00:01"):
- call_checkout_events(
- plugins_manager,
- [
- WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,
- ],
- checkout_with_items,
- )
-
- # then
- # Make sure that we didnt recieve notification about missing payloads for sync webhooks
- # and make sure, that pregenerated payload loaders were called. Pregenerated dataloaders
- # should skip the payload when called inside non-deferred webhook processing. This is skipped
- # as all sync webhooks are called inside the mutation.
- assert mocked_pregenerated_tax_payload_loader.called
- assert "Subscription did not return a payload." not in caplog.text
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 4e5b1793da..36ef00106a 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -9,6 +9,7 @@ from django.utils import timezone
from freezegun import freeze_time
from graphene import Node
from prices import Money, TaxedMoney
+from promise import Promise
from ...checkout.models import CheckoutDelivery
from ...core.prices import quantize_price
@@ -154,6 +155,7 @@ def fetch_kwargs(checkout_with_items, plugins_manager):
),
"manager": plugins_manager,
"lines": lines,
+ "requestor": checkout_with_items.user,
}
@@ -197,7 +199,6 @@ def test_fetch_checkout_data_plugins(
checkout_with_items.price_expiration = timezone.now()
checkout_with_items.save(update_fields=["price_expiration"])
currency = checkout_with_items.currency
- plugins_manager.get_taxes_for_checkout = Mock(return_value=None)
totals, tax_rates = zip(
*[
@@ -231,7 +232,7 @@ def test_fetch_checkout_data_plugins(
)
# when
- fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=True)
+ fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=True).get()
# then
checkout_with_items.refresh_from_db()
@@ -261,7 +262,6 @@ def test_fetch_checkout_data_plugins_allow_sync_webhooks_set_to_false(
checkout_with_items.save(update_fields=["price_expiration"])
currency = checkout_with_items.currency
- plugins_manager.get_taxes_for_checkout = Mock(return_value=None)
previous_subtotal = checkout_with_items.subtotal
previous_shipping_price = checkout_with_items.shipping_price
@@ -292,7 +292,7 @@ def test_fetch_checkout_data_plugins_allow_sync_webhooks_set_to_false(
)
# when
- fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=False)
+ fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=False).get()
# then
assert checkout_with_items.subtotal == previous_subtotal
@@ -343,7 +343,7 @@ def test_fetch_checkout_data_flat_rates(
)
# when
- fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=allow_sync_webhooks)
+ fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=allow_sync_webhooks).get()
checkout.refresh_from_db()
line = checkout.lines.first()
@@ -407,7 +407,8 @@ def test_fetch_checkout_data_flat_rates_with_weighted_shipping_tax(
plugins_manager,
lines,
allow_sync_webhooks=allow_sync_webhooks,
- )
+ requestor=None,
+ ).get()
# then
checkout.refresh_from_db()
@@ -450,7 +451,7 @@ def test_fetch_checkout_data_flat_rates_and_no_tax_calc_strategy(
)
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs).get()
checkout.refresh_from_db()
line = checkout.lines.first()
@@ -571,7 +572,9 @@ def test_set_checkout_base_prices_no_charge_taxes_with_order_promotion(
@freeze_time("2020-12-12 12:00:00")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
def test_fetch_checkout_data_webhooks_success(
+ mocked_get_taxes,
plugins_manager,
fetch_kwargs,
checkout_with_items,
@@ -581,10 +584,10 @@ def test_fetch_checkout_data_webhooks_success(
checkout_with_items.price_expiration = timezone.now()
checkout_with_items.save(update_fields=["price_expiration"])
currency = checkout_with_items.currency
- plugins_manager.get_taxes_for_checkout = Mock(return_value=tax_data)
+ mocked_get_taxes.return_value = Promise.resolve(tax_data)
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs).get()
# then
checkout_with_items.refresh_from_db()
@@ -600,22 +603,32 @@ def test_fetch_checkout_data_webhooks_success(
@freeze_time("2020-12-12 12:00:00")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
def test_fetch_checkout_prices_when_tax_exemption_and_include_taxes_in_prices(
- checkout_with_items_and_shipping, settings
+ mocked_get_taxes, checkout_with_items_and_shipping, settings
):
- """Test tax exemption when taxes are included in prices.
-
- Use PluginSample to test tax exemption.
- PluginSample always return same values of calculated taxes:
-
- shipping_price_net_amount = 50
- shipping_price_gross_amount = 63.20
-
- Each line is treated as line with 3 units where unite gross value = 12.30 and net
- value = 10
- """
+ """Test tax exemption when taxes are included in prices."""
# given
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ expected_total_net = Decimal("10.00") * 3
+ expected_total_gross = Decimal("12.30") * 3
+ expected_shipping_net = Decimal("50.00")
+ expected_shipping_gross = Decimal("63.20")
+
+ mocked_get_taxes.return_value = Promise.resolve(
+ TaxData(
+ shipping_price_net_amount=expected_shipping_net,
+ shipping_price_gross_amount=expected_shipping_gross,
+ shipping_tax_rate=Decimal(23),
+ lines=[
+ TaxLineData(
+ total_net_amount=expected_total_net,
+ total_gross_amount=expected_total_gross,
+ tax_rate=Decimal(23),
+ )
+ for _ in checkout_with_items_and_shipping.lines.all()
+ ],
+ )
+ )
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_items_and_shipping
@@ -631,24 +644,27 @@ def test_fetch_checkout_prices_when_tax_exemption_and_include_taxes_in_prices(
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ ).get()
checkout.refresh_from_db()
# then
+ # Set net and gross to the same value to simulate the moment, when taxes are calculated
+ # for the first time
one_line_total_price = TaxedMoney(
- net=Money("30.0", currency), gross=Money("30.0", currency)
+ net=Money(expected_total_net, currency),
+ gross=Money(expected_total_net, currency),
)
all_lines_total_price = len(lines_info) * one_line_total_price
shipping_price = TaxedMoney(
- net=Money("50.0", currency), gross=Money("50.0", currency)
+ net=Money(expected_shipping_net, currency),
+ gross=Money(expected_shipping_net, currency),
)
for line in checkout.lines.all():
@@ -663,8 +679,9 @@ def test_fetch_checkout_prices_when_tax_exemption_and_include_taxes_in_prices(
@freeze_time("2020-12-12 12:00:00")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_prices(
- checkout_with_items_and_shipping, settings
+ mocked_get_taxes, checkout_with_items_and_shipping, settings
):
"""Test tax exemption when taxes are not included in prices.
@@ -672,7 +689,6 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
tax plugins should be ignored and only net prices should be calculated and returned.
"""
# given
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
manager = get_plugins_manager(allow_replica=False)
checkout = checkout_with_items_and_shipping
@@ -688,14 +704,14 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
lines_info, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines_info, manager)
- fetch_kwargs = {
- "checkout_info": checkout_info,
- "manager": manager,
- "lines": lines_info,
- }
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ ).get()
checkout.refresh_from_db()
# then
@@ -716,11 +732,12 @@ def test_fetch_checkout_prices_when_tax_exemption_and_not_include_taxes_in_price
assert checkout.total == shipping_price + all_lines_total_price
assert checkout.subtotal == all_lines_total_price
+ assert not mocked_get_taxes.called
@freeze_time()
@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")
-@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
def test_fetch_checkout_data_calls_plugin(
mock_get_taxes,
@@ -743,14 +760,13 @@ def test_fetch_checkout_data_calls_plugin(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ ).get()
# then
mock_calculate_checkout_total.assert_called_once()
@@ -759,9 +775,8 @@ def test_fetch_checkout_data_calls_plugin(
@freeze_time()
@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")
-@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
@patch("saleor.checkout.calculations._apply_tax_data")
-@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
def test_fetch_checkout_data_calls_tax_app(
mock_apply_tax_data,
mock_get_taxes,
@@ -775,7 +790,7 @@ def test_fetch_checkout_data_calls_tax_app(
checkout.price_expiration = timezone.now()
checkout.save()
- mock_get_taxes.return_value = tax_data_response
+ mock_get_taxes.return_value = Promise.resolve(tax_data_response)
checkout.channel.tax_configuration.tax_app_id = "test.app"
checkout.channel.tax_configuration.save()
@@ -783,15 +798,14 @@ def test_fetch_checkout_data_calls_tax_app(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- "allow_sync_webhooks": True,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ allow_sync_webhooks=True,
+ ).get()
# then
mock_get_taxes.assert_called_once()
@@ -801,10 +815,9 @@ def test_fetch_checkout_data_calls_tax_app(
@freeze_time()
@patch("saleor.plugins.manager.PluginsManager.calculate_checkout_total")
-@patch("saleor.plugins.manager.PluginsManager.get_taxes_for_checkout")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
@patch("saleor.checkout.calculations._apply_tax_data")
-@override_settings(PLUGINS=["saleor.plugins.tests.sample_plugins.PluginSample"])
-def test_fetch_checkout_data_calls_tax_app_when_allow_sync_webhooks_set_to_false(
+def test_fetch_checkout_data_dont_call_tax_app_when_allow_sync_webhooks_set_to_false(
mock_apply_tax_data,
mock_get_taxes,
mock_calculate_checkout_total,
@@ -828,19 +841,19 @@ def test_fetch_checkout_data_calls_tax_app_when_allow_sync_webhooks_set_to_false
lines_info, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines_info, manager)
- fetch_kwargs = {
- "checkout_info": checkout_info,
- "manager": manager,
- "lines": lines_info,
- "allow_sync_webhooks": False,
- }
assert (
checkout_info.tax_configuration.tax_calculation_strategy
== TaxCalculationStrategy.TAX_APP
)
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ allow_sync_webhooks=False,
+ ).get()
# then
assert checkout_with_items.subtotal == previous_subtotal
@@ -869,14 +882,13 @@ def test_fetch_checkout_data_calls_inactive_plugin(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=checkout.user,
+ ).get()
# then
assert checkout.total.gross.amount > 0
@@ -920,16 +932,15 @@ def test_fetch_checkout_data_flat_rates_shipping_tax_differs_from_default(
checkout.save(update_fields=["shipping_address", "billing_address"])
lines, _ = fetch_checkout_lines(checkout_with_items)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(
- checkout_with_items, lines, plugins_manager
- ),
- "manager": plugins_manager,
- "lines": lines,
- }
# when
- fetch_checkout_data(**fetch_kwargs, allow_sync_webhooks=False)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout_with_items, lines, plugins_manager),
+ manager=plugins_manager,
+ lines=lines,
+ requestor=checkout.user,
+ allow_sync_webhooks=False,
+ ).get()
# then
checkout.refresh_from_db()
@@ -992,12 +1003,12 @@ def test_external_shipping_webhook_it_not_called_during_tax_calculations(
_calculate_and_add_tax(
TaxCalculationStrategy.TAX_APP,
None,
- checkout_with_single_item,
manager,
checkout_info,
checkout_lines,
prices_entered_with_tax=False,
- )
+ requestor=checkout_with_single_item.user,
+ ).get()
# then
assert mock_send_webhook_request_sync.call_count == 1
@@ -1032,7 +1043,6 @@ def test_calculate_and_add_tax_empty_tax_data_logging_address(
"calculate_checkout_shipping": Mock(return_value=zero_money),
"get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
"get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_taxes_for_checkout": Mock(return_value=None),
}
manager = Mock(**manager_methods)
@@ -1043,12 +1053,12 @@ def test_calculate_and_add_tax_empty_tax_data_logging_address(
_calculate_and_add_tax(
TaxCalculationStrategy.TAX_APP,
None,
- checkout,
manager,
checkout_info,
checkout_lines_info,
prices_entered_with_tax=False,
- )
+ requestor=None,
+ ).get()
# then
assert (
@@ -1062,9 +1072,11 @@ def test_calculate_and_add_tax_empty_tax_data_logging_address(
[(True, None), (True, "test.app"), (False, None), (False, "test.app")],
)
@patch.object(logger, "warning")
+@patch("saleor.checkout.webhooks.calculate_taxes.get_taxes")
@patch("saleor.checkout.calculations._set_checkout_base_prices")
def test_fetch_checkout_data_tax_data_with_tax_data_error(
mock_set_base_prices,
+ mocked_get_taxes,
mocked_logger,
prices_entered_with_tax,
tax_app_id,
@@ -1081,6 +1093,8 @@ def test_fetch_checkout_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)
+ mocked_get_taxes.return_value = Promise.reject(returned_tax_error)
+
zero_money = zero_taxed_money(checkout.currency)
manager_methods = {
"calculate_checkout_total": Mock(return_value=zero_money),
@@ -1089,7 +1103,6 @@ def test_fetch_checkout_data_tax_data_with_tax_data_error(
"calculate_checkout_shipping": Mock(return_value=zero_money),
"get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
"get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_taxes_for_checkout": Mock(side_effect=returned_tax_error),
}
manager = Mock(**manager_methods)
@@ -1097,7 +1110,9 @@ def test_fetch_checkout_data_tax_data_with_tax_data_error(
checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
# when
- fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)
+ fetch_checkout_data(
+ checkout_info, manager, checkout_lines_info, force_update=True, requestor=None
+ ).get()
# then
assert checkout_info.checkout.tax_error == error_msg
@@ -1136,7 +1151,6 @@ def test_fetch_checkout_data_tax_data_missing_tax_id_empty_tax_data(
"calculate_checkout_shipping": Mock(return_value=zero_money),
"get_checkout_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
"get_checkout_line_tax_rate": Mock(return_value=Decimal("0.00")),
- "get_taxes_for_checkout": Mock(return_value=None),
}
manager = Mock(**manager_methods)
@@ -1144,7 +1158,9 @@ def test_fetch_checkout_data_tax_data_missing_tax_id_empty_tax_data(
checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
# when
- fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)
+ fetch_checkout_data(
+ checkout_info, manager, checkout_lines_info, force_update=True, requestor=None
+ ).get()
# then
# In case the app identifier is not set, in case of error in tax data, it's skipped.
@@ -1190,7 +1206,9 @@ def test_fetch_order_data_plugin_tax_data_with_negative_values(
checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
# when
- fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)
+ fetch_checkout_data(
+ checkout_info, manager, checkout_lines_info, force_update=True, requestor=None
+ ).get()
# then
assert checkout.tax_error == TaxDataErrorMessage.NEGATIVE_VALUE
@@ -1235,7 +1253,9 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(
checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
# when
- fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)
+ fetch_checkout_data(
+ checkout_info, manager, checkout_lines_info, force_update=True, requestor=None
+ ).get()
# then
assert checkout.tax_error == TaxDataErrorMessage.OVERFLOW
@@ -1244,7 +1264,6 @@ def test_fetch_order_data_plugin_tax_data_price_overflow(
def test_fetch_checkout_with_prior_price_change(
- fetch_kwargs,
checkout_with_items,
):
# given
@@ -1263,14 +1282,13 @@ def test_fetch_checkout_with_prior_price_change(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout_with_items)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout_with_items, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout_with_items, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=None,
+ ).get()
# then
line.refresh_from_db()
@@ -1278,7 +1296,6 @@ def test_fetch_checkout_with_prior_price_change(
def test_fetch_checkout_with_prior_price_none(
- fetch_kwargs,
checkout_with_items,
):
# given
@@ -1295,14 +1312,13 @@ def test_fetch_checkout_with_prior_price_none(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout_with_items)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout_with_items, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
-
# when
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout_with_items, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=None,
+ ).get()
# then
line.refresh_from_db()
@@ -1327,10 +1343,8 @@ def test_fetch_checkout_data_updates_status_for_zero_amount_checkout_with_lines(
# when
fetch_checkout_data(
- checkout_info=checkout_info,
- manager=manager,
- lines=lines,
- )
+ checkout_info=checkout_info, manager=manager, lines=lines, requestor=None
+ ).get()
# then
checkout_with_item_total_0.refresh_from_db()
@@ -1364,7 +1378,6 @@ def test_fetch_checkout_data_considers_gift_cards_balance_when_updating_checkout
lines, _ = fetch_checkout_lines(checkout)
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- address = checkout.shipping_address or checkout.billing_address
assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
assert checkout.charge_status == CheckoutChargeStatus.NONE
@@ -1375,16 +1388,16 @@ def test_fetch_checkout_data_considers_gift_cards_balance_when_updating_checkout
)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
)
assert total.gross.amount == Decimal(30)
# when
fetch_checkout_data(
- checkout_info=checkout_info,
- manager=manager,
- lines=lines,
- )
+ checkout_info=checkout_info, manager=manager, lines=lines, requestor=None
+ ).get()
# then
checkout.refresh_from_db()
@@ -1405,11 +1418,6 @@ def test_fetch_checkout_data_checkout_removed_before_save(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
# when
def delete_checkout(*args, **kwargs):
@@ -1420,7 +1428,12 @@ def test_fetch_checkout_data_checkout_removed_before_save(
with race_condition.RunAfter(
"saleor.checkout.calculations._calculate_and_add_tax", delete_checkout
):
- result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+ result_checkout_info, result_lines_info = fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=None,
+ ).get()
# then
# Check if checkout was deleted.
@@ -1453,11 +1466,6 @@ def test_fetch_checkout_data_checkout_updated_during_price_recalculation(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
expected_email = "[email protected]"
freeze_time_str = "2024-01-01T12:00:00+00:00"
@@ -1472,7 +1480,12 @@ def test_fetch_checkout_data_checkout_updated_during_price_recalculation(
with race_condition.RunAfter(
"saleor.checkout.calculations._calculate_and_add_tax", modify_checkout
):
- result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+ result_checkout_info, result_lines_info = fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=None,
+ ).get()
# then
# Check if prices are recalculated and returned in info objects.
@@ -1505,11 +1518,6 @@ def test_fetch_checkout_data_checkout_deleted_during_discount_recalculation(
manager = get_plugins_manager(allow_replica=False)
lines_info, _ = fetch_checkout_lines(checkout)
- fetch_kwargs = {
- "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
- "manager": manager,
- "lines": lines_info,
- }
# when
def delete_checkout(*args, **kwargs):
@@ -1519,7 +1527,12 @@ def test_fetch_checkout_data_checkout_deleted_during_discount_recalculation(
"saleor.checkout.calculations.recalculate_discounts",
side_effect=delete_checkout,
):
- result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+ result_checkout_info, result_lines_info = fetch_checkout_data(
+ checkout_info=fetch_checkout_info(checkout, lines_info, manager),
+ manager=manager,
+ lines=lines_info,
+ requestor=None,
+ ).get()
# then
# Check if checkout was deleted.
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 6918db7743..a205851a99 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -59,7 +59,6 @@ def test_adding_same_variant(checkout, product):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
== subtotal
)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index ebff99c7af..b2cb2ac824 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -1172,7 +1172,6 @@ def test_recalculate_checkout_discount_with_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
).gross.amount
== discounted_subtotal - voucher_discount
)
@@ -1346,7 +1345,6 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
).gross + Money("10.00", "USD")
checkout.assigned_delivery.save()
@@ -1362,13 +1360,11 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
checkout_subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert checkout_total == checkout_subtotal
@@ -1388,7 +1384,6 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
).gross - Money("10.00", "USD")
checkout.assigned_delivery.save()
@@ -1404,13 +1399,11 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
checkout_subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert checkout_total == checkout_subtotal
@@ -1753,7 +1746,6 @@ def test_is_fully_paid(checkout_with_item, payment_dummy):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = payment_dummy
payment.is_active = True
@@ -1775,7 +1767,6 @@ def test_is_fully_paid_mg_payments(checkout_with_item, payment_dummy):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = payment_dummy
payment.is_active = True
@@ -1805,7 +1796,6 @@ def test_is_fully_paid_partially_paid(checkout_with_item, payment_dummy):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
payment = payment_dummy
payment.is_active = True
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index d808d86815..f2aae6642b 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -685,13 +685,11 @@ def test_create_order_with_gift_card(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross_without_gift_cards = (
subtotal.gross + shipping_price.gross - checkout.discount
@@ -744,7 +742,6 @@ def test_create_order_with_gift_card_partial_use(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
gift_card_balance_before_order = gift_card_used.current_balance_amount
@@ -803,7 +800,6 @@ def test_create_order_with_many_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
gift_cards_balance_before_order = (
gift_card_created_by_staff.current_balance.amount
@@ -873,7 +869,9 @@ def test_create_order_gift_card_bought(
checkout_info = fetch_checkout_info(checkout, lines, manager)
amount = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, customer_user.default_billing_address
+ manager,
+ checkout_info,
+ lines,
).gross.amount
payment_txn_captured.order = None
@@ -892,13 +890,11 @@ def test_create_order_gift_card_bought(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -970,13 +966,11 @@ def test_create_order_gift_card_bought_order_not_captured_gift_cards_not_sent(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -1035,13 +1029,11 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -1094,13 +1086,11 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -1733,7 +1723,7 @@ def test_complete_checkout_checkout_limited_use_voucher_multiple_thread(
voucher_free_shipping.save(update_fields=["usage_limit"])
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
Payment.objects.create(
@@ -1801,7 +1791,7 @@ def test_complete_checkout_checkout_completed_in_the_meantime(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
Payment.objects.create(
@@ -2530,7 +2520,6 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
checkout_with_item,
checkout_delivery,
app,
- address,
payment_dummy,
):
# given
@@ -2549,7 +2538,7 @@ def test_complete_checkout_ensure_prices_are_not_recalculated_in_post_payment_pa
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
calculation_call_count = mocked_get_tax_calculation_strategy_for_checkout.call_count
@@ -2836,8 +2825,8 @@ def test_checkout_complete_with_voucher_0_total(
voucher_percentage.codes.first(),
)
checkout_info, lines = calculations.fetch_checkout_data(
- checkout_info, manager, lines, force_status_update=True
- )
+ checkout_info, manager, lines, force_status_update=True, requestor=None
+ ).get()
channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
channel.allow_unpaid_orders = True
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index 58c77fbdd3..ffcd957a0a 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -6,6 +6,7 @@ import pytest
from django.core.exceptions import ValidationError
from django.test import override_settings
from prices import Money, TaxedMoney
+from promise import Promise
from ...channel import MarkAsPaidStrategy
from ...checkout.models import Checkout, CheckoutLine
@@ -79,13 +80,11 @@ def test_create_order_with_gift_card(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross_without_gift_cards = (
subtotal.gross + shipping_price.gross - checkout.discount
@@ -127,7 +126,6 @@ def test_create_order_with_gift_card_partial_use(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
gift_card_balance_before_order = gift_card_used.current_balance_amount
@@ -180,7 +178,6 @@ def test_create_order_with_many_gift_cards_worth_more_than_total(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
gift_card_2_old_balance = gift_card_2.current_balance.amount
gift_card_2_balance_halved = gift_card_2_old_balance / 2
@@ -248,7 +245,6 @@ def test_create_order_with_many_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
gift_cards_balance_before_order = (
gift_card_created_by_staff.current_balance.amount
@@ -316,13 +312,11 @@ def test_create_order_gift_card_bought(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -395,13 +389,11 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -447,13 +439,11 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
shipping_price = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
total_gross = subtotal.gross + shipping_price.gross - checkout.discount
@@ -976,8 +966,8 @@ def test_create_order_with_voucher_0_total(
manager, checkout_info, lines, voucher_percentage, voucher_code
)
checkout_info, lines = calculations.fetch_checkout_data(
- checkout_info, manager, lines, force_status_update=True
- )
+ checkout_info, manager, lines, force_status_update=True, requestor=None
+ ).get()
assert checkout_info.checkout.total == zero_taxed_money(
checkout_info.checkout.currency
@@ -1027,7 +1017,9 @@ def test_create_order_from_checkout_update_tax_error(
# given
checkout = checkout_with_items_and_shipping
lines, _ = fetch_checkout_lines(checkout)
- _calculate_and_add_tax_mock.side_effect = TaxDataError(TaxDataErrorMessage.EMPTY)
+ _calculate_and_add_tax_mock.return_value = Promise.reject(
+ TaxDataError(TaxDataErrorMessage.EMPTY)
+ )
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager, [])
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
index 891ef42450..4d4b9d9e37 100644
--- a/saleor/checkout/tests/test_tasks.py
+++ b/saleor/checkout/tests/test_tasks.py
@@ -630,18 +630,20 @@ def test_automatic_checkout_completion_transaction_flow(
).exists()
checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
- assert len(caplog.records) == 2
+ assert len(caplog.records) == 3
assert caplog.records[0].message == (
f"Automatic checkout completion triggered for checkout: {checkout_id}."
)
assert caplog.records[0].checkout_id == checkout_id
assert caplog.records[0].levelno == logging.INFO
- assert caplog.records[1].message == (
+ assert "Missing tax configuration for channel" in caplog.records[1].message
+
+ assert caplog.records[2].message == (
f"Automatic checkout completion succeeded for checkout: {checkout_id}."
)
- assert caplog.records[1].checkout_id == checkout_id
- assert caplog.records[1].levelno == logging.INFO
+ assert caplog.records[2].checkout_id == checkout_id
+ assert caplog.records[2].levelno == logging.INFO
def test_automatic_checkout_completion_payment_flow(
@@ -675,18 +677,21 @@ def test_automatic_checkout_completion_payment_flow(
).exists()
checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
- assert len(caplog.records) == 2
+
+ assert len(caplog.records) == 3
assert caplog.records[0].message == (
f"Automatic checkout completion triggered for checkout: {checkout_id}."
)
assert caplog.records[0].checkout_id == checkout_id
assert caplog.records[0].levelno == logging.INFO
- assert caplog.records[1].message == (
+ assert "Missing tax configuration for channel" in caplog.records[1].message
+
+ assert caplog.records[2].message == (
f"Automatic checkout completion succeeded for checkout: {checkout_id}."
)
- assert caplog.records[1].checkout_id == checkout_id
- assert caplog.records[1].levelno == logging.INFO
+ assert caplog.records[2].checkout_id == checkout_id
+ assert caplog.records[2].levelno == logging.INFO
def test_automatic_checkout_completion_missing_checkout(checkout, caplog):
@@ -819,19 +824,21 @@ def test_automatic_checkout_completion_error_raised(
# then
assert Checkout.objects.filter(pk=checkout_pk).exists()
checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)
- assert len(caplog.records) == 2
+ assert len(caplog.records) == 3
assert caplog.records[0].message == (
f"Automatic checkout completion triggered for checkout: {checkout_id}."
)
assert caplog.records[0].checkout_id == checkout_id
assert caplog.records[0].levelno == logging.INFO
- assert caplog.records[1].message == (
+ assert "Missing tax configuration for channel" in caplog.records[1].message
+
+ assert caplog.records[2].message == (
f"Automatic checkout completion failed for checkout: {checkout_id}."
)
- assert caplog.records[1].checkout_id == checkout_id
- assert caplog.records[1].error
- assert caplog.records[1].levelno == logging.WARNING
+ assert caplog.records[2].checkout_id == checkout_id
+ assert caplog.records[2].error
+ assert caplog.records[2].levelno == logging.WARNING
def test_automatic_checkout_completion_missing_lines(
diff --git a/saleor/checkout/tests/webhooks/static_payloads/test_calculate_taxes.py b/saleor/checkout/tests/webhooks/static_payloads/test_calculate_taxes.py
new file mode 100644
index 0000000000..fb5a51c78a
--- /dev/null
+++ b/saleor/checkout/tests/webhooks/static_payloads/test_calculate_taxes.py
@@ -0,0 +1,876 @@
+import json
+from decimal import Decimal
+from unittest.mock import Mock, patch
+
+import graphene
+import pytest
+from prices import Money
+
+from .....core.prices import quantize_price
+from .....discount import DiscountType, RewardValueType
+from .....discount.models import CheckoutDiscount, CheckoutLineDiscount, PromotionRule
+from .....discount.utils.checkout import (
+ create_or_update_discount_objects_from_promotion_for_checkout,
+)
+from .....plugins.manager import get_plugins_manager
+from .....product.models import Product, ProductVariantChannelListing
+from .....product.utils.variant_prices import update_discounted_prices_for_promotion
+from .....product.utils.variants import fetch_variants_for_promotion_rules
+from .....webhook.serializers import serialize_variant_full_name
+from .... import base_calculations
+from ....fetch import fetch_checkout_info, fetch_checkout_lines
+from ....models import CheckoutLine
+from ....utils import add_voucher_to_checkout
+from ....webhooks.calculate_taxes import (
+ generate_checkout_payload_for_tax_calculation,
+ serialize_checkout_lines_for_tax_calculation,
+)
+
+
+def mocked_fetch_checkout():
+ def mocked_fetch_side_effect(
+ checkout_info, manager, lines, address, force_update=False
+ ):
+ return checkout_info, lines
+
+ with patch(
+ "saleor.checkout.calculations.fetch_checkout_data",
+ new=Mock(side_effect=mocked_fetch_side_effect),
+ ) as mocked_fetch:
+ yield mocked_fetch
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_entire_order_voucher(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ voucher,
+):
+ checkout = checkout_with_prices
+ currency = checkout.currency
+
+ voucher.name = "Voucher 5 USD"
+ voucher.save(update_fields=["name"])
+
+ discount_amount = Decimal("5.00")
+ checkout.voucher_code = voucher.code
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = voucher.name
+ checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ shipping_price = str(
+ quantize_price(
+ checkout.assigned_delivery.price.amount,
+ currency,
+ )
+ )
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [{"amount": str(discount_amount), "name": voucher.name}],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.assigned_delivery.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(checkout_info, lines).amount,
+ currency,
+ )
+ ),
+ "shipping_amount": shipping_price,
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ voucher_specific_product_type,
+):
+ checkout = checkout_with_prices
+ currency = checkout.currency
+
+ voucher = voucher_specific_product_type
+ voucher.name = "Voucher 5 USD"
+ voucher.save(update_fields=["name"])
+
+ discount_amount = Decimal("5.00")
+ checkout.voucher_code = voucher.code
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = voucher.name
+ checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ shipping_price = str(
+ quantize_price(
+ checkout.assigned_delivery.price.amount,
+ currency,
+ )
+ )
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.assigned_delivery.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(checkout_info, lines).amount,
+ currency,
+ )
+ ),
+ "shipping_amount": shipping_price,
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_shipping_voucher(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_items_and_shipping,
+ prices_entered_with_tax,
+ voucher_shipping_type,
+ customer_user,
+):
+ checkout = checkout_with_items_and_shipping
+ checkout.user = customer_user
+ currency = checkout.currency
+ voucher = voucher_shipping_type
+ voucher.countries = []
+ voucher.save(update_fields=["countries"])
+
+ shipping_price = checkout.assigned_delivery.price.amount
+ assert shipping_price == Decimal(10)
+
+ voucher_discount_amount = Decimal(3)
+ listing = voucher.channel_listings.first()
+ listing.discount_value = voucher_discount_amount
+ listing.save(update_fields=["discount_value"])
+ expected_shipping_price = quantize_price(
+ shipping_price - voucher_discount_amount, currency
+ )
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ add_voucher_to_checkout(
+ manager, checkout_info, lines, voucher, voucher.codes.first()
+ )
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {},
+ "shipping_name": checkout.assigned_delivery.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"key": "value"},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(checkout_info, lines).amount,
+ currency,
+ )
+ ),
+ "shipping_amount": str(expected_shipping_price),
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_order_discount(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ order_promotion_rule,
+):
+ checkout = checkout_with_prices
+ rule = order_promotion_rule
+ currency = checkout.currency
+
+ discount_amount = Decimal("5.00")
+ CheckoutDiscount.objects.create(
+ checkout=checkout,
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=rule.reward_value_type,
+ value=rule.reward_value,
+ amount_value=discount_amount,
+ currency=checkout.currency,
+ )
+
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = rule.name
+ checkout.save(update_fields=["discount_amount", "discount_name"])
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ subtotal_price = Money(0, currency)
+ for line_info in lines:
+ variant = line_info.variant
+ variant_listing = line_info.channel_listing
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price += unit_price * line_info.line.quantity
+ shipping_price = quantize_price(
+ checkout.assigned_delivery.price.amount,
+ currency,
+ )
+ total_price_amount = subtotal_price.amount + shipping_price
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [{"amount": str(discount_amount), "name": rule.name}],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.assigned_delivery.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ total_price_amount,
+ currency,
+ )
+ ),
+ "shipping_amount": str(shipping_price),
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_gift_promotion(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ gift_promotion_rule,
+):
+ checkout = checkout_with_prices
+ currency = checkout.currency
+
+ variants = gift_promotion_rule.gifts.all()
+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
+ top_price, variant_id = max(
+ variant_listings.values_list("discounted_price_amount", "variant")
+ )
+ variant_listing = [
+ listing for listing in variant_listings if listing.variant_id == variant_id
+ ][0]
+
+ line = CheckoutLine.objects.create(
+ checkout=checkout,
+ quantity=1,
+ variant_id=variant_id,
+ is_gift=True,
+ currency="USD",
+ undiscounted_unit_price_amount=variant_listing.price_amount,
+ )
+
+ CheckoutLineDiscount.objects.create(
+ line=line,
+ promotion_rule=gift_promotion_rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=top_price,
+ amount_value=top_price,
+ currency=checkout.channel.currency_code,
+ )
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+
+ # then
+ subtotal_price = Money(0, currency)
+ for line_info in lines:
+ if line_info.line.is_gift:
+ continue
+ variant = line_info.variant
+ variant_listing = line_info.channel_listing
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price += unit_price * line_info.line.quantity
+ shipping_price = quantize_price(
+ checkout.assigned_delivery.price.amount,
+ currency,
+ )
+ total_price_amount = subtotal_price.amount + shipping_price
+ assert payload["discounts"] == []
+ assert payload["total_amount"] == str(
+ quantize_price(
+ total_price_amount,
+ currency,
+ )
+ )
+
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+@patch(
+ "saleor.checkout.webhooks.calculate_taxes.serialize_checkout_lines_for_tax_calculation"
+)
[email protected]("prices_entered_with_tax", [True, False])
+def test_generate_checkout_payload_for_tax_calculation_no_discount(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ prices_entered_with_tax,
+ order_promotion_rule,
+):
+ checkout = checkout_with_prices
+ rule = order_promotion_rule
+ currency = checkout.currency
+
+ discount_amount = 0
+ checkout.discount_amount = discount_amount
+ checkout.discount_name = rule.name
+ checkout.save(update_fields=["discount_amount", "discount_name"])
+
+ tax_configuration = checkout.channel.tax_configuration
+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax
+ tax_configuration.save(update_fields=["prices_entered_with_tax"])
+ tax_configuration.country_exceptions.all().delete()
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ subtotal_price = Money(0, currency)
+ for line_info in lines:
+ variant = line_info.variant
+ variant_listing = line_info.channel_listing
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price += unit_price * line_info.line.quantity
+ shipping_price = quantize_price(
+ checkout.assigned_delivery.price.amount,
+ currency,
+ )
+ total_price_amount = subtotal_price.amount + shipping_price
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [],
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.assigned_delivery.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ total_price_amount,
+ currency,
+ )
+ ),
+ "shipping_amount": str(shipping_price),
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ )
+
+
+ ("charge_taxes", "prices_entered_with_tax"),
+ [(False, False), (False, True), (True, False), (True, True)],
+)
+def test_serialize_checkout_lines_for_tax_calculation(
+ checkout_with_prices, charge_taxes, prices_entered_with_tax
+):
+ # We should be sure that we always sends base prices to tax app.
+ # We shouldn't use previously calculated prices because they can be
+ # changed by tax app due to e.g.
+ # Checkout discount
+ # Propagating shipping tax to lines.
+
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ tax_configuration = checkout_info.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()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines
+ )
+
+ # then
+ for data, line_info in zip(checkout_lines_data, lines, strict=False):
+ line = line_info.line
+ variant = line.variant
+ product = variant.product
+
+ total_price = base_calculations.calculate_base_line_total_price(
+ line_info
+ ).amount
+ unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
+
+ assert data == {
+ "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": charge_taxes,
+ "full_name": serialize_variant_full_name(variant),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price,
+ "total_amount": total_price,
+ }
+ assert len(checkout_lines_data) == len(list(lines))
+
+
+def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
+ checkout_with_prices, promotion_rule, product_list, product
+):
+ # given
+ checkout = checkout_with_prices
+ product_list.append(product)
+ promotion_rule.catalogue_predicate = {
+ "productPredicate": {
+ "ids": [
+ graphene.Node.to_global_id("Product", product.id)
+ for product in product_list
+ ]
+ },
+ }
+ promotion_rule.save(update_fields=["catalogue_predicate"])
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
+
+ tax_configuration = checkout_info.tax_configuration
+ tax_configuration.country_exceptions.all().delete()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines
+ )
+
+ # then
+ for data, line_info in zip(checkout_lines_data, lines, strict=False):
+ line = line_info.line
+ variant = line.variant
+ product = variant.product
+
+ total_price = base_calculations.calculate_base_line_total_price(
+ line_info
+ ).amount
+ unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
+
+ assert data == {
+ "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": tax_configuration.charge_taxes,
+ "full_name": serialize_variant_full_name(variant),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price,
+ "total_amount": total_price,
+ }
+
+ discount = line_info.discounts[0]
+ assert discount.type == DiscountType.PROMOTION
+ undiscounted_unit_price = variant.get_base_price(
+ line_info.channel_listing,
+ line_info.line.price_override,
+ ).amount
+ assert unit_price < undiscounted_unit_price
+
+ assert len(checkout_lines_data) == len(list(lines))
+
+
+def test_serialize_checkout_lines_for_tax_calculation_with_order_discount(
+ checkout_with_item_and_order_discount, product
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ tax_configuration = checkout_info.tax_configuration
+ tax_configuration.country_exceptions.all().delete()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines
+ )
+
+ # then
+ line_info = lines[0]
+ line = line_info.line
+ variant = line.variant
+ product = variant.product
+
+ unit_price = variant.get_price(
+ channel_listing=line_info.channel_listing,
+ )
+ total_price_amount = (unit_price * line.quantity).amount
+
+ line_data = checkout_lines_data[0]
+ # the line data shouldn't include order promotion discount
+ assert line_data == {
+ "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": tax_configuration.charge_taxes,
+ "full_name": serialize_variant_full_name(variant),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price.amount,
+ "total_amount": total_price_amount,
+ }
+
+
+def test_serialize_checkout_lines_for_tax_calculation_with_gift_promotion(
+ checkout_with_item_and_gift_promotion, product
+):
+ # given
+ checkout = checkout_with_item_and_gift_promotion
+
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ tax_configuration = checkout_info.tax_configuration
+ tax_configuration.country_exceptions.all().delete()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines
+ )
+
+ # then
+ line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]
+ line = line_info.line
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ variant = line.variant
+ product = variant.product
+
+ unit_price = variant.get_price(
+ channel_listing=line_info.channel_listing,
+ )
+ total_price_amount = (unit_price * line.quantity).amount
+
+ line_data = [
+ line_data for line_data in checkout_lines_data if line_data["id"] == line_id
+ ][0]
+ assert line_data == {
+ "id": line_id,
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": tax_configuration.charge_taxes,
+ "full_name": serialize_variant_full_name(variant),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price.amount,
+ "total_amount": total_price_amount,
+ }
+ gift_info = [line_info for line_info in lines if line_info.line.is_gift][0]
+ gift_line = gift_info.line
+ gift_line_id = graphene.Node.to_global_id("CheckoutLine", gift_info.line.pk)
+ gift_line_data = [
+ line_data
+ for line_data in checkout_lines_data
+ if line_data["id"] == gift_line_id
+ ][0]
+ assert gift_line_data == {
+ "id": gift_line_id,
+ "sku": gift_line.variant.sku,
+ "quantity": 1,
+ "charge_taxes": tax_configuration.charge_taxes,
+ "full_name": serialize_variant_full_name(gift_line.variant),
+ "product_name": gift_line.variant.product.name,
+ "variant_name": gift_line.variant.name,
+ "variant_id": graphene.Node.to_global_id(
+ "ProductVariant", gift_line.variant.pk
+ ),
+ "product_metadata": gift_line.variant.product.metadata,
+ "product_type_metadata": gift_line.variant.product.product_type.metadata,
+ "unit_amount": Decimal("0.00"),
+ "total_amount": Decimal("0.00"),
+ }
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/checkout/tests/webhooks/subscriptions/test_calculate_taxes.py
similarity index 94%
rename from saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
rename to saleor/checkout/tests/webhooks/subscriptions/test_calculate_taxes.py
index e78d2036d6..43fabb6717 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/checkout/tests/webhooks/subscriptions/test_calculate_taxes.py
@@ -4,12 +4,12 @@ from unittest.mock import ANY
import pytest
from freezegun import freeze_time
-from ....discount.models import PromotionRule
-from ....graphql.core.utils import to_global_id_or_none
-from ....tax import TaxableObjectDiscountType
-from ...event_types import WebhookEventSyncType
-from ...models import Webhook
-from ...transport.synchronous.transport import (
+from .....discount.models import PromotionRule
+from .....graphql.core.utils import to_global_id_or_none
+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,
)
@@ -239,35 +239,6 @@ def test_checkout_calculate_taxes_with_free_shipping_voucher(
}
-@freeze_time("2020-03-18 12:00:00")
-def test_checkout_calculate_taxes_with_pregenerated_payload(
- checkout_with_voucher_free_shipping,
- tax_app,
-):
- # given
- checkout = checkout_with_voucher_free_shipping
- webhook = Webhook.objects.create(
- name="Webhook",
- app=tax_app,
- target_url="http://www.example.com/any",
- subscription_query=TAXES_SUBSCRIPTION_QUERY,
- )
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- webhook.events.create(event_type=event_type)
- expected_payload = {"payload": "test"}
-
- # when
- deliveries = create_delivery_for_subscription_sync_event(
- event_type,
- checkout,
- webhook,
- pregenerated_payload=expected_payload,
- )
-
- # then
- assert json.loads(deliveries.payload.get_payload()) == expected_payload
-
-
@freeze_time("2020-03-18 12:00:00")
def test_checkout_calculate_taxes_with_entire_order_voucher(
checkout_with_voucher,
diff --git a/saleor/checkout/tests/webhooks/test_calculate_taxes.py b/saleor/checkout/tests/webhooks/test_calculate_taxes.py
new file mode 100644
index 0000000000..7c67fa0318
--- /dev/null
+++ b/saleor/checkout/tests/webhooks/test_calculate_taxes.py
@@ -0,0 +1,257 @@
+import json
+from unittest import mock
+from unittest.mock import ANY
+
+import pytest
+from promise import Promise
+
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.webhooks import calculate_taxes as checkout_calculate_taxes
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery
+from ....core.taxes import TaxDataError
+from ....plugins.manager import get_plugins_manager
+from ....tax.webhooks.parser import parse_tax_data
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook, WebhookEvent
+
+
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_get_taxes_no_permission(
+ mock_request,
+ checkout,
+):
+ # given
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines, get_plugins_manager(allow_replica=False)
+ )
+ app_identifier = None
+
+ # when
+ tax_data = checkout_calculate_taxes.get_taxes(
+ checkout_info, lines, app_identifier
+ ).get()
+
+ # then
+ assert mock_request.call_count == 0
+ assert tax_data is None
+
+
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
+)
+def test_get_taxes_with_sync_subscription(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = tax_data_response
+ mock_generate_payload.return_value = Promise.resolve(expected_payload)
+ webhook = tax_app.webhooks.get(name="tax-webhook-1")
+ webhook.subscription_query = subscription_query
+ webhook.save(update_fields=["subscription_query"])
+ app_identifier = None
+
+ # when
+ tax_data = checkout_calculate_taxes.get_taxes(
+ checkout_info, [], app_identifier
+ ).get()
+
+ # then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ subscribable_object=checkout,
+ subscription_query=subscription_query,
+ request=ANY, # SaleorContext,
+ )
+ 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.CHECKOUT_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ tax_data_response,
+ checkout.lines.count(),
+ )
+
+
+def test_get_taxes_with_app_identifier_app_missing(checkout_info):
+ # given
+ app_identifier = "missing_app"
+
+ # when & then
+ with pytest.raises(TaxDataError, match="Configured tax app doesn't exist."):
+ checkout_calculate_taxes.get_taxes(
+ checkout_info, checkout_info.lines, app_identifier
+ ).get()
+
+
+def test_get_taxes_with_app_identifier_webhook_is_missing(checkout_info, app):
+ # when & then
+ with pytest.raises(
+ TaxDataError,
+ match="Configured tax app's webhook for taxes calculation doesn't exists.",
+ ):
+ checkout_calculate_taxes.get_taxes(
+ checkout_info, checkout_info.lines, app.identifier
+ ).get()
+
+
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
+)
+def test_get_taxes_with_app_identifier_invalid_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ tax_data_response_factory,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = tax_data_response_factory(shipping_tax_rate=-10)
+ mock_generate_payload.return_value = Promise.resolve(expected_payload)
+ 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
+ with pytest.raises(TaxDataError):
+ checkout_calculate_taxes.get_taxes(checkout_info, [], app_identifier).get()
+
+
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
+)
+def test_get_taxes_with_app_identifier(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = tax_data_response
+ mock_generate_payload.return_value = Promise.resolve(expected_payload)
+ 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 = checkout_calculate_taxes.get_taxes(
+ checkout_info, [], app_identifier
+ ).get()
+
+ # then
+ mock_generate_payload.assert_called_once_with(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ subscribable_object=checkout,
+ subscription_query=subscription_query,
+ request=ANY, # SaleorContext,
+ )
+ 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.CHECKOUT_CALCULATE_TAXES
+ assert delivery.webhook == webhook
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ tax_data_response,
+ checkout.lines.count(),
+ )
+
+
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"
+)
+def test_get_taxes_with_app_identifier_empty_response(
+ mock_generate_payload,
+ mock_request,
+ mock_fetch,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ expected_payload = {"taxBase": {"currency": "USD"}}
+ checkout_info = fetch_checkout_info(
+ checkout, [], get_plugins_manager(allow_replica=False)
+ )
+ mock_request.return_value = None
+ mock_generate_payload.return_value = Promise.resolve(expected_payload)
+ 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):
+ checkout_calculate_taxes.get_taxes(checkout_info, [], app_identifier).get()
+
+
+def tax_checkout_webhooks(tax_app):
+ tax_app.webhooks.all().delete()
+ webhooks = [
+ Webhook(
+ name=f"Tax checkout webhook no {i}",
+ app=tax_app,
+ target_url=f"https://www.example.com/tax-checkout-{i}",
+ )
+ for i in range(3)
+ ]
+ Webhook.objects.bulk_create(webhooks)
+ WebhookEvent.objects.bulk_create(
+ WebhookEvent(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ webhook=webhook,
+ )
+ for webhook in webhooks
+ )
+
+ return list(
+ Webhook.objects.filter(
+ events__event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ )
+ )
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 0e2f157d0c..75042dd3aa 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -867,12 +867,10 @@ def is_fully_paid(
checkout = checkout_info.checkout
payments = [payment for payment in checkout.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
- address = checkout_info.shipping_address or checkout_info.billing_address
checkout_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
database_connection_name=database_connection_name,
)
checkout_total = max(
diff --git a/saleor/checkout/webhooks/calculate_taxes.py b/saleor/checkout/webhooks/calculate_taxes.py
new file mode 100644
index 0000000000..acefac968a
--- /dev/null
+++ b/saleor/checkout/webhooks/calculate_taxes.py
@@ -0,0 +1,188 @@
+import logging
+from typing import TYPE_CHECKING, Any, Union
+
+import graphene
+from promise import Promise
+
+from ...app.models import App
+from ...core.db.connection import allow_writer
+from ...core.prices import quantize_price
+from ...core.taxes import TaxData
+from ...discount.utils.voucher import is_order_level_voucher
+from ...tax.utils import get_charge_taxes_for_checkout
+from ...tax.webhooks import shared
+from ...webhook import traced_payload_generator
+from ...webhook.event_types import WebhookEventSyncType
+from ...webhook.payload_serializers import PayloadSerializer
+from ...webhook.serializers import (
+ serialize_variant_full_name,
+)
+from .. import base_calculations
+from ..utils import get_checkout_metadata
+
+if TYPE_CHECKING:
+ from ...account.models import User
+ from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo
+
+logger = logging.getLogger(__name__)
+
+ADDRESS_FIELDS = (
+ "first_name",
+ "last_name",
+ "company_name",
+ "street_address_1",
+ "street_address_2",
+ "city",
+ "city_area",
+ "postal_code",
+ "country",
+ "country_area",
+ "phone",
+)
+CHANNEL_FIELDS = ("slug", "currency_code")
+
+
+def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> dict[str, Any]:
+ line_id = graphene.Node.to_global_id("CheckoutLine", line_info.line.pk)
+ variant = line_info.variant
+ product = line_info.product
+ return {
+ "id": line_id,
+ "sku": variant.sku,
+ "variant_id": variant.get_global_id(),
+ "quantity": line_info.line.quantity,
+ "full_name": serialize_variant_full_name(variant, product=product),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "product_metadata": line_info.product.metadata,
+ "product_type_metadata": line_info.product_type.metadata,
+ }
+
+
+def serialize_checkout_lines_for_tax_calculation(
+ checkout_info: "CheckoutInfo",
+ lines: list["CheckoutLineInfo"],
+) -> list[dict]:
+ charge_taxes = get_charge_taxes_for_checkout(checkout_info)
+ return [
+ {
+ **_get_checkout_line_payload_data(line_info),
+ "charge_taxes": charge_taxes,
+ "unit_amount": quantize_price(
+ base_calculations.calculate_base_line_unit_price(line_info).amount,
+ checkout_info.checkout.currency,
+ ),
+ "total_amount": quantize_price(
+ base_calculations.calculate_base_line_total_price(line_info).amount,
+ checkout_info.checkout.currency,
+ ),
+ }
+ for line_info in lines
+ ]
+
+
+@allow_writer()
+@traced_payload_generator
+def generate_checkout_payload_for_tax_calculation(
+ checkout_info: "CheckoutInfo",
+ lines: list["CheckoutLineInfo"],
+):
+ checkout = checkout_info.checkout
+ tax_configuration = checkout_info.tax_configuration
+ prices_entered_with_tax = tax_configuration.prices_entered_with_tax
+
+ serializer = PayloadSerializer()
+
+ checkout_fields = ("currency",)
+
+ # Prepare checkout data
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ total_amount = quantize_price(
+ base_calculations.base_checkout_total(checkout_info, lines).amount,
+ checkout.currency,
+ )
+
+ # Prepare user data
+ user = checkout_info.user
+ user_id = None
+ user_public_metadata = {}
+ if user:
+ user_id = graphene.Node.to_global_id("User", user.id)
+ user_public_metadata = user.metadata
+
+ # order promotion discount and entire_order voucher discount with
+ # apply_once_per_order set to False is not already included in the total price
+ discounted_object_promotion = bool(checkout_info.discounts)
+ discount_not_included = discounted_object_promotion or is_order_level_voucher(
+ checkout_info.voucher
+ )
+ if not checkout.discount_amount:
+ discounts = []
+ else:
+ discount_amount = quantize_price(checkout.discount_amount, checkout.currency)
+ discount_name = checkout.discount_name
+ discounts = (
+ [{"name": discount_name, "amount": discount_amount}]
+ if discount_amount and discount_not_included
+ else []
+ )
+
+ # Prepare shipping data
+ assigned_delivery = checkout.assigned_delivery
+ shipping_method_name = None
+ if assigned_delivery:
+ shipping_method_name = assigned_delivery.name
+ shipping_method_amount = quantize_price(
+ base_calculations.base_checkout_delivery_price(checkout_info, lines).amount,
+ checkout.currency,
+ )
+
+ # Prepare line data
+ lines_dict_data = serialize_checkout_lines_for_tax_calculation(checkout_info, lines)
+
+ checkout_data = serializer.serialize(
+ [checkout],
+ fields=checkout_fields,
+ pk_field_name="token",
+ additional_fields={
+ "channel": (lambda c: c.channel, CHANNEL_FIELDS),
+ "address": (lambda _: address, ADDRESS_FIELDS),
+ },
+ extra_dict_data={
+ "user_id": user_id,
+ "user_public_metadata": user_public_metadata,
+ "included_taxes_in_prices": prices_entered_with_tax,
+ "total_amount": total_amount,
+ "shipping_amount": shipping_method_amount,
+ "shipping_name": shipping_method_name,
+ "discounts": discounts,
+ "lines": lines_dict_data,
+ "metadata": (
+ lambda c=checkout: (
+ get_checkout_metadata(c).metadata # type: ignore[union-attr]
+ if hasattr(c, "metadata_storage")
+ else {}
+ )
+ ),
+ },
+ )
+ return checkout_data
+
+
+def get_taxes(
+ checkout_info: "CheckoutInfo",
+ lines: list["CheckoutLineInfo"],
+ app_identifier: str | None,
+ requestor: Union["App", "User", None] = None,
+) -> Promise[TaxData | None]:
+ return shared.get_taxes(
+ taxable_object=checkout_info.checkout,
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ app_identifier=app_identifier,
+ static_payload=generate_checkout_payload_for_tax_calculation(
+ checkout_info, lines
+ ),
+ lines_count=len(lines),
+ requestor=requestor,
+ )
diff --git a/saleor/core/utils/events.py b/saleor/core/utils/events.py
index 6d07f07d4a..4a268c7692 100644
--- a/saleor/core/utils/events.py
+++ b/saleor/core/utils/events.py
@@ -1,9 +1,6 @@
from django.db import transaction
-from ...checkout.fetch import CheckoutInfo
-from ...checkout.models import Checkout
from ...webhook.event_types import WebhookEventAsyncType
-from ...webhook.models import Webhook
def get_is_deferred_payload(event_name: str) -> bool:
@@ -19,118 +16,13 @@ def get_is_deferred_payload(event_name: str) -> bool:
)
-def any_webhook_has_subscription(
- events: list[str], webhook_event_map: dict[str, set["Webhook"]]
-) -> bool:
- event_has_subscription = False
- for event in events:
- event_has_subscription = any(
- bool(webhook.subscription_query)
- for webhook in webhook_event_map.get(event, [])
- )
- if event_has_subscription:
- break
- return event_has_subscription
-
-
-def any_webhook_is_active_for_events(
- events: list[str], webhook_event_map: dict[str, set["Webhook"]]
-) -> bool:
- """Check if any webhook is active for given events."""
-
- active_webhook_events = {
- event for event, webhooks in webhook_event_map.items() if webhooks
- }
- if not active_webhook_events.intersection(events):
- return False
- return True
-
-
-def _validate_event_name(event_name, webhook_event_map):
- is_async_event = event_name in WebhookEventAsyncType.ALL
- if not is_async_event:
- raise ValueError(f"Event {event_name} is not an async event.")
-
- if event_name not in webhook_event_map:
- raise ValueError(f"Event {event_name} not found in webhook_event_map.")
-
-
-def _validate_webhook_event_map(webhook_event_map, possible_sync_events):
- missing_possible_sync_events_in_map = set(possible_sync_events).difference(
- webhook_event_map.keys()
- )
- if missing_possible_sync_events_in_map:
- raise ValueError(
- f"Event {missing_possible_sync_events_in_map} not found in webhook_event_map."
- )
-
-
-def webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name: str,
- webhook_event_map: dict[str, set["Webhook"]],
- possible_sync_events: list[str],
-) -> bool:
- """Check if calling the event requires additional actions.
-
- In case of having active webhook with the `event_name`, the function will return
- True, when any sync from `possible_sync_events`'s webhooks are active. `True`
- means that sync webhook should be triggered first, before calling async webhook.
- """
- _validate_event_name(event_name, webhook_event_map)
- _validate_webhook_event_map(webhook_event_map, possible_sync_events)
-
- is_deferred_payload = get_is_deferred_payload(event_name)
- if is_deferred_payload:
- return False
-
- if not webhook_event_map[event_name] and not webhook_event_map.get(
- WebhookEventAsyncType.ANY
- ):
- return False
-
- if not any_webhook_is_active_for_events(possible_sync_events, webhook_event_map):
- return False
-
- async_webhooks_have_subscriptions = any_webhook_has_subscription(
- [event_name], webhook_event_map
- )
- if not async_webhooks_have_subscriptions:
- return False
-
- sync_events_have_subscriptions = any_webhook_has_subscription(
- possible_sync_events, webhook_event_map
- )
- if not sync_events_have_subscriptions:
- return False
- return True
-
-
-def call_event_including_protected_events(func_obj, *func_args, **func_kwargs):
- """Call event without additional validation.
+def call_event(func_obj, *func_args, **func_kwargs):
+ """Call webhook event with given args.
- This function triggers the event without any additional validation. It should be
- used when all additional actions are already handled. Additional actions like
- triggering all existing sync webhooks before calling async webhooks.
+ Ensures that in atomic transaction event is called on_commit.
"""
connection = transaction.get_connection()
if connection.in_atomic_block:
transaction.on_commit(lambda: func_obj(*func_args, **func_kwargs))
else:
func_obj(*func_args, **func_kwargs)
-
-
-def call_event(func_obj, *func_args, **func_kwargs):
- """Call webhook event with given args.
-
- Ensures that in atomic transaction event is called on_commit.
- """
- is_protected_instance = any(
- isinstance(arg, Checkout | CheckoutInfo) for arg in func_args
- )
- func_obj_self = getattr(func_obj, "__self__", None)
- is_plugin_manager_method = "PluginsManager" in str(
- getattr(func_obj_self, "__class__", "")
- )
- if is_protected_instance and is_plugin_manager_method:
- raise NotImplementedError("`call_event` doesn't support checkout events.")
- call_event_including_protected_events(func_obj, *func_args, **func_kwargs)
diff --git a/saleor/core/utils/tests/test_events.py b/saleor/core/utils/tests/test_events.py
index 6cd1b18ef9..68641035e7 100644
--- a/saleor/core/utils/tests/test_events.py
+++ b/saleor/core/utils/tests/test_events.py
@@ -1,333 +1,26 @@
-from unittest.mock import patch
+from unittest import mock
-import pytest
+from django.db import transaction
-from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from ....webhook.utils import get_webhooks_for_multiple_events
-from ..events import (
- call_event,
- call_event_including_protected_events,
- webhook_async_event_requires_sync_webhooks_to_trigger,
-)
+from ..events import call_event
-def test_call_event_cannot_be_used_with_checkout_info_object(
- checkout_info, plugins_manager
-):
- with pytest.raises(NotImplementedError):
- call_event(plugins_manager.checkout_updated, checkout_info)
-
-
-def test_call_event_cannot_be_used_with_checkout_object(checkout, plugins_manager):
- with pytest.raises(NotImplementedError):
- call_event(plugins_manager.checkout_updated, checkout)
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_requires_event_in_map():
- # given
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = {}
-
- # when & then
- with pytest.raises(
- ValueError, match=f"Event {event_name} not found in webhook_event_map."
- ):
- webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, []
- )
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_not_async_event():
- # given
- event_name = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- webhook_event_map = {}
-
- # when & then
- with pytest.raises(ValueError, match=f"Event {event_name} is not an async event."):
- webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, []
- )
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_no_webhooks():
- # given
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert not should_trigger
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_async_webhook(
- webhook, permission_manage_checkouts
-):
- # given
- webhook.events.create(event_type=WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
- webhook.app.permissions.set([permission_manage_checkouts])
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert not should_trigger
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_when_sync_webhook_active(
- webhook, permission_manage_checkouts, setup_checkout_webhooks
-):
- # given
- different_event = WebhookEventAsyncType.ORDER_EXPIRED
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(different_event)
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert not should_trigger
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_webhooks_active(
- setup_checkout_webhooks,
-):
- # given
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(event_name)
-
- webhook_event_map = get_webhooks_for_multiple_events(
- [event_name, WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert should_trigger
-
-
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_missing_event_in_map():
- # given
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- ]
- )
- expected_failure_events = {WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES}
-
- # when & then
- with pytest.raises(
- ValueError,
- match=(f"Event {expected_failure_events} not found in webhook_event_map."),
- ):
- webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name,
- webhook_event_map,
- [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
- )
-
-
-@patch("saleor.plugins.manager.PluginsManager.checkout_created")
-def test_call_event_including_protected_events(
- mocked_checkout_created,
- checkout_with_items,
[email protected](transaction, "get_connection", wraps=transaction.get_connection)
+def test_call_event_triggers_provided_method(
+ mocked_transaction,
+ checkout_info,
plugins_manager,
- webhook,
django_capture_on_commit_callbacks,
-):
- # when
- with django_capture_on_commit_callbacks(execute=True):
- call_event_including_protected_events(
- plugins_manager.checkout_created, checkout_with_items, webhooks=[webhook]
- )
-
- # then
- mocked_checkout_created.assert_called_once_with(
- checkout_with_items, webhooks=[webhook]
- )
-
-
[email protected]("subscription_query", ["", None])
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_for_event(
- setup_checkout_webhooks, subscription_query, webhook, permission_manage_checkouts
):
# given
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
-
- checkout_created_webhook.subscription_query = subscription_query
- checkout_created_webhook.save(update_fields=["subscription_query"])
-
- webhook.events.create(event_type=WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
- webhook.app.permissions.set([permission_manage_checkouts])
- webhook.subscription_query = subscription_query
- webhook.save(update_fields=["subscription_query"])
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
+ mocked_fun = mock.Mock()
+ expected_args = [1, 2]
+ expected_kwargs = {"one": True, "two": False}
# when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert not should_trigger
-
-
[email protected]("subscription_query", ["", None])
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_single_webhook(
- setup_checkout_webhooks, subscription_query, webhook, permission_manage_checkouts
-):
- # given
- webhook.events.create(event_type=WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
- webhook.app.permissions.set([permission_manage_checkouts])
- webhook.subscription_query = subscription_query
- webhook.save(update_fields=["subscription_query"])
-
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert should_trigger
-
-
[email protected]("subscription_query", ["", None])
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_for_async_events(
- setup_checkout_webhooks, subscription_query
-):
- # given
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
- shipping_webhook.subscription_query = subscription_query
- shipping_webhook.save(update_fields=["subscription_query"])
- tax_webhook.subscription_query = subscription_query
- tax_webhook.save(update_fields=["subscription_query"])
- shipping_filter_webhook.subscription_query = subscription_query
- shipping_filter_webhook.save(update_fields=["subscription_query"])
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
-
- # then
- assert not should_trigger
-
-
[email protected]("subscription_query", ["", None])
-def test_webhook_async_event_requires_sync_webhooks_to_trigger_no_subscription_for_single_async_event(
- setup_checkout_webhooks, subscription_query
-):
- # given
- (
- tax_webhook,
- shipping_webhook,
- shipping_filter_webhook,
- checkout_created_webhook,
- ) = setup_checkout_webhooks(WebhookEventAsyncType.CHECKOUT_FULLY_PAID)
- shipping_filter_webhook.subscription_query = subscription_query
- shipping_filter_webhook.save(update_fields=["subscription_query"])
-
- event_name = WebhookEventAsyncType.CHECKOUT_FULLY_PAID
- webhook_event_map = get_webhooks_for_multiple_events(
- [
- WebhookEventAsyncType.CHECKOUT_FULLY_PAID,
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- ]
- )
-
- # when
-
- should_trigger = webhook_async_event_requires_sync_webhooks_to_trigger(
- event_name, webhook_event_map, [WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
- )
+ with django_capture_on_commit_callbacks(execute=True):
+ call_event(mocked_fun, *expected_args, **expected_kwargs)
# then
- assert should_trigger
+ assert mocked_transaction.called
+ mocked_fun.assert_called_with(*expected_args, **expected_kwargs)
diff --git a/saleor/graphql/account/tests/queries/test_me.py b/saleor/graphql/account/tests/queries/test_me.py
index 0a9947e151..5f12f48fd5 100644
--- a/saleor/graphql/account/tests/queries/test_me.py
+++ b/saleor/graphql/account/tests/queries/test_me.py
@@ -202,7 +202,7 @@ def test_me_query_checkouts_do_not_trigger_sync_tax_webhooks(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=user,
)
@@ -254,7 +254,7 @@ def test_me_query_checkouts_calculate_flat_taxes(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=user,
)
diff --git a/saleor/graphql/checkout/dataloaders/calculations.py b/saleor/graphql/checkout/dataloaders/calculations.py
new file mode 100644
index 0000000000..aa488227ca
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders/calculations.py
@@ -0,0 +1,64 @@
+from collections.abc import Iterable
+from uuid import UUID
+
+from promise import Promise
+
+from ....app.models import App
+from ....checkout.calculations import fetch_checkout_data
+from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
+from ...app.dataloaders.utils import get_app_promise
+from ...core.dataloaders import DataLoader
+from ...plugins.dataloaders import plugin_manager_promise
+from .checkout_infos import (
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
+
+
+class CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ DataLoader[tuple[UUID, bool, bool], tuple[CheckoutInfo, list[CheckoutLineInfo]]]
+):
+ context_key = (
+ "checkout_price_calculation_by_checkout_id_and_webhook_sync_and_status"
+ )
+
+ def batch_load(
+ self, keys: Iterable[tuple[UUID, bool, bool]]
+ ) -> Promise[list[tuple[CheckoutInfo, list[CheckoutLineInfo]]]]:
+ tokens = [token for (token, _, _) in keys]
+ lines_dataloader = CheckoutLinesInfoByCheckoutTokenLoader(
+ self.context
+ ).load_many(keys=tokens)
+ checkout_info_dataloader = CheckoutInfoByCheckoutTokenLoader(
+ self.context
+ ).load_many(keys=tokens)
+
+ def with_checkout_details(
+ data: tuple[App | None, list[CheckoutInfo], list[list[CheckoutLineInfo]]],
+ ):
+ app, checkout_infos, line_infos = data
+
+ def calculate_prices(manager):
+ results: list[Promise[tuple[CheckoutInfo, list[CheckoutLineInfo]]]] = []
+ for checkout_info, lines_info, (
+ _,
+ allow_sync_webhooks,
+ force_status_update,
+ ) in zip(checkout_infos, line_infos, keys, strict=True):
+ result = fetch_checkout_data(
+ checkout_info=checkout_info,
+ manager=manager,
+ lines=lines_info,
+ requestor=app or self.context.user,
+ database_connection_name=self.database_connection_name,
+ allow_sync_webhooks=allow_sync_webhooks,
+ force_status_update=force_status_update,
+ )
+ 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), checkout_info_dataloader, lines_dataloader]
+ ).then(with_checkout_details)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 3ea8376865..0f3c94b3ad 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -419,7 +419,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(88):
+ with django_assert_num_queries(89):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -437,7 +437,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(88):
+ with django_assert_num_queries(89):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -569,7 +569,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(107):
+ with django_assert_num_queries(108):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -826,7 +826,7 @@ def test_update_checkout_lines_with_reservations(
)
user_api_client.ensure_access_token()
- with django_assert_num_queries(107):
+ with django_assert_num_queries(108):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -840,7 +840,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(107):
+ with django_assert_num_queries(108):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1100,7 +1100,7 @@ def test_add_checkout_lines_with_reservations(
user_api_client.ensure_access_token()
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(104):
+ with django_assert_num_queries(105):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1113,7 +1113,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(104):
+ with django_assert_num_queries(105):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1164,7 +1164,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(95):
+ with django_assert_num_queries(96):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1250,7 +1250,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(95):
+ with django_assert_num_queries(96):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1286,7 +1286,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(107):
+ with django_assert_num_queries(108):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1321,7 +1321,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(142):
+ with django_assert_num_queries(143):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1448,10 +1448,7 @@ def test_checkout_payment_charge(
checkout_info = fetch_checkout_info(checkout_with_billing_address, lines, manager)
manager = get_plugins_manager(allow_replica=False)
total = calculations.calculate_checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=checkout_with_billing_address.shipping_address,
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
index cadc0a7700..b08ba8822b 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
@@ -96,7 +96,7 @@ def test_checkout_complete(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -263,7 +263,7 @@ def test_checkout_complete_for_token_as_input(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index b8801724ec..7a1fce1bc8 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -96,10 +96,7 @@ def test_checkout_add_voucher_for_entire_order(api_client, checkout_with_item, v
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
taxed_total = calculations.calculate_checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=checkout_with_item.shipping_address,
+ manager=manager, checkout_info=checkout_info, lines=lines
)
# when
@@ -279,7 +276,6 @@ def test_checkout_add_products_voucher_code_checkout_with_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
voucher_discount_value = (
@@ -308,7 +304,6 @@ def test_checkout_add_products_voucher_code_checkout_with_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + Money(
@@ -363,7 +358,6 @@ def test_checkout_add_voucher_code_checkout_on_promotion(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- address = checkout.shipping_address
voucher_discount_value = (
voucher_percentage.channel_listings.filter(channel=checkout.channel)
@@ -377,7 +371,6 @@ def test_checkout_add_voucher_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
variables = {
@@ -429,7 +422,6 @@ def test_checkout_add_specific_product_voucher_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
variables = {
@@ -452,7 +444,6 @@ def test_checkout_add_specific_product_voucher_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + Money(
@@ -496,7 +487,6 @@ def test_checkout_add_collection_voucher_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
variables = {
@@ -519,7 +509,6 @@ def test_checkout_add_collection_voucher_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert not data["errors"]
@@ -559,7 +548,6 @@ def test_checkout_add_category_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -581,7 +569,6 @@ def test_checkout_add_category_code_checkout_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert not data["errors"]
assert subtotal_discounted == subtotal_with_voucher + Money(
@@ -704,7 +691,6 @@ def test_checkout_add_variant_voucher_code_apply_once_per_order(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
variables = {
@@ -882,10 +868,7 @@ def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
taxed_total = calculations.calculate_checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=checkout_with_item.shipping_address,
+ manager=manager, checkout_info=checkout_info, lines=lines
)
total_with_gift_card = taxed_total.gross.amount - gift_card.current_balance_amount
@@ -911,7 +894,6 @@ def test_checkout_get_total_with_many_gift_card(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_gift_card.shipping_address,
)
total_with_gift_card = (
taxed_total.gross.amount - gift_card_created_by_staff.current_balance_amount
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index 45886ebe47..cdb66f7fb6 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -223,7 +223,9 @@ def test_checkout_complete_0_total_value_no_payment(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
)
orders_count = Order.objects.count()
variables = {
@@ -288,7 +290,7 @@ def test_checkout_complete_0_total_value_from_voucher(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
orders_count = Order.objects.count()
variables = {
@@ -350,7 +352,9 @@ def test_checkout_complete_0_total_value_from_giftcard(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
)
orders_count = Order.objects.count()
variables = {
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
index 9fbe6e0db1..dda6c1e04f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_price_override.py
@@ -127,7 +127,7 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_fixed(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
_ = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get().price_amount
@@ -207,7 +207,7 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_percentag
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
_ = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get().price_amount
@@ -702,7 +702,7 @@ def test_checkout_complete_with_price_override_and_catalogue_promotion_and_entir
checkout_info = fetch_checkout_info(checkout, lines, manager)
add_voucher_code_to_checkout(manager, checkout_info, lines, voucher_code)
_ = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get().price_amount
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 2f9359e6cb..04f3e1d0c3 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -160,7 +160,6 @@ def test_checkout_complete_with_inactive_channel(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -237,7 +236,7 @@ def test_checkout_complete(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -329,16 +328,18 @@ def test_checkout_complete(
recalculate_with_plugins_mock.assert_not_called()
assert not len(Reservation.objects.all())
-
+ gift_card_log = next(
+ rec for rec in caplog.records if "Gift card payment" in rec.message
+ )
assert (
graphene.Node.to_global_id("Checkout", checkout_info.checkout.pk)
- == caplog.records[0].checkout_id
+ == gift_card_log.checkout_id
)
assert gift_card.initial_balance_amount == Decimal(
- caplog.records[0].gift_card_compensation
+ gift_card_log.gift_card_compensation
)
assert total.gross.amount == Decimal(
- caplog.records[0].total_after_gift_card_compensation
+ gift_card_log.total_after_gift_card_compensation
)
assert customer_user.addresses.count() == user_address_count + 2
@@ -382,7 +383,7 @@ def test_checkout_complete_with_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -459,7 +460,7 @@ def test_checkout_complete_with_metadata_updates_existing_keys(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -521,7 +522,7 @@ def test_checkout_complete_with_metadata_checkout_without_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -594,7 +595,7 @@ def test_checkout_complete_by_app(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -657,7 +658,7 @@ def test_checkout_complete_by_app_with_missing_permission(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -727,7 +728,7 @@ def test_checkout_complete_gift_card_bought(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -799,7 +800,7 @@ def test_checkout_complete_with_variant_without_sku(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -1003,7 +1004,7 @@ def test_checkout_with_voucher_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -1117,7 +1118,7 @@ def test_checkout_with_order_promotion_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -1244,7 +1245,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -1398,7 +1399,6 @@ def test_checkout_with_voucher_complete_product_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -1527,7 +1527,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -1643,7 +1643,7 @@ def test_checkout_complete_with_voucher_single_use(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -1753,7 +1753,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card_and_payment(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
gift_card_initial_balance = gift_card.initial_balance_amount
@@ -1875,7 +1875,7 @@ def test_checkout_complete_with_voucher_paid_by_gift_card(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total_without_gc = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
gift_card.initial_balance_amount = total_without_gc.gross.amount + Decimal(1)
@@ -1887,7 +1887,7 @@ def test_checkout_complete_with_voucher_paid_by_gift_card(
)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
@@ -1997,7 +1997,7 @@ def test_checkout_complete_free_shipping_voucher_and_gift_card(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
@@ -2148,7 +2148,6 @@ def test_checkout_complete_product_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -2294,7 +2293,6 @@ def test_checkout_complete_product_on_promotion_deleted_promotion_instance(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -2393,7 +2391,7 @@ def test_checkout_complete_price_override(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -2529,7 +2527,6 @@ def test_checkout_complete_product_on_old_sale(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -2708,7 +2705,6 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
payment = payment_dummy
payment.is_active = True
@@ -2876,7 +2872,7 @@ def test_checkout_complete_without_inventory_tracking(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -2954,7 +2950,7 @@ def test_checkout_complete_checkout_without_lines(
assert not lines
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -3016,7 +3012,7 @@ def test_checkout_complete_error_in_gateway_response_for_dummy_credit_card(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy_credit_card
payment.is_active = True
@@ -3095,7 +3091,7 @@ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
taxed_total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -3193,7 +3189,7 @@ def test_checkout_complete_confirmation_needed(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -3256,7 +3252,7 @@ def test_checkout_confirm(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_txn_to_confirm
payment.is_active = True
@@ -3307,7 +3303,7 @@ def test_checkout_complete_insufficient_stock(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -3358,7 +3354,7 @@ def test_checkout_complete_insufficient_stock_payment_refunded(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -3420,7 +3416,7 @@ def test_checkout_complete_insufficient_stock_payment_voided(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_txn_preauth
@@ -3496,7 +3492,7 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -3552,7 +3548,7 @@ def test_checkout_complete_own_reservation(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -3617,7 +3613,7 @@ def test_checkout_complete_without_redirect_url(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -3685,7 +3681,7 @@ def test_checkout_complete_payment_payment_total_different_than_checkout(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -3760,7 +3756,7 @@ def test_create_order_raises_insufficient_stock(
)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, checkout.shipping_address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -3823,7 +3819,7 @@ def test_checkout_complete_0_total_value(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -3900,7 +3896,7 @@ def test_complete_checkout_for_local_click_and_collect(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -3969,7 +3965,7 @@ def test_complete_checkout_for_global_click_and_collect(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -4081,7 +4077,7 @@ def test_comp_checkout_builds_order_for_all_warehouse_even_if_not_available_loca
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -4135,7 +4131,7 @@ def test_checkout_complete_raises_InsufficientStock_when_quantity_above_stock_su
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
@@ -4182,7 +4178,7 @@ def test_checkout_complete_raises_InvalidShippingMethod_when_warehouse_disabled(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
assert not checkout_info.valid_pick_up_points
@@ -4235,7 +4231,7 @@ def test_checkout_complete_with_preorder_variant(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -4345,7 +4341,7 @@ def test_checkout_complete_with_click_collect_preorder_fails_for_disabled_wareho
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
assert not checkout_info.valid_pick_up_points
@@ -4402,7 +4398,7 @@ def test_checkout_complete_variant_channel_listing_does_not_exist(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
@@ -4471,7 +4467,7 @@ def test_checkout_complete_variant_channel_listing_no_price(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
@@ -4536,7 +4532,7 @@ def test_checkout_complete_product_channel_listing_does_not_exist(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
@@ -4608,7 +4604,7 @@ def test_checkout_complete_product_channel_listing_not_available_for_purchase(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
@@ -4673,7 +4669,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_required_
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy_credit_card
payment.is_active = True
@@ -4736,7 +4732,7 @@ def test_checkout_complete_error_when_shipping_address_doesnt_have_all_valid_fie
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy_credit_card
payment.is_active = True
@@ -4798,7 +4794,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_required_f
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy_credit_card
payment.is_active = True
@@ -4860,7 +4856,7 @@ def test_checkout_complete_error_when_billing_address_doesnt_have_all_valid_fiel
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy_credit_card
payment.is_active = True
@@ -4927,7 +4923,7 @@ def test_checkout_complete_with_not_normalized_shipping_address(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -4990,7 +4986,7 @@ def test_checkout_complete_with_not_normalized_billing_address(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -5042,7 +5038,7 @@ def test_checkout_complete_check_reservations_create(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -5101,7 +5097,7 @@ def test_checkout_complete_reservations_drop(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5151,7 +5147,7 @@ def test_checkout_complete_saving_addresses_off(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5226,7 +5222,7 @@ def test_checkout_complete_saving_addresses_on(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5309,7 +5305,7 @@ def test_checkout_complete_payment_create_create_run_in_meantime(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5392,7 +5388,7 @@ def test_checkout_complete_payment_payment_deactivated_in_meantime(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5458,7 +5454,7 @@ def test_checkout_complete_line_deleted_in_the_meantime(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5541,7 +5537,7 @@ def test_checkout_complete_with_invalid_address(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -5599,7 +5595,7 @@ def test_checkout_complete_log_unknown_discount_reason(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -5626,8 +5622,10 @@ def test_checkout_complete_log_unknown_discount_reason(
order = Order.objects.first()
order_line = order.lines.first()
assert not order_line.unit_discount_reason
- assert "Unknown discount reason" in caplog.text
- assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)
+ unknown_discount_log = next(
+ rec for rec in caplog.records if "Unknown discount reason" in rec.message
+ )
+ assert unknown_discount_log.checkout_id == to_global_id_or_none(checkout)
@patch("saleor.order.calculations._recalculate_with_plugins")
@@ -5673,7 +5671,7 @@ def test_checkout_complete_empty_product_translation(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -5817,7 +5815,7 @@ def test_checkout_complete_with_external_shipping(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -5951,7 +5949,7 @@ def test_checkout_complete_with_external_shipping_private_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -6010,7 +6008,7 @@ def test_checkout_complete_with_different_email_than_user_email(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -6057,7 +6055,7 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
}
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
payment = payment_dummy
payment.is_active = True
@@ -6312,7 +6310,7 @@ def test_checkout_complete_warehouse_without_shipping_zones(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
@@ -6370,7 +6368,7 @@ def test_checkout_complete_warehouse_without_shipping_zones_excluded_from_stock_
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = payment_dummy
payment.is_active = True
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index f52991ce7a..bb1b499c6c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -168,7 +168,7 @@ def prepare_checkout_for_test(
)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, shipping_address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(checkout_id=checkout.pk)
transaction_events_generator(
@@ -217,7 +217,7 @@ def test_checkout_without_any_transaction(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
update_checkout_payment_statuses(
@@ -267,7 +267,7 @@ def test_checkout_without_any_transaction_allow_to_create_order(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
update_checkout_payment_statuses(
@@ -322,7 +322,7 @@ def test_checkout_with_total_0(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -403,7 +403,7 @@ def test_checkout_with_authorized(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(
@@ -515,7 +515,7 @@ def test_checkout_with_charged(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(
@@ -628,7 +628,7 @@ def test_checkout_price_override(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(
@@ -724,7 +724,7 @@ def test_checkout_paid_with_multiple_transactions(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(
@@ -788,7 +788,7 @@ def test_checkout_partially_paid(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction_item_generator(
@@ -842,7 +842,7 @@ def test_checkout_partially_paid_allow_unpaid_order(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(
@@ -899,7 +899,7 @@ def test_checkout_with_pending_charged(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(checkout_id=checkout.pk)
@@ -978,7 +978,7 @@ def test_checkout_with_pending_authorized(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction = transaction_item_generator(checkout_id=checkout.pk)
@@ -1079,10 +1079,8 @@ def test_checkout_with_voucher_not_applicable(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
calculations.fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=None
+ ).get()
Voucher.objects.all().delete()
@@ -1124,10 +1122,8 @@ def test_checkout_with_voucher_inactive_code(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
calculations.fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=None
+ ).get()
code.is_active = False
code.save(update_fields=["is_active"])
@@ -1402,7 +1398,7 @@ def test_checkout_complete(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
@@ -1481,16 +1477,13 @@ def test_checkout_complete(
assert not len(Reservation.objects.all())
+ gift_log = next(rec for rec in caplog.records if "Gift card payment" in rec.message)
assert (
graphene.Node.to_global_id("Checkout", checkout_info.checkout.pk)
- == caplog.records[0].checkout_id
- )
- assert gift_card.initial_balance_amount == Decimal(
- caplog.records[0].gift_card_compensation
- )
- assert total.gross.amount == Decimal(
- caplog.records[0].total_after_gift_card_compensation
+ == gift_log.checkout_id
)
+ assert gift_card.initial_balance_amount == Decimal(gift_log.gift_card_compensation)
+ assert total.gross.amount == Decimal(gift_log.total_after_gift_card_compensation)
assert customer_user.addresses.count() == user_address_count + 2
# ensure the the customer addresses are not the same instances as the order addresses
@@ -1912,7 +1905,7 @@ def test_checkout_complete_with_shipping_voucher_and_gift_card(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
@@ -2100,7 +2093,7 @@ def test_checkout_with_voucher_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -2197,7 +2190,7 @@ def test_checkout_with_order_promotion_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -2289,7 +2282,7 @@ def test_checkout_complete_with_entire_order_voucher_paid_with_gift_card_and_tra
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
@@ -2389,7 +2382,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total_without_gc = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
gift_card.initial_balance_amount = total_without_gc.gross.amount + Decimal(1)
@@ -2401,7 +2394,7 @@ def test_checkout_complete_with_voucher_paid_with_gift_card(
)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
@@ -2521,7 +2514,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -2625,7 +2618,7 @@ def test_checkout_complete_with_voucher_apply_once_per_order_and_gift_card(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
@@ -2723,7 +2716,7 @@ def test_checkout_complete_with_voucher_single_use(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -2816,7 +2809,7 @@ def test_checkout_complete_with_shipping_voucher(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
@@ -2972,7 +2965,6 @@ def test_checkout_with_voucher_complete_product_on_sale(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
variables = {
@@ -3071,7 +3063,7 @@ def test_checkout_with_voucher_on_specific_product_complete(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -3168,7 +3160,7 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
shipping_price = shipping_method.channel_listings.get(
channel=checkout.channel
@@ -3308,7 +3300,6 @@ def test_checkout_complete_product_on_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
variables = {
@@ -3466,7 +3457,6 @@ def test_checkout_complete_multiple_rules_applied(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
variables = {
@@ -3579,7 +3569,6 @@ def test_checkout_with_voucher_on_specific_product_complete_with_product_on_prom
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
variables = {
@@ -3750,9 +3739,7 @@ def test_checkout_complete_checkout_without_lines(
lines, _ = fetch_checkout_lines(checkout)
assert not lines
checkout_info = fetch_checkout_info(checkout, lines, manager)
- calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
+ calculations.calculate_checkout_total_with_gift_cards(manager, checkout_info, lines)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
channel.save()
@@ -4414,7 +4401,7 @@ def test_checkout_complete_with_preorder_variant(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
@@ -5117,7 +5104,7 @@ def test_checkout_complete_with_invalid_address(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
update_checkout_payment_statuses(
@@ -5187,8 +5174,10 @@ def test_checkout_complete_log_unknown_discount_reason(
order = Order.objects.first()
order_line = order.lines.first()
assert not order_line.unit_discount_reason
- assert "Unknown discount reason" in caplog.text
- assert caplog.records[0].checkout_id == to_global_id_or_none(checkout)
+ unknown_discount_log = next(
+ rec for rec in caplog.records if "Unknown discount reason" in rec.message
+ )
+ assert unknown_discount_log.checkout_id == to_global_id_or_none(checkout)
@patch("saleor.order.calculations._recalculate_with_plugins")
@@ -5227,7 +5216,7 @@ def test_checkout_complete_empty_product_translation(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
@@ -5396,7 +5385,7 @@ def test_checkout_complete_with_external_shipping_method(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction_item_generator(
@@ -5527,7 +5516,9 @@ def test_checkout_complete_with_external_shipping_method_private_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager,
+ checkout_info,
+ lines,
)
transaction_item_generator(
@@ -6032,7 +6023,7 @@ def test_checkout_complete_with_transaction_warehouse_without_shipping_zones(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction_item_generator(
@@ -6091,7 +6082,7 @@ def test_checkout_complete_with_transaction_warehouse_without_shipping_zones_exc
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
transaction_item_generator(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 280a7de863..bb9f2d0922 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -2012,7 +2012,7 @@ def test_checkout_lines_update_with_new_metadata_merge_old(
wraps=_calculate_and_add_tax,
)
@mock.patch(
- "saleor.checkout.calculations.fetch_checkout_data",
+ "saleor.graphql.checkout.dataloaders.calculations.fetch_checkout_data",
wraps=fetch_checkout_data,
)
def test_checkout_lines_update_checkout_updated_during_price_recalculation(
@@ -2039,8 +2039,8 @@ def test_checkout_lines_update_checkout_updated_during_price_recalculation(
checkout_to_modify.email = expected_email
checkout_to_modify.save(update_fields=["email", "last_change"])
- with race_condition.RunAfter(
- "saleor.checkout.calculations._calculate_and_add_tax", modify_checkout
+ with race_condition.RunBefore(
+ "saleor.checkout.calculations.checkout_qs_select_for_update", modify_checkout
):
response = user_api_client.post_graphql(
MUTATION_CHECKOUT_LINES_UPDATE, variables
@@ -2052,7 +2052,7 @@ def test_checkout_lines_update_checkout_updated_during_price_recalculation(
assert not data["errors"]
# Ensure that the checkout prices recalculation was triggered more than one time.
- assert mock_fetch_checkout_data.call_count > 1
+ assert mock_fetch_checkout_data.call_count == 1
# Ensure that the checkout price are recalculated only one time
assert mock_calculate_and_add_tax.call_count == 1
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 307d6e217b..e76d657590 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -204,10 +204,8 @@ def test_checkout_shipping_method_update_external_shipping_method(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=staff_api_client.user
+ ).get()
errors = data["errors"]
assert not errors
assert data["checkout"]["token"] == str(checkout_with_item.token)
@@ -383,10 +381,8 @@ def test_checkout_shipping_method_update_with_not_all_required_shipping_address_
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=staff_api_client.user
+ ).get()
assert not data["errors"]
assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
@@ -432,10 +428,8 @@ def test_checkout_shipping_method_update_with_not_valid_shipping_address_data(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=staff_api_client.user
+ ).get()
assert not data["errors"]
assert checkout.assigned_delivery.shipping_method_id == str(shipping_method.id)
@@ -503,10 +497,8 @@ def test_checkout_shipping_method_update_shipping_zone_without_channel(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- )
+ checkout_info, manager, lines, requestor=staff_api_client.user
+ ).get()
errors = data["errors"]
assert len(errors) == 1
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 074dbb7adf..ad43ab8770 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -10,6 +10,7 @@ from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
from prices import Money, TaxedMoney
+from promise import Promise
from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
@@ -184,7 +185,7 @@ def test_order_from_checkout(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -425,7 +426,7 @@ def test_order_from_checkout_with_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -495,7 +496,7 @@ def test_order_from_checkout_with_metadata_checkout_without_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -600,7 +601,7 @@ def test_order_from_checkout_gift_card_bought(
checkout_info = fetch_checkout_info(checkout, lines, manager)
amount = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
).gross.amount
payment_txn_captured.order = None
@@ -1615,7 +1616,7 @@ def test_order_from_checkout_without_inventory_tracking(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
orders_count = Order.objects.count()
@@ -1987,7 +1988,7 @@ def test_order_from_checkout_0_total_value(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
orders_count = Order.objects.count()
@@ -2242,7 +2243,7 @@ def test_order_from_draft_create_with_preorder_variant(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
channel = checkout.channel
channel.automatically_confirm_all_new_orders = True
@@ -2616,7 +2617,7 @@ def test_order_from_draft_create_0_total_value_from_voucher(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -2675,7 +2676,7 @@ def test_order_from_draft_create_0_total_value_from_giftcard(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
orders_count = Order.objects.count()
variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
@@ -2708,8 +2709,8 @@ def test_order_from_draft_create_0_total_value_from_giftcard(
@patch(
- "saleor.checkout.calculations._get_taxes_for_checkout",
- side_effect=TaxDataError("Invalid data"),
+ "saleor.checkout.calculations._get_promised_taxes_for_checkout",
+ return_value=Promise.reject(TaxDataError("Invalid data")),
)
def test_order_from_checkout_tax_error(
mocked_get_taxes_for_order,
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 96a8a5e72f..73ea7dfbe2 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -681,7 +681,6 @@ def test_checkout_deliveries_with_price_based_shipping_method_and_discount(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
checkout_with_item.discount_amount = Decimal(5.0)
@@ -723,7 +722,6 @@ def test_checkout_deliveries_with_price_based_shipping_and_shipping_discount(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
checkout_with_item.discount_amount = Decimal(5.0)
@@ -783,7 +781,6 @@ def test_checkout_deliveries_with_price_based_method_and_product_voucher(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
shipping_method.name = "Price based"
shipping_method.save(update_fields=["name"])
@@ -2049,7 +2046,6 @@ def test_checkout_prices(user_api_client, checkout_with_item):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
@@ -2057,7 +2053,6 @@ def test_checkout_prices(user_api_client, checkout_with_item):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
@@ -2242,14 +2237,12 @@ def test_checkout_prices_with_promotion(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -2721,14 +2714,12 @@ def test_checkout_prices_with_promotion_line_deleted_in_meantime(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -2782,13 +2773,11 @@ def test_checkout_prices_with_promotion_one_line_deleted_in_meantime(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
def delete_checkout_line(*args, **kwargs):
@@ -2861,7 +2850,7 @@ def test_checkout_display_gross_prices_use_default(user_api_client, checkout_wit
wraps=_calculate_and_add_tax,
)
@mock.patch(
- "saleor.checkout.calculations.fetch_checkout_data",
+ "saleor.graphql.checkout.dataloaders.calculations.fetch_checkout_data",
wraps=fetch_checkout_data,
)
def test_checkout_prices_with_checkout_updated_during_price_recalculation(
@@ -2899,8 +2888,8 @@ def test_checkout_prices_with_checkout_updated_during_price_recalculation(
# then
assert data["token"] == str(checkout.token)
- # Ensure that the checkout prices recalculation was triggered more than one time
- assert mock_fetch_checkout_data.call_count > 1
+ # Ensure that the checkout prices recalculation was triggered only once time
+ assert mock_fetch_checkout_data.call_count == 1
# Ensure that the checkout price are recalculated only one time
assert mock_calculate_and_add_tax.call_count == 1
@@ -2971,14 +2960,12 @@ def test_checkout_prices_with_specific_voucher(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3056,14 +3043,12 @@ def test_checkout_prices_with_specific_voucher_when_line_without_listing(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == total.gross.amount
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == subtotal.gross.amount
line_info = lines[0]
@@ -3130,14 +3115,12 @@ def test_checkout_prices_with_voucher_once_per_order(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3219,14 +3202,12 @@ def test_checkout_prices_with_voucher_once_per_order_when_line_without_listing(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3295,14 +3276,12 @@ def test_checkout_prices_with_voucher(user_api_client, checkout_with_item_and_vo
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3384,14 +3363,12 @@ def test_checkout_prices_with_voucher_when_line_without_listing(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == total.gross.amount
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == subtotal.gross.amount
line_info = lines[0]
@@ -3463,14 +3440,12 @@ def test_checkout_prices_with_voucher_code_that_doesnt_exist(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3554,14 +3529,12 @@ def test_checkout_prices_voucher_code_that_doesnt_exist_when_line_without_listin
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
subtotal = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_info.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
@@ -3622,7 +3595,8 @@ def test_checkout_prices_variant_listing_price_changed(
manager,
lines,
force_update=True,
- )
+ requestor=None,
+ ).get()
line = lines[0]
listing = line.variant.channel_listings.get(
@@ -3648,7 +3622,6 @@ def test_checkout_prices_variant_listing_price_changed(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
@@ -3656,7 +3629,6 @@ def test_checkout_prices_variant_listing_price_changed(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
@@ -3696,11 +3668,8 @@ def test_checkout_prices_expired_variant_listing_price_changed(
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
calculations.fetch_checkout_data(
- checkout_info,
- manager,
- lines,
- force_update=True,
- )
+ checkout_info, manager, lines, force_update=True, requestor=None
+ ).get()
checkout_with_item.price_expiration = timezone.now() - datetime.timedelta(days=1)
checkout_with_item.discount_expiration = timezone.now() - datetime.timedelta(days=1)
checkout_with_item.save(update_fields=["price_expiration", "discount_expiration"])
@@ -3730,7 +3699,6 @@ def test_checkout_prices_expired_variant_listing_price_changed(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
@@ -3738,7 +3706,6 @@ def test_checkout_prices_expired_variant_listing_price_changed(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout_with_item.shipping_address,
)
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
@@ -3909,7 +3876,7 @@ def test_query_checkouts_do_not_trigger_sync_tax_webhooks(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
@@ -3960,7 +3927,7 @@ def test_query_checkouts_calculate_flat_taxes(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
@@ -4055,7 +4022,7 @@ def test_query_checkout_lines_do_not_trigger_sync_tax_webhooks(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
@@ -4102,7 +4069,7 @@ def test_query_checkout_lines_calculate_flat_taxes(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
@@ -4205,7 +4172,9 @@ def test_clean_checkout(
checkout_info = fetch_checkout_info(checkout, lines, manager)
manager = get_plugins_manager(allow_replica=False)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
)
payment = payment_dummy
diff --git a/saleor/graphql/checkout/tests/test_checkout_line_problems.py b/saleor/graphql/checkout/tests/test_checkout_line_problems.py
index c279f92744..882b14b40d 100644
--- a/saleor/graphql/checkout/tests/test_checkout_line_problems.py
+++ b/saleor/graphql/checkout/tests/test_checkout_line_problems.py
@@ -608,7 +608,7 @@ def test_query_checkouts_do_not_trigger_sync_tax_webhooks_when_variant_not_avail
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
@@ -715,7 +715,7 @@ def test_query_checkouts_do_not_trigger_sync_tax_webhooks_when_out_of_stock(
force_update=False,
lines=lines,
manager=mock.ANY,
- pregenerated_subscription_payloads=mock.ANY,
+ requestor=staff_api_client.user,
)
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index 549a56ad7b..3f46989ed2 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -48,7 +48,6 @@ def test_checkout_totals_use_discounts(api_client, checkout_with_item, channel_U
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address,
)
assert data["totalPrice"]["gross"]["amount"] == taxed_total.gross.amount
assert data["subtotalPrice"]["gross"]["amount"] == taxed_total.gross.amount
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index e39fa93f26..a9f8f75969 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,12 +1,12 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING
import graphene
from promise import Promise
from ...account.models import User
-from ...checkout import calculations, models, problems
-from ...checkout.calculations import fetch_checkout_data
+from ...checkout import models, problems
+from ...checkout.calculations import recalculate_discounts
from ...checkout.delivery_context import (
get_valid_collection_points_for_checkout,
)
@@ -90,16 +90,15 @@ from ..warehouse.dataloaders import (
WarehouseByIdLoader,
)
from ..warehouse.types import Warehouse
-from ..webhook.dataloaders.pregenerated_payload_for_checkout_tax import (
- PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader,
-)
from .dataloaders import (
- CheckoutByTokenLoader,
CheckoutInfoByCheckoutTokenLoader,
CheckoutLinesInfoByCheckoutTokenLoader,
CheckoutMetadataByCheckoutIdLoader,
TransactionItemsByCheckoutIDLoader,
)
+from .dataloaders.calculations import (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader,
+)
from .dataloaders.checkout_delivery import (
CheckoutDeliveriesOnlyValidByCheckoutIdAndWebhookSyncLoader,
CheckoutDeliveryByIdLoader,
@@ -108,40 +107,10 @@ from .enums import CheckoutAuthorizeStatusEnum, CheckoutChargeStatusEnum
from .utils import prevent_sync_event_circular_query
if TYPE_CHECKING:
- from ...account.models import Address
from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ...plugins.manager import PluginsManager
-def get_dataloaders_for_fetching_checkout_data(
- root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
-) -> tuple[
- Promise["Address"] | None,
- Promise[list["CheckoutLineInfo"]],
- Promise["CheckoutInfo"],
- Promise["PluginsManager"],
- Promise[dict[str, Any]] | None,
-]:
- checkout = root.node
- address_id = checkout.shipping_address_id or checkout.billing_address_id
- address = AddressByIdLoader(info.context).load(address_id) if address_id else None
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(checkout.token)
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(checkout.token)
- manager = get_plugin_manager_promise(info.context)
- tax_payloads = None
- if root.allow_sync_webhooks:
- tax_payloads = PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(
- info.context
- ).load(checkout.token)
- return (
- address,
- lines,
- checkout_info,
- manager,
- tax_payloads,
- )
-
-
def get_dataloaders_for_recalculate_discounts(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
) -> tuple[
@@ -392,87 +361,49 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
def resolve_unit_price(
root: SyncWebhookControlContext[models.CheckoutLine], info: ResolveInfo
):
- def with_checkout(data):
- checkout, manager = data
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
+ checkout_line = root.node
+
+ def _get_unit_price(data):
+ checkout_info, lines = data
+ line_info = next(
+ (li for li in lines if li.line.pk == checkout_line.pk), None
)
- tax_payloads = None
- if root.allow_sync_webhooks:
- tax_payloads = PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(
- info.context
- ).load(checkout.token)
-
- @allow_writer_in_context(info.context)
- def calculate_line_unit_price(data):
- checkout_info, lines, tax_payloads = data
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- database_connection_name = get_database_connection_name(info.context)
- for line_info in lines:
- if line_info.line.pk == root.node.pk:
- return calculations.checkout_line_unit_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ if line_info is None:
return None
+ currency = checkout_info.checkout.currency
+ unit_price = line_info.line.total_price / line_info.line.quantity
+ return quantize_price(unit_price, currency)
- return Promise.all([checkout_info, lines, tax_payloads]).then(
- calculate_line_unit_price
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
)
-
- return Promise.all(
- [
- CheckoutByTokenLoader(info.context).load(root.node.checkout_id),
- get_plugin_manager_promise(info.context),
- ]
- ).then(with_checkout)
+ .load((checkout_line.checkout_id, root.allow_sync_webhooks, False))
+ .then(_get_unit_price)
+ )
@staticmethod
def resolve_undiscounted_unit_price(
root: SyncWebhookControlContext[models.CheckoutLine], info: ResolveInfo
):
- def with_checkout(checkout):
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
+ checkout_line = root.node
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
+ def _get_undiscounted_unit_price(data):
+ checkout_info, lines = data
+ line_info = next(
+ (li for li in lines if li.line.pk == checkout_line.pk), None
)
-
- def calculate_undiscounted_unit_price(data):
- (
- checkout_info,
- lines,
- ) = data
- for line_info in lines:
- if line_info.line.pk == root.node.pk:
- return calculations.checkout_line_undiscounted_unit_price(
- checkout_info=checkout_info,
- checkout_line_info=line_info,
- )
-
+ if line_info is None:
return None
-
- return Promise.all(
- [
- checkout_info,
- lines,
- ]
- ).then(calculate_undiscounted_unit_price)
+ currency = checkout_info.checkout.currency
+ return quantize_price(line_info.line.undiscounted_unit_price, currency)
return (
- CheckoutByTokenLoader(info.context)
- .load(root.node.checkout_id)
- .then(with_checkout)
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout_line.checkout_id, root.allow_sync_webhooks, False))
+ .then(_get_undiscounted_unit_price)
)
@staticmethod
@@ -481,86 +412,49 @@ class CheckoutLine(SyncWebhookControlContextModelObjectType[models.CheckoutLine]
def resolve_total_price(
root: SyncWebhookControlContext[models.CheckoutLine], info: ResolveInfo
):
- def with_checkout(data):
- checkout, manager = data
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
+ checkout_line = root.node
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
+ def _get_total_price(data):
+ checkout_info, lines = data
+ line_info = next(
+ (li for li in lines if li.line.pk == checkout_line.pk), None
)
- tax_payloads = None
- if root.allow_sync_webhooks:
- tax_payloads = PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(
- info.context
- ).load(checkout.token)
-
- @allow_writer_in_context(info.context)
- def calculate_line_total_price(data):
- checkout_info, lines, tax_payloads = data
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
- database_connection_name = get_database_connection_name(info.context)
- for line_info in lines:
- if line_info.line.pk == root.node.pk:
- return calculations.checkout_line_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ if line_info is None:
return None
+ currency = checkout_info.checkout.currency
+ return quantize_price(line_info.line.total_price, currency)
- return Promise.all([checkout_info, lines, tax_payloads]).then(
- calculate_line_total_price
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
)
-
- return Promise.all(
- [
- CheckoutByTokenLoader(info.context).load(root.node.checkout_id),
- get_plugin_manager_promise(info.context),
- ]
- ).then(with_checkout)
+ .load((checkout_line.checkout_id, root.allow_sync_webhooks, False))
+ .then(_get_total_price)
+ )
@staticmethod
def resolve_undiscounted_total_price(
root: SyncWebhookControlContext[models.CheckoutLine], info: ResolveInfo
):
- def with_checkout(checkout):
- checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
- checkout.token
- )
+ checkout_line = root.node
- def calculate_undiscounted_total_price(data):
- (
- checkout_info,
- lines,
- ) = data
- for line_info in lines:
- if line_info.line.pk == root.node.pk:
- return calculations.checkout_line_undiscounted_total_price(
- checkout_info=checkout_info,
- checkout_line_info=line_info,
- )
+ def _get_undiscounted_total_price(data):
+ checkout_info, lines = data
+ line_info = next(
+ (li for li in lines if li.line.pk == checkout_line.pk), None
+ )
+ if line_info is None:
return None
-
- return Promise.all(
- [
- checkout_info,
- lines,
- ]
- ).then(calculate_undiscounted_total_price)
+ currency = checkout_info.checkout.currency
+ total = line_info.line.undiscounted_unit_price * line_info.line.quantity
+ return quantize_price(total, currency)
return (
- CheckoutByTokenLoader(info.context)
- .load(root.node.checkout_id)
- .then(with_checkout)
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout_line.checkout_id, root.allow_sync_webhooks, False))
+ .then(_get_undiscounted_total_price)
)
@staticmethod
@@ -1119,25 +1013,31 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_total_price(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def calculate_total_price(data):
- address, lines, checkout_info, manager, tax_payloads = data
+ checkout = root.node
+
+ def _get_total_price(data):
+ checkout_info, _ = data
database_connection_name = get_database_connection_name(info.context)
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ currency = checkout_info.checkout.currency
+ total = quantize_price(checkout_info.checkout.total, currency)
+ if total == zero_taxed_money(currency):
+ return max(total, zero_taxed_money(currency))
+ gross_percentage = total.gross / total.net
+ with allow_writer_in_context(info.context):
+ total.gross -= checkout_info.checkout.get_total_gift_cards_balance(
+ database_connection_name
+ )
+ total.gross = max(total.gross, zero_money(currency))
+ total.net = quantize_price(total.gross / gross_percentage, currency)
+ return max(total, zero_taxed_money(currency))
- taxed_total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
)
- return max(taxed_total, zero_taxed_money(root.node.currency))
-
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- return Promise.all(dataloaders).then(calculate_total_price)
+ .load((checkout.token, root.allow_sync_webhooks, False))
+ .then(_get_total_price)
+ )
@staticmethod
@traced_resolver
@@ -1145,24 +1045,20 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_subtotal_price(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def calculate_subtotal_price(data):
- address, lines, checkout_info, manager, tax_payloads = data
- database_connection_name = get_database_connection_name(info.context)
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ checkout = root.node
- return calculations.checkout_subtotal(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def _get_subtotal(data):
+ checkout_info, _ = data
+ currency = checkout_info.checkout.currency
+ return quantize_price(checkout_info.checkout.subtotal, currency)
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- return Promise.all(dataloaders).then(calculate_subtotal_price)
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout.token, root.allow_sync_webhooks, False))
+ .then(_get_subtotal)
+ )
@staticmethod
@traced_resolver
@@ -1170,24 +1066,20 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_shipping_price(
root: SyncWebhookControlContext[models.Checkout], info: ResolveInfo
):
- @allow_writer_in_context(info.context)
- def calculate_shipping_price(data):
- address, lines, checkout_info, manager, tax_payloads = data
- database_connection_name = get_database_connection_name(info.context)
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ checkout = root.node
- return calculations.checkout_shipping_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def _get_shipping_price(data):
+ checkout_info, _ = data
+ currency = checkout_info.checkout.currency
+ return quantize_price(checkout_info.checkout.shipping_price, currency)
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- return Promise.all(dataloaders).then(calculate_shipping_price)
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout.token, root.allow_sync_webhooks, False))
+ .then(_get_shipping_price)
+ )
@staticmethod
def resolve_lines(
@@ -1198,9 +1090,7 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
lines_info, checkout_info = data
database_connection_name = get_database_connection_name(info.context)
# we need to recalculate discount as the gift line might be added / changed
- calculations.recalculate_discounts(
- checkout_info, lines_info, database_connection_name
- )
+ recalculate_discounts(checkout_info, lines_info, database_connection_name)
return (
SyncWebhookControlContext(
line_info.line, allow_sync_webhooks=root.allow_sync_webhooks
@@ -1479,105 +1369,72 @@ class Checkout(SyncWebhookControlContextModelObjectType[models.Checkout]):
def resolve_authorize_status(
root: SyncWebhookControlContext[models.Checkout], info
):
- @allow_writer_in_context(info.context)
- def _resolve_authorize_status(data):
- (
- address,
- lines,
- checkout_info,
- manager,
- tax_payloads,
- transactions,
- ) = data
- database_connection_name = get_database_connection_name(info.context)
- fetch_checkout_data(
- checkout_info=checkout_info,
- manager=manager,
- lines=lines,
- checkout_transactions=transactions,
- force_status_update=True,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ checkout = root.node
+
+ def _resolve_authorize_status(
+ data: tuple["CheckoutInfo", list["CheckoutLineInfo"]],
+ ):
+ checkout_info, _ = data
return checkout_info.checkout.authorize_status
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- dataloaders.append(
- TransactionItemsByCheckoutIDLoader(info.context).load(root.node.pk)
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout.token, root.allow_sync_webhooks, True))
+ .then(_resolve_authorize_status)
)
- return Promise.all(dataloaders).then(_resolve_authorize_status)
@staticmethod
def resolve_charge_status(root: SyncWebhookControlContext[models.Checkout], info):
- @allow_writer_in_context(info.context)
- def _resolve_charge_status(data):
- (
- address,
- lines,
- checkout_info,
- manager,
- tax_payloads,
- transactions,
- ) = data
- database_connection_name = get_database_connection_name(info.context)
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
+ checkout = root.node
- fetch_checkout_data(
- checkout_info=checkout_info,
- manager=manager,
- lines=lines,
- checkout_transactions=transactions,
- force_status_update=True,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
+ def _resolve_charge_status(
+ data: tuple["CheckoutInfo", list["CheckoutLineInfo"]],
+ ):
+ checkout_info, _ = data
return checkout_info.checkout.charge_status
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- dataloaders.append(
- TransactionItemsByCheckoutIDLoader(info.context).load(root.node.pk)
+ return (
+ CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ )
+ .load((checkout.token, root.allow_sync_webhooks, True))
+ .then(_resolve_charge_status)
)
- return Promise.all(dataloaders).then(_resolve_charge_status)
@staticmethod
def resolve_total_balance(root: SyncWebhookControlContext[models.Checkout], info):
+ checkout = root.node
database_connection_name = get_database_connection_name(info.context)
- def _calculate_total_balance_for_transactions(data):
- (
- address,
- lines,
- checkout_info,
- manager,
- tax_payloads,
- transactions,
- ) = data
- checkout_info.allow_sync_webhooks = root.allow_sync_webhooks
-
- taxed_total = calculations.calculate_checkout_total_with_gift_cards(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- database_connection_name=database_connection_name,
- pregenerated_subscription_payloads=tax_payloads,
- allow_sync_webhooks=root.allow_sync_webhooks,
- )
- currency = root.node.currency
- checkout_total = max(taxed_total, zero_taxed_money(currency))
+ def _calculate_total_balance(data):
+ (checkout_info, _), transactions = data
+ currency = checkout_info.checkout.currency
+ total = quantize_price(checkout_info.checkout.total, currency)
+ if total != zero_taxed_money(currency):
+ gross_percentage = total.gross / total.net
+ total.gross -= checkout_info.checkout.get_total_gift_cards_balance(
+ database_connection_name
+ )
+ total.gross = max(total.gross, zero_money(currency))
+ total.net = quantize_price(total.gross / gross_percentage, currency)
+ checkout_total = max(total, zero_taxed_money(currency))
total_charged = zero_money(currency)
for transaction in transactions:
total_charged += transaction.amount_charged
total_charged += transaction.amount_charge_pending
return total_charged - checkout_total.gross
- dataloaders = list(get_dataloaders_for_fetching_checkout_data(root, info))
- dataloaders.append(
- TransactionItemsByCheckoutIDLoader(info.context).load(root.node.pk)
+ price_calculation = CheckoutPriceCalculationByCheckoutIdAndWebhookSyncAndForceStatusUpdateLoader(
+ info.context
+ ).load((checkout.token, root.allow_sync_webhooks, False))
+ transactions = TransactionItemsByCheckoutIDLoader(info.context).load(
+ checkout.pk
+ )
+ return Promise.all([price_calculation, transactions]).then(
+ _calculate_total_balance
)
- return Promise.all(dataloaders).then(_calculate_total_balance_for_transactions)
@staticmethod
@traced_resolver
diff --git a/saleor/graphql/payment/mutations/base.py b/saleor/graphql/payment/mutations/base.py
index 8740b7721f..813b08d208 100644
--- a/saleor/graphql/payment/mutations/base.py
+++ b/saleor/graphql/payment/mutations/base.py
@@ -13,6 +13,7 @@ from ....order import models as order_models
from ...core.enums import TransactionInitializeErrorCode
from ...core.mutations import BaseMutation
from ...core.utils import from_global_id_or_error
+from ...utils import get_user_or_app_from_context
if TYPE_CHECKING:
from ....plugins.manager import PluginsManager
@@ -58,7 +59,12 @@ class TransactionSessionBase(BaseMutation):
if source_object:
lines, _ = fetch_checkout_lines(source_object)
checkout_info = fetch_checkout_info(source_object, lines, manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ requestor=get_user_or_app_from_context(info.context),
+ ).get()
source_object = checkout_info.checkout
else:
source_object = (
diff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
index d2968cff60..f71f26f1c4 100644
--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
@@ -271,14 +271,10 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
manager, gateway, input, channel_slug=checkout_info.channel.slug
)
- address = (
- checkout.shipping_address or checkout.billing_address
- ) # FIXME: check which address we need here
checkout_total = calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
)
amount = input.get("amount", checkout_total.gross.amount)
clean_checkout_shipping(checkout_info, lines, PaymentErrorCode)
diff --git a/saleor/graphql/payment/tests/deprecated/test_checkout_payment_create.py b/saleor/graphql/payment/tests/deprecated/test_checkout_payment_create.py
index 4580927bed..222b02271f 100644
--- a/saleor/graphql/payment/tests/deprecated/test_checkout_payment_create.py
+++ b/saleor/graphql/payment/tests/deprecated/test_checkout_payment_create.py
@@ -39,7 +39,7 @@ def test_checkout_add_payment_by_checkout_id(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"checkoutId": checkout_id,
@@ -81,7 +81,7 @@ def test_checkout_add_payment_neither_token_and_id_given(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"input": {
@@ -115,7 +115,7 @@ def test_checkout_add_payment_both_token_and_id_given(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"checkoutId": checkout_id,
diff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
index 859c6564bc..02d6007b82 100644
--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
@@ -54,7 +54,7 @@ def test_checkout_add_payment_without_shipping_method_and_not_shipping_required(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
# when
@@ -97,7 +97,7 @@ def test_checkout_add_payment_without_shipping_method_with_shipping_required(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -137,7 +137,7 @@ def test_checkout_add_payment_with_shipping_method_and_shipping_required(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -182,7 +182,7 @@ def test_checkout_add_payment(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -229,7 +229,7 @@ def test_checkout_add_payment_default_amount(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -265,7 +265,7 @@ def test_checkout_add_payment_bad_amount(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
@@ -300,7 +300,7 @@ def test_checkout_add_payment_no_checkout_email(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -411,7 +411,7 @@ def test_use_checkout_billing_address_as_payment_billing(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -464,7 +464,7 @@ def test_create_payment_for_checkout_with_active_payments(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -517,7 +517,7 @@ def test_create_payment_with_store(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -551,7 +551,7 @@ def test_create_payment_with_store_as_none(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -587,7 +587,7 @@ def test_create_payment_with_metadata(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -625,7 +625,7 @@ def test_checkout_add_payment_no_variant_channel_listings(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -671,7 +671,7 @@ def test_checkout_add_payment_no_product_channel_listings(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -716,7 +716,7 @@ def test_checkout_add_payment_checkout_without_lines(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -754,7 +754,7 @@ def test_checkout_add_payment_run_multiple_times(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
variables = {
"id": to_global_id_or_none(checkout),
@@ -832,7 +832,7 @@ def test_checkout_payment_create_checkout_locked(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -872,7 +872,7 @@ def test_checkout_payment_create_checkout_locked_time_pass(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
return_url = "https://www.example.com"
variables = {
@@ -910,7 +910,7 @@ def test_checkout_payment_create_is_not_allowed_when_checkout_has_transaction(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
total = calculations.calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
transaction_item_generator(
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
index b8fdacd7fd..67ddef7e45 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -56,7 +56,9 @@ def test_for_checkout_without_payment_gateways(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
checkout = checkout_info.checkout
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
@@ -161,7 +163,9 @@ def test_for_checkout_with_payment_gateways(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
checkout = checkout_info.checkout
expected_app_identifier = "app.id"
@@ -906,7 +910,9 @@ def test_for_checkout_with_shipping_app(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
checkout = checkout_info.checkout
variables = {
@@ -993,8 +999,12 @@ def test_for_checkout_with_tax_app(
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info, manager, lines, force_update=True
- )
+ checkout_info,
+ manager,
+ lines,
+ requestor=user_api_client.user,
+ force_update=True,
+ ).get()
variables = {
"id": to_global_id_or_none(checkout),
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index b739ed733a..b765e3200b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -1220,7 +1220,9 @@ def test_transaction_create_for_checkout_fully_paid(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=staff_api_client.user
+ ).get()
assert checkout.channel.automatically_complete_fully_paid_checkouts is False
@@ -1278,7 +1280,9 @@ def test_transaction_create_for_checkout_fully_authorized(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=staff_api_client.user
+ ).get()
assert checkout.channel.automatically_complete_fully_paid_checkouts is False
@@ -2792,7 +2796,9 @@ def test_lock_checkout_during_updating_checkout_amounts(
checkout = checkout_with_items
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
assert checkout.channel.automatically_complete_fully_paid_checkouts is False
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 90d0fd5ee8..73484246d0 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1273,7 +1273,9 @@ def test_transaction_event_updates_checkout_payment_statuses(
# Fetch checkout lines and info to recalculate checkout total prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- fetch_checkout_data(checkout_info, plugins_manager, lines)
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
current_charged_value = Decimal(20)
psp_reference = "111-abc"
@@ -1466,7 +1468,9 @@ def test_transaction_event_updates_checkout_full_paid_with_charged_amount(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
psp_reference = "111-abc"
transaction = transaction_item_generator(
@@ -1534,7 +1538,9 @@ def test_transaction_event_updates_checkout_full_paid_with_pending_charge_amount
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
psp_reference = "111-abc"
transaction = transaction_item_generator(
app=app_api_client.app, checkout_id=checkout.pk
@@ -1601,7 +1607,9 @@ def test_transaction_event_updates_checkout_fully_authorized(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
psp_reference = "111-abc"
transaction = transaction_item_generator(
@@ -3181,7 +3189,9 @@ def test_lock_checkout_during_updating_checkout_amounts(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
psp_reference = "111-abc"
transaction = transaction_item_generator(
@@ -3243,7 +3253,9 @@ def test_transaction_event_report_checkout_completed_race_condition(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
psp_reference = "111-abc"
transaction = transaction_item_generator(
@@ -3890,7 +3902,9 @@ def test_invalidate_stored_payment_methods_for_checkout(
# Fetch checkout lines and info to recalculate checkout total prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- fetch_checkout_data(checkout_info, plugins_manager, lines)
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
app = app_api_client.app
expected_app_identifier = "webhook.app.identifier"
@@ -4079,7 +4093,9 @@ def test_stored_payment_methods_not_invalidated_for_checkout(
# Fetch checkout lines and info to recalculate checkout total prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- fetch_checkout_data(checkout_info, plugins_manager, lines)
+ fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
app = app_api_client.app
expected_app_identifier = "webhook.app.identifier"
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index ca8c0bf44d..e1c4cdae3e 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -966,7 +966,9 @@ def test_checkout_when_amount_is_not_provided(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1265,7 +1267,9 @@ def test_checkout_with_transaction_when_amount_is_not_provided(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
checkout = checkout_info.checkout
expected_charged_amount = Decimal(10)
@@ -1332,7 +1336,9 @@ def test_app_with_action_field_and_handle_payments(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
@@ -1868,7 +1874,9 @@ def test_checkout_fully_paid(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1919,7 +1927,9 @@ def test_checkout_fully_paid_pending_charge(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1978,7 +1988,9 @@ def test_checkout_fully_authorized(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -2029,7 +2041,9 @@ def test_checkout_fully_authorized_pending_authorization(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -2360,10 +2374,8 @@ def test_updates_checkout_last_transaction_modified_at(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -2420,10 +2432,8 @@ def test_updates_checkout_search_index_dirty(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -3010,7 +3020,9 @@ def test_lock_checkout_during_updating_checkout_amounts(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -3069,7 +3081,9 @@ def test_transaction_initialize_checkout_completed_race_condition(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -3752,7 +3766,8 @@ def test_for_checkout_with_gift_card_payment_gateway_invalidates_previous_author
checkout_info=another_checkout_info,
manager=manager,
lines=[],
- )
+ requestor=user_api_client.user,
+ ).get()
assert (
another_checkout_info.checkout.authorize_status == CheckoutAuthorizeStatus.FULL
)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_process.py b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
index 1f1d54fdaa..8d6c0ee89a 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_process.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_process.py
@@ -1143,7 +1143,9 @@ def test_checkout_fully_paid(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1208,7 +1210,9 @@ def test_checkout_fully_paid_pending(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1282,7 +1286,9 @@ def test_checkout_fully_authorized(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1347,7 +1353,9 @@ def test_checkout_fully_authorized_pending(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -1845,10 +1853,8 @@ def test_updates_checkout_last_transaction_modified_at(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
checkout_info, _ = fetch_checkout_data(
- checkout_info,
- plugins_manager,
- lines,
- )
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -2529,7 +2535,9 @@ def test_lock_checkout_during_updating_checkout_amounts(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
@@ -2590,7 +2598,9 @@ def test_transaction_initialize_checkout_completed_race_condition(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=user_api_client.user
+ ).get()
expected_app_identifier = "webhook.app.identifier"
webhook_app.identifier = expected_app_identifier
webhook_app.save()
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index e33a4d880b..385277be35 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -2718,7 +2718,9 @@ def test_transaction_update_for_checkout_fully_paid(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.token),
@@ -2775,7 +2777,9 @@ def test_transaction_update_for_checkout_fully_authorized(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
variables = {
"id": graphene.Node.to_global_id("TransactionItem", transaction.token),
@@ -3725,7 +3729,9 @@ def test_lock_checkout_during_updating_checkout_amounts(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
assert checkout.channel.automatically_complete_fully_paid_checkouts is False
@@ -3775,7 +3781,9 @@ def test_transaction_update_checkout_completed_race_condition(
checkout = checkout_with_prices
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
- checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+ checkout_info, _ = fetch_checkout_data(
+ checkout_info, plugins_manager, lines, requestor=app_api_client.app
+ ).get()
assert checkout.channel.automatically_complete_fully_paid_checkouts is False
diff --git a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py b/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py
deleted file mode 100644
index 9b79578f63..0000000000
--- a/saleor/graphql/webhook/dataloaders/pregenerated_payload_for_checkout_tax.py
+++ /dev/null
@@ -1,151 +0,0 @@
-from collections import defaultdict
-from typing import Any
-
-from django.utils import timezone
-from promise import Promise
-
-from ....core.db.connection import allow_writer_in_context
-from ....core.utils.events import get_is_deferred_payload
-from ....tax import TaxCalculationStrategy
-from ....tax.utils import (
- get_tax_app_id,
- get_tax_calculation_strategy,
- get_tax_configuration_for_checkout,
-)
-from ....webhook.event_types import WebhookEventSyncType
-from ...app.dataloaders.apps import AppsByEventTypeLoader
-from ...checkout.dataloaders.checkout_infos import (
- CheckoutInfoByCheckoutTokenLoader,
- CheckoutLinesInfoByCheckoutTokenLoader,
-)
-from ...core import SaleorContext
-from ...core.dataloaders import DataLoader
-from ...utils import get_user_or_app_from_context
-from ..subscription_payload import (
- generate_payload_promise_from_subscription,
- initialize_request,
-)
-from ..utils import get_subscription_query_hash
-from .models import WebhooksByEventTypeLoader
-
-
-class PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader(DataLoader):
- context_key = "pregenerated_checkout_tax_payloads_by_checkout_token"
-
- def batch_load(self, keys):
- """Fetch pregenerated tax payloads for checkouts.
-
- This loader is used to fetch pregenerated tax payloads for checkouts.
-
- return: A dict of tax payloads for checkouts.
-
- Example:
- {
- "checkout_token": {
- "app_id": {
- "query_hash": {
- <payload>
- }
- }
- }
- }
-
- """
- results: dict[str, dict[int, dict[str, dict[str, Any]]]] = defaultdict(
- lambda: defaultdict(dict)
- )
- requestor = get_user_or_app_from_context(self.context)
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
-
- if requested_by_event_type := getattr(self.context, "event_type", None):
- # Skip sync payload generation when request is generated by
- # subscription for non-deferred ASYNC webhook. Sync webhooks in that case
- # are called before async webhook events.
- if not get_is_deferred_payload(requested_by_event_type):
- return [None for _ in keys]
-
- request_map: dict[int, SaleorContext] = {}
- dataloaders: dict[str, DataLoader] = {}
-
- @allow_writer_in_context(self.context)
- def generate_payloads(data):
- checkouts_info, checkout_lines_info, apps, webhooks = data
- apps_map = {app.id: app for app in apps}
- promises = []
-
- for checkout_info in checkouts_info:
- tax_configuration, country_tax_configuration = (
- get_tax_configuration_for_checkout(
- checkout_info, self.database_connection_name
- )
- )
- tax_strategy = get_tax_calculation_strategy(
- tax_configuration, country_tax_configuration
- )
-
- if (
- tax_strategy == TaxCalculationStrategy.TAX_APP
- and checkout_info.checkout.price_expiration <= timezone.now()
- ):
- tax_app_identifier = get_tax_app_id(
- tax_configuration, country_tax_configuration
- )
-
- for webhook in webhooks:
- app_id = webhook.app_id
- app = apps_map[app_id]
- if webhook.subscription_query and (
- not tax_app_identifier
- or app.identifier == tax_app_identifier
- ):
- request_context = request_map.get(app_id)
- if not request_context:
- request_context = initialize_request(
- app=app,
- requestor=requestor,
- sync_event=True,
- allow_replica=False,
- event_type=event_type,
- dataloaders=dataloaders,
- )
- request_map[app_id] = request_context
- query_hash = get_subscription_query_hash(
- webhook.subscription_query
- )
- checkout = checkout_info.checkout
- checkout_token = str(checkout.token)
- promise_payload = (
- generate_payload_promise_from_subscription(
- event_type=event_type,
- subscribable_object=checkout,
- subscription_query=webhook.subscription_query,
- request=request_context,
- )
- )
- promises.append(promise_payload)
-
- def store_payload(
- payload,
- checkout_token=checkout_token,
- app_id=app_id,
- query_hash=query_hash,
- ):
- if payload:
- results[checkout_token][app_id][query_hash] = (
- payload
- )
-
- promises.append(promise_payload.then(store_payload))
-
- def return_payloads(_payloads):
- return [results[str(checkout_token)] for checkout_token in keys]
-
- return Promise.all(promises).then(return_payloads)
-
- checkouts_info = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)
- lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)
- apps = AppsByEventTypeLoader(self.context).load(event_type)
- webhooks = WebhooksByEventTypeLoader(self.context).load(event_type)
- return Promise.all([checkouts_info, lines, apps, webhooks]).then(
- generate_payloads
- )
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
deleted file mode 100644
index 743d241c7e..0000000000
--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py
+++ /dev/null
@@ -1,492 +0,0 @@
-import datetime
-from unittest import mock
-
-from django.test import override_settings
-from django.utils import timezone
-
-from ....core.utils import to_global_id_or_none
-from ....tests.utils import get_graphql_content
-
-_line_tax_data = {
- "total_gross_amount": 2.5,
- "total_net_amount": 2,
- "tax_rate": 20,
-}
-TAX_DATA_RESPONSE = {
- "currency": "USD",
- "shipping_price_gross_amount": 10,
- "shipping_price_net_amount": 8,
- "shipping_tax_rate": 20,
- "lines": [_line_tax_data for _ in range(4)],
-}
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_total_price_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
- assert content["data"]["checkout"]["totalPrice"]["net"]["amount"] == 16
- assert content["data"]["checkout"]["totalPrice"]["gross"]["amount"] == 20
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_subtotal_price_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- subtotalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
- assert content["data"]["checkout"]["subtotalPrice"]["net"]["amount"] == 8
- assert content["data"]["checkout"]["subtotalPrice"]["gross"]["amount"] == 10
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_total_balance_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalBalance {
- amount
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
- assert content["data"]["checkout"]["totalBalance"]["amount"] == -20
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_shipping_price_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- shippingPrice {
- net {
- amount
- }
- gross {
- amount
- }
- tax {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
- assert content["data"]["checkout"]["shippingPrice"]["net"]["amount"] == 8
- assert content["data"]["checkout"]["shippingPrice"]["gross"]["amount"] == 10
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_authorize_status_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- authorizeStatus
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_charge_status_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- chargeStatus
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_line_unit_price_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- lines {
- unitPrice {
- net {
- amount
- }
- gross {
- amount
- }
- tax {
- amount
- }
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- assert content["data"]["checkout"]["id"] == checkout_global_id
- lines_data = content["data"]["checkout"]["lines"]
- assert lines_data[0]["unitPrice"]["net"]["amount"] == 2
- assert lines_data[0]["unitPrice"]["gross"]["amount"] == 2.5
- assert lines_data[1]["unitPrice"]["net"]["amount"] == 0.2
- assert lines_data[1]["unitPrice"]["gross"]["amount"] == 0.25
- assert lines_data[2]["unitPrice"]["net"]["amount"] == 0.67
- assert lines_data[2]["unitPrice"]["gross"]["amount"] == 0.83
- assert lines_data[3]["unitPrice"]["net"]["amount"] == 0.4
- assert lines_data[3]["unitPrice"]["gross"]["amount"] == 0.5
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_checkout_line_total_price_use_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- checkout_with_shipping_address,
- api_client,
- tax_app,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- lines {
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- tax {
- amount
- }
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = TAX_DATA_RESPONSE
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- assert content["data"]["checkout"]["id"] == checkout_global_id
- for line_data in content["data"]["checkout"]["lines"]:
- assert line_data["totalPrice"]["net"]["amount"] == 2
- assert line_data["totalPrice"]["gross"]["amount"] == 2.5
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
-
-
-CHECKOUTS_QUERY = """
- query CheckoutsQuery {
- checkouts(first: 1) {
- edges {
- node {
- id
- deliveryMethod {
- __typename
- ... on ShippingMethod {
- id
- name
- price {
- amount
- }
- }
- }
- shippingPrice {
- gross {
- amount
- }
- }
- totalPrice {
- gross {
- amount
- }
- }
- subtotalPrice {
- gross {
- amount
- }
- }
- lines {
- totalPrice {
- gross {
- amount
- }
- }
- unitPrice {
- gross {
- amount
- }
- }
- }
- shippingMethods {
- id
- name
- active
- }
- availableShippingMethods {
- id
- name
- active
- }
- }
- }
- }
- }
- """
-
-
- "saleor.graphql.checkout.types.PregeneratedCheckoutTaxPayloadsByCheckoutTokenLoader"
-)
-def test_pregegenerated_tax_payload_is_skipped_for_bulk_queries(
- mocked_pregenerated_payload,
- checkout_with_shipping_address,
- staff_api_client,
- permission_manage_checkouts,
-):
- # given
- checkout = checkout_with_shipping_address
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
-
- # when
- response = staff_api_client.post_graphql(
- CHECKOUTS_QUERY,
- permissions=[permission_manage_checkouts],
- )
- content = get_graphql_content(response)
-
- # then
- assert len(content["data"]["checkouts"]["edges"]) == 1
- checkout = content["data"]["checkouts"]["edges"][0]["node"]
- assert checkout["id"] == checkout_global_id
-
- mocked_pregenerated_payload.assert_not_called()
diff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
deleted file mode 100644
index ae6c3d4ca3..0000000000
--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_tax_configurations_with_pregenerated_payloads.py
+++ /dev/null
@@ -1,383 +0,0 @@
-import datetime
-from collections import defaultdict
-from unittest import mock
-
-from django.test import override_settings
-from django.utils import timezone
-
-from .....checkout.calculations import fetch_checkout_data
-from .....tax import TaxCalculationStrategy
-from .....tax.models import TaxConfiguration
-from ....core.utils import to_global_id_or_none
-from ....tests.utils import get_graphql_content
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_selected_tax_app_price_entered_with_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- tax_app,
-):
- # given
- tax_app_global_id = to_global_id_or_none(tax_app)
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = True
- tax_configuration.tax_app_id = tax_app_global_id
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = tax_data_response
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_selected_tax_app_price_entered_without_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- tax_app,
-):
- # given
- tax_app_global_id = to_global_id_or_none(tax_app)
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = False
- tax_configuration.tax_app_id = tax_app_global_id
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = tax_data_response
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_selected_external_tax_app_price_entered_without_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- external_tax_app,
-):
- # given
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = False
- tax_configuration.tax_app_id = external_tax_app.identifier
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = tax_data_response
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_selected_external_tax_app_price_entered_with_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- external_tax_app,
-):
- # given
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = True
- tax_configuration.tax_app_id = external_tax_app.identifier
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = tax_data_response
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- mock_request.assert_called_once()
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_all_apps_price_entered_with_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- tax_app,
- external_tax_app,
-):
- # given
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = True
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- # Set response for tax calculation to None to ensure that all apps are called
- mock_request.return_value = None
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- assert mock_request.call_count == 2
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
-def test_pregenerated_payload_with_all_apps_price_entered_without_tax(
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- tax_app,
- external_tax_app,
-):
- # given
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = False
- tax_configuration.save()
- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- # Set response for tax calculation to None to ensure that all apps are called
- mock_request.return_value = None
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- mock_generate_payload.assert_not_called()
- assert mock_request.call_count == 2
- assert content["data"]["checkout"]["id"] == checkout_global_id
-
-
-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
- "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
-)
- "saleor.checkout.calculations.fetch_checkout_data",
- wraps=fetch_checkout_data,
-)
-def test_pregenerated_payload_skipped_when_checkout_not_expired(
- mock_fetch_checkout_data,
- mock_generate_payload,
- mock_request,
- checkout,
- api_client,
- tax_data_response,
- tax_app,
-):
- # given
- tax_app_global_id = to_global_id_or_none(tax_app)
- tax_configuration = TaxConfiguration.objects.get()
- tax_configuration.tax_calculation_strategy = TaxCalculationStrategy.TAX_APP
- tax_configuration.prices_entered_with_tax = True
- tax_configuration.tax_app_id = tax_app_global_id
- tax_configuration.save()
- checkout.price_expiration = timezone.now() + datetime.timedelta(days=1)
- checkout.save()
- checkout_global_id = to_global_id_or_none(checkout)
- checkout_total_price_query = """
- query getCheckout($id: ID!) {
- checkout(id: $id) {
- id
- totalPrice {
- net {
- amount
- }
- gross {
- amount
- }
- }
- }
- }
- """
- variables = {"id": checkout_global_id}
-
- mock_request.return_value = tax_data_response
-
- # when
- response = api_client.post_graphql(checkout_total_price_query, variables)
- content = get_graphql_content(response)
-
- # then
- assert content["data"]["checkout"]["id"] == checkout_global_id
- mock_generate_payload.assert_not_called()
- mock_request.assert_not_called()
- mock_fetch_checkout_data.assert_called_once()
- assert mock_fetch_checkout_data.call_args.kwargs[
- "pregenerated_subscription_payloads"
- ] == defaultdict(dict)
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index efad068331..fb9ec450aa 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -6,7 +6,7 @@ from django.test import override_settings
from ...channel import MarkAsPaidStrategy
from ...core.models import EventDelivery
-from ...core.utils.events import call_event_including_protected_events
+from ...core.utils.events import call_event
from ...giftcard import GiftCardEvents
from ...giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from ...giftcard.models import GiftCard, GiftCardEvent
@@ -2365,13 +2365,10 @@ def test_call_order_event_incorrect_webhook_event(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.core.utils.events.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
+@patch("saleor.order.actions.call_event", wraps=call_event)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_order_for_draft_order_deleted(
- mocked_call_event_including_protected_events,
+ mocked_call_event,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
mocked_cache,
@@ -2427,7 +2424,7 @@ def test_call_order_for_draft_order_deleted(
)
assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- mocked_call_event_including_protected_events.assert_called_once_with(
+ mocked_call_event.assert_called_once_with(
ANY, order_with_lines, webhooks={order_webhook}
)
@@ -2528,13 +2525,10 @@ def test_call_order_events_incorrect_webhook_event(
@patch(
"saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"
)
-@patch(
- "saleor.core.utils.events.call_event_including_protected_events",
- wraps=call_event_including_protected_events,
-)
+@patch("saleor.order.actions.call_event", wraps=call_event)
@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
def test_call_order_events_for_draft_order_deleted(
- mocked_call_event_including_protected_events,
+ mocked_call_event,
mocked_send_webhook_request_async,
mocked_send_webhook_request_sync,
mocked_cache,
@@ -2594,7 +2588,7 @@ def test_call_order_events_for_draft_order_deleted(
)
assert filter_shipping_call.kwargs["timeout"] == settings.WEBHOOK_SYNC_TIMEOUT
- mocked_call_event_including_protected_events.assert_has_calls(
+ mocked_call_event.assert_has_calls(
[
call(
plugins_manager.draft_order_deleted,
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
index 8a74fc6b17..02487d08f9 100644
--- a/saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py
+++ b/saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py
@@ -9,6 +9,7 @@ from freezegun import freeze_time
from .....core.prices import quantize_price
from .....discount import DiscountType, DiscountValueType, VoucherType
+from .....webhook.serializers import serialize_variant_full_name
from ....webhooks.order_calculate_taxes import (
generate_order_payload_for_tax_calculation,
)
@@ -120,7 +121,9 @@ def test_generate_order_payload_for_tax_calculation(
"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,
+ "full_name": (
+ serialize_variant_full_name(line.variant) if line.variant else None
+ ),
"product_metadata": (
line.variant.product.metadata if line.variant else {}
),
@@ -347,7 +350,7 @@ def test_order_lines_for_tax_calculation_have_all_required_fields(
"type": "OrderLine",
"id": line_id,
"variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "full_name": variant.display_product(),
+ "full_name": serialize_variant_full_name(variant),
"product_name": line.product_name,
"variant_name": line.variant_name,
"product_metadata": {"product_meta": "value"},
diff --git a/saleor/order/webhooks/order_calculate_taxes.py b/saleor/order/webhooks/order_calculate_taxes.py
index 44d3d52c2a..cb082afefe 100644
--- a/saleor/order/webhooks/order_calculate_taxes.py
+++ b/saleor/order/webhooks/order_calculate_taxes.py
@@ -17,6 +17,7 @@ from ...tax.webhooks import shared
from ...webhook import traced_payload_generator
from ...webhook.event_types import WebhookEventSyncType
from ...webhook.payload_serializers import PayloadSerializer
+from ...webhook.serializers import serialize_variant_full_name
from ..models import Order, OrderLine
if TYPE_CHECKING:
@@ -40,7 +41,9 @@ def _generate_order_lines_payload_for_tax_calculation(lines: QuerySet[OrderLine]
extra_dict_data={
"variant_id": (lambda line: line.product_variant_id),
"full_name": (
- lambda line: line.variant.display_product() if line.variant else None
+ lambda line: (
+ serialize_variant_full_name(line.variant) if line.variant else None
+ )
),
"product_metadata": (
lambda line: line.variant.product.metadata if line.variant else {}
diff --git a/saleor/payment/gateways/stripe/tests/conftest.py b/saleor/payment/gateways/stripe/tests/conftest.py
index a0b6589ed3..60bf9adeea 100644
--- a/saleor/payment/gateways/stripe/tests/conftest.py
+++ b/saleor/payment/gateways/stripe/tests/conftest.py
@@ -23,7 +23,7 @@ def payment_stripe_for_checkout(checkout_with_items, address, checkout_delivery)
lines, _ = fetch_checkout_lines(checkout_with_items)
checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
payment = create_payment(
gateway=StripeGatewayPlugin.PLUGIN_ID,
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index f7de361432..98628c3c55 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -414,10 +414,7 @@ def test_handle_successful_payment_intent_checkout_with_voucher_ongoing_completi
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- address = customer_user.default_billing_address
- total = calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
- )
+ total = calculate_checkout_total_with_gift_cards(manager, checkout_info, lines)
# set voucher usage limit to 1
voucher_free_shipping.usage_limit = 1
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 98b3212df6..8cc0f80c5c 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -195,7 +195,6 @@ def _finalize_checkout(
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=checkout.shipping_address or checkout.billing_address,
)
try:
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index dff263f910..c53bb95ee2 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -120,7 +120,7 @@ def test_create_payment(checkout_with_item, address):
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
data = {
@@ -161,7 +161,7 @@ def test_create_payment_from_checkout_requires_billing_address(checkout_with_ite
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=None
+ manager=manager, checkout_info=checkout_info, lines=lines
)
data = {
@@ -203,7 +203,7 @@ def test_create_payment_information_for_checkout_payment(address, checkout_with_
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
data = {
@@ -339,7 +339,7 @@ def test_create_payment_information_store(checkout_with_item, address, store):
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
data = {
@@ -374,7 +374,7 @@ def test_create_payment_information_metadata(checkout_with_item, address, metada
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, manager)
total = calculate_checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ manager=manager, checkout_info=checkout_info, lines=lines
)
data = {
diff --git a/saleor/payment/tests/test_utils/test_utils.py b/saleor/payment/tests/test_utils/test_utils.py
index 21bfa1b50b..9f2274266d 100644
--- a/saleor/payment/tests/test_utils/test_utils.py
+++ b/saleor/payment/tests/test_utils/test_utils.py
@@ -110,7 +110,6 @@ def get_expected_checkout_payment_lines(manager, checkout_info, lines, address):
manager=manager,
checkout_info=checkout_info,
lines=lines,
- address=address,
).gross.amount
return PaymentLinesData(
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 17359a9c5a..d90cf079cf 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -185,7 +185,6 @@ def create_checkout_payment_lines_information(
line_items = []
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- address = checkout_info.shipping_address or checkout_info.billing_address
for line_info in lines:
unit_price = calculations.checkout_line_unit_price(
@@ -209,10 +208,7 @@ def create_checkout_payment_lines_information(
)
)
shipping_amount = calculations.checkout_shipping_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
+ manager=manager, checkout_info=checkout_info, lines=lines
).gross.amount
voucher_amount = -checkout.discount_amount
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 215c52cec9..de702ba398 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -42,7 +42,7 @@ if TYPE_CHECKING:
from ..checkout.models import Checkout
from ..core.middleware import Requestor
from ..core.notify import NotifyEventType
- from ..core.taxes import TaxData, TaxType
+ from ..core.taxes import TaxType
from ..core.utils.translations import Translation
from ..csv.models import ExportFile
from ..discount.models import Promotion, PromotionRule, Voucher, VoucherCode
@@ -720,13 +720,6 @@ class BasePlugin:
Any,
]
- # 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_checkout: Callable[
- ["CheckoutInfo", list["CheckoutLineInfo"], str, Any, dict | None],
- 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 c1469289ef..dbbb580161 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -629,26 +629,6 @@ class PluginsManager(PaymentInterface):
or default_value
)
- # 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_checkout(
- self,
- checkout_info,
- lines,
- app_identifier,
- pregenerated_subscription_payloads: dict | None = None,
- ) -> TaxData | None:
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
- return self.__run_tax_method_until_first_success(
- "get_taxes_for_checkout",
- checkout_info,
- lines,
- app_identifier,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- channel_slug=checkout_info.channel.slug,
- )
-
def __run_tax_method_until_first_success(
self,
method_name: str,
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 8fae3d455a..01f86c28e8 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -6,7 +6,7 @@ from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from prices import Money, TaxedMoney
from ...account.models import User
-from ...core.taxes import TaxData, TaxLineData, TaxType
+from ...core.taxes import TaxType
from ...graphql.core import SaleorContext
from ...order.interface import OrderTaxedPricesData
from ...payment.interface import (
@@ -26,29 +26,6 @@ if TYPE_CHECKING:
from ...product.models import Product, ProductVariant
-def sample_tax_data(obj_with_lines: Union["Order", "Checkout"]) -> TaxData:
- unit = Decimal("10.00")
- unit_gross = Decimal("12.30")
- lines = [
- TaxLineData(
- total_net_amount=unit * 3,
- total_gross_amount=unit_gross * 3,
- tax_rate=Decimal(23),
- )
- for _ in obj_with_lines.lines.all()
- ]
-
- shipping = Decimal("50.00")
- shipping_gross = Decimal("63.20")
-
- return TaxData(
- shipping_price_net_amount=shipping,
- shipping_price_gross_amount=shipping_gross,
- shipping_tax_rate=Decimal(23),
- lines=lines,
- )
-
-
class PluginSample(BasePlugin):
PLUGIN_ID = "plugin.sample"
PLUGIN_NAME = "PluginSample"
@@ -288,16 +265,6 @@ class PluginSample(BasePlugin):
def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
return Decimal("0.080").quantize(Decimal(".01"))
- def get_taxes_for_checkout(
- self,
- checkout_info: "CheckoutInfo",
- lines,
- app_identifier,
- previous_value,
- pregenerated_subscription_payloads=None,
- ) -> Optional["TaxData"]:
- return sample_tax_data(checkout_info.checkout)
-
def sample_not_implemented(self, previous_value):
return NotImplemented
diff --git a/saleor/plugins/tests/test_manager_get_taxes.py b/saleor/plugins/tests/test_manager_get_taxes.py
deleted file mode 100644
index f3e63d3f1f..0000000000
--- a/saleor/plugins/tests/test_manager_get_taxes.py
+++ /dev/null
@@ -1,120 +0,0 @@
-from unittest.mock import patch
-
-import pytest
-
-from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ...core.taxes import TaxDataError
-from ..manager import PluginsManager, get_plugins_manager
-from ..tests.sample_plugins import sample_tax_data
-
-
-def sample_none_data(obj):
- return None
-
-
- ("plugins", "expected_tax_data"),
- [
- ([], sample_none_data),
- (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
- ],
-)
-def test_manager_get_taxes_for_checkout(
- checkout,
- plugins,
- expected_tax_data,
-):
- # given
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins=plugins).get_taxes_for_checkout(
- checkout_info, lines, app_identifier
- )
-
- # then
- assert tax_data == expected_tax_data(checkout)
-
-
-@patch(
- "saleor.plugins.webhook.plugin.WebhookPlugin.get_taxes_for_checkout",
- side_effect=TaxDataError("test error"),
-)
-def test_manager_get_taxes_for_checkout_raises_error(
- mocked_get_taxes_for_checkout,
- checkout,
-):
- # given
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- app_identifier = None
- plugins = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- # when & then
- with pytest.raises(TaxDataError):
- PluginsManager(plugins=plugins).get_taxes_for_checkout(
- checkout_info, lines, app_identifier
- )
-
- mocked_get_taxes_for_checkout.assert_called_once()
-
-
-def test_manager_get_taxes_for_checkout_raises_no_active_plugin(
- checkout,
-):
- # given
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins=[]).get_taxes_for_checkout(
- checkout_info, lines, 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_checkout",
- side_effect=TaxDataError("test error"),
-)
-def test_manager_get_taxes_for_checkout_multiple_plugins(
- mocked_get_taxes_for_checkout,
- plugins,
- checkout,
-):
- # given
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- app_identifier = None
-
- # when
- tax_data = PluginsManager(plugins).get_taxes_for_checkout(
- checkout_info, lines, app_identifier
- )
-
- # then
- assert tax_data == sample_tax_data(checkout)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index bbd3fc4cd0..2d0c4aa2ae 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -17,7 +17,7 @@ from ...checkout.models import Checkout
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ...core.notify import NotifyEventType
-from ...core.taxes import TaxData, TaxDataError, TaxType
+from ...core.taxes import TaxType
from ...core.telemetry import get_task_context
from ...core.utils import build_absolute_uri, get_domain
from ...core.utils.json_serializer import CustomJsonEncoder
@@ -60,13 +60,11 @@ 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
from ...webhook.payloads import (
generate_checkout_payload,
- generate_checkout_payload_for_tax_calculation,
generate_collection_payload,
generate_customer_payload,
generate_fulfillment_payload,
@@ -111,7 +109,6 @@ from ...webhook.transport.payment import (
parse_payment_action_response,
)
from ...webhook.transport.synchronous.transport import (
- trigger_taxes_all_webhooks_sync,
trigger_transaction_request,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
@@ -3462,97 +3459,6 @@ class WebhookPlugin(BasePlugin):
**kwargs,
)
- def __run_tax_webhook(
- self,
- event_type: str,
- app_identifier: str,
- payload_gen: Callable,
- expected_lines_count: int,
- subscriptable_object=None,
- pregenerated_subscription_payloads: dict | None = None,
- ) -> TaxData:
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
- 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)
- raise 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)
- raise TaxDataError(msg)
-
- request_context = initialize_request(
- app=app,
- requestor=self.requestor,
- sync_event=event_type in WebhookEventSyncType.ALL,
- allow_replica=False,
- event_type=event_type,
- )
-
- pregenerated_subscription_payload = get_pregenerated_subscription_payload(
- webhook, pregenerated_subscription_payloads
- )
- response = trigger_webhook_sync(
- event_type=event_type,
- webhook=webhook,
- payload=payload_gen(),
- allow_replica=False,
- subscribable_object=subscriptable_object,
- request=request_context,
- requestor=self.requestor,
- pregenerated_subscription_payload=pregenerated_subscription_payload,
- )
- return parse_tax_data(event_type, response, expected_lines_count)
-
- def get_taxes_for_checkout(
- self,
- checkout_info,
- lines,
- app_identifier,
- previous_value,
- pregenerated_subscription_payloads: dict | None = None,
- ) -> TaxData | None:
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- lines_count = len(lines)
- if app_identifier:
- return self.__run_tax_webhook(
- event_type,
- app_identifier,
- lambda: generate_checkout_payload_for_tax_calculation(
- checkout_info, lines
- ),
- lines_count,
- checkout_info.checkout,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- )
- # 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(
- event_type,
- lambda: generate_checkout_payload_for_tax_calculation(
- checkout_info,
- lines,
- ),
- lines_count,
- checkout_info.checkout,
- self.requestor,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- )
-
def get_tax_code_from_object_meta(
self,
obj: Union["Product", "ProductType", "TaxClass"],
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index 4a34bb9425..fca480e310 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -1,40 +1,8 @@
-import json
-from unittest import mock
-from unittest.mock import ANY, sentinel
+from unittest.mock import sentinel
import pytest
-from freezegun import freeze_time
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-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 ...manager import get_plugins_manager
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_get_taxes_for_checkout_no_permission(
- mock_request,
- webhook_plugin,
- checkout,
-):
- # given
- plugin = webhook_plugin()
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(
- checkout, lines, get_plugins_manager(allow_replica=False)
- )
- app_identifier = None
-
- # when
- tax_data = plugin.get_taxes_for_checkout(checkout_info, lines, app_identifier, None)
-
- # then
- assert mock_request.call_count == 0
- assert tax_data is None
+from ....core.taxes import TaxType
@pytest.fixture
@@ -96,270 +64,3 @@ def test_get_tax_code_from_object_meta_default_code(
code="UNMAPPED",
description="Unmapped Product/Product Type",
)
-
-
-@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[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_checkout_with_sync_subscription(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- checkout,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- checkout_info = fetch_checkout_info(
- checkout, [], get_plugins_manager(allow_replica=False)
- )
- 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 = None
-
- # when
- tax_data = plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
-
- # then
- mock_generate_payload.assert_called_once_with(
- event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- subscribable_object=checkout,
- subscription_query=subscription_query,
- request=ANY, # SaleorContext,
- )
- 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.CHECKOUT_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- tax_data_response,
- checkout.lines.count(),
- )
-
-
-@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[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_checkout_with_sync_subscription_with_pregenerated_payload(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- checkout,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- subscription_query_hash = get_subscription_query_hash(subscription_query)
- expected_payload = {"taxBase": {"currency": "USD"}}
- checkout_info = fetch_checkout_info(
- checkout, [], get_plugins_manager(allow_replica=False)
- )
- mock_request.return_value = tax_data_response
- 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 = None
- pregenerated_subscription_payloads = {
- webhook.app.id: {subscription_query_hash: expected_payload}
- }
-
- # when
- tax_data = plugin.get_taxes_for_checkout(
- checkout_info,
- [],
- app_identifier,
- None,
- pregenerated_subscription_payloads=pregenerated_subscription_payloads,
- )
-
- # then
- mock_generate_payload.assert_not_called()
- 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.CHECKOUT_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- 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(
- checkout_info, 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_checkout(
- checkout_info, checkout_info.lines, app_identifier, None
- )
-
-
-def test_get_taxes_for_checkout_with_app_identifier_webhook_is_missing(
- checkout_info, 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_checkout(
- checkout_info, checkout_info.lines, app.identifier, None
- )
-
-
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[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_checkout_with_app_identifier_invalid_response(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response_factory,
- checkout,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- checkout_info = fetch_checkout_info(
- checkout, [], get_plugins_manager(allow_replica=False)
- )
- # 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
- with pytest.raises(TaxDataError):
- plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
-
-
-@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[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_checkout_with_app_identifier(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- checkout,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- checkout_info = fetch_checkout_info(
- checkout, [], get_plugins_manager(allow_replica=False)
- )
- 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_checkout(checkout_info, [], app_identifier, None)
-
- # then
- mock_generate_payload.assert_called_once_with(
- event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- subscribable_object=checkout,
- subscription_query=subscription_query,
- request=ANY, # SaleorContext,
- )
- 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.CHECKOUT_CALCULATE_TAXES
- assert delivery.webhook == webhook
- mock_fetch.assert_not_called()
- assert tax_data == parse_tax_data(
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- tax_data_response,
- checkout.lines.count(),
- )
-
-
-@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_data")
[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_checkout_with_app_identifier_empty_response(
- mock_generate_payload,
- mock_request,
- mock_fetch,
- webhook_plugin,
- tax_data_response,
- checkout,
- tax_app,
-):
- # given
- subscription_query = "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
- expected_payload = {"taxBase": {"currency": "USD"}}
- checkout_info = fetch_checkout_info(
- checkout, [], get_plugins_manager(allow_replica=False)
- )
- mock_request.return_value = None
- 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_checkout(checkout_info, [], app_identifier, None)
diff --git a/saleor/product/models.py b/saleor/product/models.py
index fe08f8586b..e830422264 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -27,7 +27,7 @@ from ..core.models import (
SortableModel,
)
from ..core.units import WeightUnits
-from ..core.utils.translations import Translation, get_translation
+from ..core.utils.translations import Translation
from ..core.weight import zero_weight
from ..discount.models import PromotionRule
from ..permission.enums import (
@@ -442,18 +442,6 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferenc
def is_gift_card(self) -> bool:
return self.product.product_type.kind == ProductTypeKind.GIFT_CARD
- def display_product(self, translated: bool = False) -> str:
- if translated:
- product = get_translation(self.product).name or ""
- variant_display = get_translation(self).name
- else:
- variant_display = str(self)
- product = self.product
- product_display = (
- f"{product} ({variant_display})" if variant_display else str(product)
- )
- return product_display
-
def get_ordering_queryset(self):
return self.product.variants.all()
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index e0bdf028e4..64cde2a887 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -85,7 +85,7 @@ def test_calculate_checkout_total_with_gift_cards(
)
total = calculations.calculate_checkout_total_with_gift_cards(
- manager, checkout_info, lines, address
+ manager, checkout_info, lines
)
assert total.net == Money(expected_total_net, "USD")
diff --git a/saleor/tax/tests/webhooks/test_shared.py b/saleor/tax/tests/webhooks/test_shared.py
index dd7c84c5b8..3ae1a7e1ac 100644
--- a/saleor/tax/tests/webhooks/test_shared.py
+++ b/saleor/tax/tests/webhooks/test_shared.py
@@ -10,8 +10,6 @@ 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,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index af254fa453..1428120d56 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -12,7 +12,6 @@ from django.db.models import F, QuerySet, Sum
from ..account.models import User
from ..attribute.models import AttributeValueTranslation
-from ..checkout import base_calculations
from ..checkout.models import Checkout
from ..checkout.utils import get_checkout_metadata
from ..core.db.connection import allow_writer
@@ -24,7 +23,6 @@ from ..core.utils.anonymization import (
generate_fake_user,
)
from ..core.utils.json_serializer import CustomJsonEncoder
-from ..discount.utils.voucher import is_order_level_voucher
from ..order import FulfillmentStatus, OrderStatus
from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ..order.utils import get_order_country
@@ -43,14 +41,12 @@ from .payload_helpers import generate_meta, generate_requestor
from .payload_serializers import PayloadSerializer
from .serializers import (
serialize_checkout_lines,
- serialize_checkout_lines_for_tax_calculation,
serialize_product_attributes,
serialize_variant_attributes,
)
from .transport.utils import from_payment_app_id
if TYPE_CHECKING:
- from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..discount.models import Promotion
from ..invoice.models import Invoice
from ..payment.interface import (
@@ -1207,95 +1203,6 @@ def generate_translation_payload(
return json.dumps(translation_data)
-@allow_writer()
-@traced_payload_generator
-def generate_checkout_payload_for_tax_calculation(
- checkout_info: "CheckoutInfo",
- lines: list["CheckoutLineInfo"],
-):
- checkout = checkout_info.checkout
- tax_configuration = checkout_info.tax_configuration
- prices_entered_with_tax = tax_configuration.prices_entered_with_tax
-
- serializer = PayloadSerializer()
-
- checkout_fields = ("currency",)
-
- # Prepare checkout data
- address = checkout_info.shipping_address or checkout_info.billing_address
-
- total_amount = quantize_price(
- base_calculations.base_checkout_total(checkout_info, lines).amount,
- checkout.currency,
- )
-
- # Prepare user data
- user = checkout_info.user
- user_id = None
- user_public_metadata = {}
- if user:
- user_id = graphene.Node.to_global_id("User", user.id)
- user_public_metadata = user.metadata
-
- # order promotion discount and entire_order voucher discount with
- # apply_once_per_order set to False is not already included in the total price
- discounted_object_promotion = bool(checkout_info.discounts)
- discount_not_included = discounted_object_promotion or is_order_level_voucher(
- checkout_info.voucher
- )
- if not checkout.discount_amount:
- discounts = []
- else:
- discount_amount = quantize_price(checkout.discount_amount, checkout.currency)
- discount_name = checkout.discount_name
- discounts = (
- [{"name": discount_name, "amount": discount_amount}]
- if discount_amount and discount_not_included
- else []
- )
-
- # Prepare shipping data
- assigned_delivery = checkout.assigned_delivery
- shipping_method_name = None
- if assigned_delivery:
- shipping_method_name = assigned_delivery.name
- shipping_method_amount = quantize_price(
- base_calculations.base_checkout_delivery_price(checkout_info, lines).amount,
- checkout.currency,
- )
-
- # Prepare line data
- lines_dict_data = serialize_checkout_lines_for_tax_calculation(checkout_info, lines)
-
- checkout_data = serializer.serialize(
- [checkout],
- fields=checkout_fields,
- pk_field_name="token",
- additional_fields={
- "channel": (lambda c: c.channel, CHANNEL_FIELDS),
- "address": (lambda _: address, ADDRESS_FIELDS),
- },
- extra_dict_data={
- "user_id": user_id,
- "user_public_metadata": user_public_metadata,
- "included_taxes_in_prices": prices_entered_with_tax,
- "total_amount": total_amount,
- "shipping_amount": shipping_method_amount,
- "shipping_name": shipping_method_name,
- "discounts": discounts,
- "lines": lines_dict_data,
- "metadata": (
- lambda c=checkout: (
- get_checkout_metadata(c).metadata # type: ignore[union-attr]
- if hasattr(c, "metadata_storage")
- else {}
- )
- ),
- },
- )
- return checkout_data
-
-
@allow_writer()
@traced_payload_generator
def generate_transaction_action_request_payload(
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index c5334042a6..0881d8ddbc 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -7,19 +7,33 @@ import graphene
from prices import Money
from ..attribute import AttributeEntityType, AttributeInputType
-from ..checkout import base_calculations
from ..checkout.fetch import fetch_checkout_lines
from ..core.prices import quantize_price
from ..product.models import Product
-from ..tax.utils import get_charge_taxes_for_checkout
if TYPE_CHECKING:
# pylint: disable=unused-import
- from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..product.models import ProductVariant
+def serialize_variant_full_name(
+ variant: "ProductVariant", product: Product | None = None
+) -> str:
+ if product:
+ assert product.id == variant.product_id, (
+ "Product does not belong to provided variant."
+ )
+ else:
+ product = variant.product
+
+ variant_display = str(variant)
+ product_display = (
+ f"{product} ({variant_display})" if variant_display else str(product)
+ )
+ return product_display
+
+
def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:
data = []
channel = checkout.channel
@@ -47,7 +61,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:
"quantity": line_info.line.quantity,
"base_price": str(quantize_price(base_price.amount, currency)),
"currency": currency,
- "full_name": variant.display_product(),
+ "full_name": serialize_variant_full_name(variant),
"product_name": product.name,
"variant_name": variant.name,
"attributes": serialize_variant_attributes(variant),
@@ -56,45 +70,6 @@ def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:
return data
-def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> dict[str, Any]:
- line_id = graphene.Node.to_global_id("CheckoutLine", line_info.line.pk)
- variant = line_info.variant
- product = variant.product
- return {
- "id": line_id,
- "sku": variant.sku,
- "variant_id": variant.get_global_id(),
- "quantity": line_info.line.quantity,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "product_metadata": line_info.product.metadata,
- "product_type_metadata": line_info.product_type.metadata,
- }
-
-
-def serialize_checkout_lines_for_tax_calculation(
- checkout_info: "CheckoutInfo",
- lines: list["CheckoutLineInfo"],
-) -> list[dict]:
- charge_taxes = get_charge_taxes_for_checkout(checkout_info)
- return [
- {
- **_get_checkout_line_payload_data(line_info),
- "charge_taxes": charge_taxes,
- "unit_amount": quantize_price(
- base_calculations.calculate_base_line_unit_price(line_info).amount,
- checkout_info.checkout.currency,
- ),
- "total_amount": quantize_price(
- base_calculations.calculate_base_line_total_price(line_info).amount,
- checkout_info.checkout.currency,
- ),
- }
- for line_info in lines
- ]
-
-
def serialize_product_attributes(product: "Product") -> list[dict]:
data = []
diff --git a/saleor/webhook/tests/test_tax_webhook_tasks.py b/saleor/webhook/tests/test_tax_webhook_tasks.py
deleted file mode 100644
index bc3cc7ec94..0000000000
--- a/saleor/webhook/tests/test_tax_webhook_tasks.py
+++ /dev/null
@@ -1,144 +0,0 @@
-from unittest import mock
-
-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
-
-
-def tax_checkout_webhooks(tax_app):
- tax_app.webhooks.all().delete()
- webhooks = [
- Webhook(
- name=f"Tax checkout webhook no {i}",
- app=tax_app,
- target_url=f"https://www.example.com/tax-checkout-{i}",
- )
- for i in range(3)
- ]
- Webhook.objects.bulk_create(webhooks)
- WebhookEvent.objects.bulk_create(
- WebhookEvent(
- event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- webhook=webhook,
- )
- for webhook in webhooks
- )
-
- return list(
- Webhook.objects.filter(
- events__event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- )
- )
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_trigger_tax_webhook_sync(
- mock_request,
- tax_app,
- tax_data_response,
-):
- # given
- mock_request.return_value = tax_data_response
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- data = '{"key": "value"}'
- webhook = tax_app.webhooks.get(name="tax-webhook-1")
- webhook.subscription_query = None
- webhook.save(update_fields=["subscription_query"])
- lines_count = len(tax_data_response["lines"])
-
- # when
- tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
-
- # then
- mock_request.assert_called_once()
- assert not EventDelivery.objects.exists()
- delivery = mock_request.mock_calls[0].args[0]
-
- assert delivery.payload.get_payload() == data
- 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)
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_trigger_tax_webhook_sync_multiple_webhooks_first(
- mock_request,
- tax_checkout_webhooks,
- tax_data_response,
-):
- # given
- mock_request.side_effect = [tax_data_response, {}, {}]
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- data = '{"key": "value"}'
- lines_count = len(tax_data_response["lines"])
-
- # when
- tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
-
- # then
- successful_webhook = tax_checkout_webhooks[0]
- mock_request.assert_called_once()
- assert not EventDelivery.objects.exists()
- delivery = mock_request.mock_calls[0].args[0]
- assert delivery.payload.get_payload() == data
- assert delivery.status == EventDeliveryStatus.PENDING
- assert delivery.event_type == event_type
- assert delivery.webhook == successful_webhook
- assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_trigger_tax_webhook_sync_multiple_webhooks_last(
- mock_request,
- tax_checkout_webhooks,
- tax_data_response,
-):
- # given
- mock_request.side_effect = [{}, {}, tax_data_response]
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- data = '{"key": "value"}'
- lines_count = len(tax_data_response["lines"])
-
- # when
- tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, lines_count)
-
- # then
- assert mock_request.call_count == 3
- assert not EventDelivery.objects.exists()
-
- for call, webhook in zip(
- mock_request.mock_calls, tax_checkout_webhooks, strict=False
- ):
- delivery = call.args[0]
- assert delivery.status == EventDeliveryStatus.PENDING
- assert delivery.event_type == event_type
- assert delivery.payload.get_payload() == data
- assert delivery.webhook == webhook
-
- assert tax_data == parse_tax_data(event_type, tax_data_response, lines_count)
-
-
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
-def test_trigger_tax_webhook_sync_invalid_webhooks(
- mock_request,
- tax_checkout_webhooks,
- tax_data_response,
-):
- # given
- mock_request.return_value = {}
- event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
- data = '{"key": "value"}'
-
- # when
- tax_data = trigger_taxes_all_webhooks_sync(event_type, lambda: data, 0)
-
- # then
- assert mock_request.call_count == len(tax_checkout_webhooks)
- assert tax_data is None
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 09d91d7dec..2cdfb27422 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -4,24 +4,18 @@ from dataclasses import asdict
from decimal import Decimal
from itertools import chain
from unittest import mock
-from unittest.mock import ANY, patch, sentinel
+from unittest.mock import ANY, sentinel
import graphene
import pytest
from django.contrib.sites.models import Site
from django.core.serializers.json import DjangoJSONEncoder
from freezegun import freeze_time
-from prices import Money
from ... import __version__
-from ...checkout import base_calculations
-from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-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
-from ...discount.models import CheckoutDiscount, CheckoutLineDiscount
+from ...discount import DiscountType, DiscountValueType
from ...graphql.utils import get_user_or_app_from_context
from ...order import FulfillmentLineData, OrderOrigin
from ...order.actions import fulfill_order_lines
@@ -31,14 +25,13 @@ from ...payment import TransactionAction, TransactionEventType
from ...payment.interface import RefundData, TransactionActionData, TransactionData
from ...payment.models import TransactionItem
from ...plugins.manager import get_plugins_manager
-from ...product.models import ProductVariant, ProductVariantChannelListing
+from ...product.models import ProductVariant
from ...warehouse import WarehouseClickAndCollectOption
from ..payloads import (
PRODUCT_VARIANT_FIELDS,
_generate_collection_point_payload,
_generate_refund_data_payload,
generate_checkout_payload,
- generate_checkout_payload_for_tax_calculation,
generate_collection_payload,
generate_customer_payload,
generate_fulfillment_lines_payload,
@@ -1437,662 +1430,6 @@ def test_generate_sale_toggle_payload(promotion_converted_from_sale):
assert graphene.Node.to_global_id("Sale", promotion.old_sale_id) == payload["id"]
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_entire_order_voucher(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_prices,
- prices_entered_with_tax,
- voucher,
-):
- checkout = checkout_with_prices
- currency = checkout.currency
-
- voucher.name = "Voucher 5 USD"
- voucher.save(update_fields=["name"])
-
- discount_amount = Decimal("5.00")
- checkout.voucher_code = voucher.code
- checkout.discount_amount = discount_amount
- checkout.discount_name = voucher.name
- checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout_with_prices)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.shipping_address
-
- # then
- shipping_price = str(
- quantize_price(
- checkout.assigned_delivery.price.amount,
- currency,
- )
- )
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [{"amount": str(discount_amount), "name": voucher.name}],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.assigned_delivery.name,
- "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
- "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
- "total_amount": str(
- quantize_price(
- base_calculations.base_checkout_total(checkout_info, lines).amount,
- currency,
- )
- ),
- "shipping_amount": shipping_price,
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_specific_product_voucher(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_prices,
- prices_entered_with_tax,
- voucher_specific_product_type,
-):
- checkout = checkout_with_prices
- currency = checkout.currency
-
- voucher = voucher_specific_product_type
- voucher.name = "Voucher 5 USD"
- voucher.save(update_fields=["name"])
-
- discount_amount = Decimal("5.00")
- checkout.voucher_code = voucher.code
- checkout.discount_amount = discount_amount
- checkout.discount_name = voucher.name
- checkout.save(update_fields=["voucher_code", "discount_amount", "discount_name"])
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout_with_prices)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.shipping_address
-
- # then
- shipping_price = str(
- quantize_price(
- checkout.assigned_delivery.price.amount,
- currency,
- )
- )
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.assigned_delivery.name,
- "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
- "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
- "total_amount": str(
- quantize_price(
- base_calculations.base_checkout_total(checkout_info, lines).amount,
- currency,
- )
- ),
- "shipping_amount": shipping_price,
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_shipping_voucher(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_items_and_shipping,
- prices_entered_with_tax,
- voucher_shipping_type,
- customer_user,
-):
- checkout = checkout_with_items_and_shipping
- checkout.user = customer_user
- currency = checkout.currency
- voucher = voucher_shipping_type
- voucher.countries = []
- voucher.save(update_fields=["countries"])
-
- shipping_price = checkout.assigned_delivery.price.amount
- assert shipping_price == Decimal(10)
-
- voucher_discount_amount = Decimal(3)
- listing = voucher.channel_listings.first()
- listing.discount_value = voucher_discount_amount
- listing.save(update_fields=["discount_value"])
- expected_shipping_price = quantize_price(
- shipping_price - voucher_discount_amount, currency
- )
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- add_voucher_to_checkout(
- manager, checkout_info, lines, voucher, voucher.codes.first()
- )
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.shipping_address
-
- # then
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {},
- "shipping_name": checkout.assigned_delivery.name,
- "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
- "user_public_metadata": {"key": "value"},
- "total_amount": str(
- quantize_price(
- base_calculations.base_checkout_total(checkout_info, lines).amount,
- currency,
- )
- ),
- "shipping_amount": str(expected_shipping_price),
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_order_discount(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_prices,
- prices_entered_with_tax,
- order_promotion_rule,
-):
- checkout = checkout_with_prices
- rule = order_promotion_rule
- currency = checkout.currency
-
- discount_amount = Decimal("5.00")
- CheckoutDiscount.objects.create(
- checkout=checkout,
- promotion_rule=rule,
- type=DiscountType.ORDER_PROMOTION,
- value_type=rule.reward_value_type,
- value=rule.reward_value,
- amount_value=discount_amount,
- currency=checkout.currency,
- )
-
- checkout.discount_amount = discount_amount
- checkout.discount_name = rule.name
- checkout.save(update_fields=["discount_amount", "discount_name"])
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout_with_prices)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.shipping_address
-
- # then
- subtotal_price = Money(0, currency)
- for line_info in lines:
- variant = line_info.variant
- variant_listing = line_info.channel_listing
- unit_price = variant.get_price(variant_listing)
- subtotal_price += unit_price * line_info.line.quantity
- shipping_price = quantize_price(
- checkout.assigned_delivery.price.amount,
- currency,
- )
- total_price_amount = subtotal_price.amount + shipping_price
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [{"amount": str(discount_amount), "name": rule.name}],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.assigned_delivery.name,
- "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
- "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
- "total_amount": str(
- quantize_price(
- total_price_amount,
- currency,
- )
- ),
- "shipping_amount": str(shipping_price),
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_gift_promotion(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_prices,
- prices_entered_with_tax,
- gift_promotion_rule,
-):
- checkout = checkout_with_prices
- currency = checkout.currency
-
- variants = gift_promotion_rule.gifts.all()
- variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
- top_price, variant_id = max(
- variant_listings.values_list("discounted_price_amount", "variant")
- )
- variant_listing = [
- listing for listing in variant_listings if listing.variant_id == variant_id
- ][0]
-
- line = CheckoutLine.objects.create(
- checkout=checkout,
- quantity=1,
- variant_id=variant_id,
- is_gift=True,
- currency="USD",
- undiscounted_unit_price_amount=variant_listing.price_amount,
- )
-
- CheckoutLineDiscount.objects.create(
- line=line,
- promotion_rule=gift_promotion_rule,
- type=DiscountType.ORDER_PROMOTION,
- value_type=RewardValueType.FIXED,
- value=top_price,
- amount_value=top_price,
- currency=checkout.channel.currency_code,
- )
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout_with_prices)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
-
- # then
- subtotal_price = Money(0, currency)
- for line_info in lines:
- if line_info.line.is_gift:
- continue
- variant = line_info.variant
- variant_listing = line_info.channel_listing
- unit_price = variant.get_price(variant_listing)
- subtotal_price += unit_price * line_info.line.quantity
- shipping_price = quantize_price(
- checkout.assigned_delivery.price.amount,
- currency,
- )
- total_price_amount = subtotal_price.amount + shipping_price
- assert payload["discounts"] == []
- assert payload["total_amount"] == str(
- quantize_price(
- total_price_amount,
- currency,
- )
- )
-
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
-def test_generate_checkout_payload_for_tax_calculation_for_checkout_without_shipping(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_without_shipping_required,
- address,
-):
- prices_entered_with_tax = True
- checkout = checkout_without_shipping_required
- checkout.billing_address = address
- checkout.save(update_fields=["billing_address"])
- currency = checkout.currency
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- # when
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.billing_address
-
- # then
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.token),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {},
- "shipping_name": None,
- "shipping_amount": str(quantize_price(Decimal("0.00"), currency)),
- "user_id": None,
- "user_public_metadata": {},
- "total_amount": str(
- quantize_price(
- base_calculations.base_checkout_total(checkout_info, lines).amount,
- currency,
- )
- ),
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
-@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("prices_entered_with_tax", [True, False])
-def test_generate_checkout_payload_for_tax_calculation_no_discount(
- mocked_serialize_checkout_lines_for_tax_calculation,
- mocked_fetch_checkout,
- checkout_with_prices,
- prices_entered_with_tax,
- order_promotion_rule,
-):
- checkout = checkout_with_prices
- rule = order_promotion_rule
- currency = checkout.currency
-
- discount_amount = 0
- checkout.discount_amount = discount_amount
- checkout.discount_name = rule.name
- checkout.save(update_fields=["discount_amount", "discount_name"])
-
- tax_configuration = checkout.channel.tax_configuration
- tax_configuration.prices_entered_with_tax = prices_entered_with_tax
- tax_configuration.save(update_fields=["prices_entered_with_tax"])
- tax_configuration.country_exceptions.all().delete()
-
- mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
- mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
- mocked_serialized_checkout_lines
- )
-
- # when
- lines, _ = fetch_checkout_lines(checkout_with_prices)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)
- payload = json.loads(
- generate_checkout_payload_for_tax_calculation(checkout_info, lines)
- )[0]
- address = checkout.shipping_address
-
- # then
- subtotal_price = Money(0, currency)
- for line_info in lines:
- variant = line_info.variant
- variant_listing = line_info.channel_listing
- unit_price = variant.get_price(variant_listing)
- subtotal_price += unit_price * line_info.line.quantity
- shipping_price = quantize_price(
- checkout.assigned_delivery.price.amount,
- currency,
- )
- total_price_amount = subtotal_price.amount + shipping_price
- assert payload == {
- "type": "Checkout",
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- "address": {
- "type": "Address",
- "id": graphene.Node.to_global_id("Address", address.pk),
- "first_name": address.first_name,
- "last_name": address.last_name,
- "company_name": address.company_name,
- "street_address_1": address.street_address_1,
- "street_address_2": address.street_address_2,
- "city": address.city,
- "city_area": address.city_area,
- "postal_code": address.postal_code,
- "country": address.country.code,
- "country_area": address.country_area,
- "phone": str(address.phone),
- },
- "channel": {
- "type": "Channel",
- "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
- "currency_code": checkout.channel.currency_code,
- "slug": checkout.channel.slug,
- },
- "currency": currency,
- "discounts": [],
- "included_taxes_in_prices": prices_entered_with_tax,
- "lines": mocked_serialized_checkout_lines,
- "metadata": {"meta_key": "meta_value"},
- "shipping_name": checkout.assigned_delivery.name,
- "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
- "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
- "total_amount": str(
- quantize_price(
- total_price_amount,
- currency,
- )
- ),
- "shipping_amount": str(shipping_price),
- }
- mocked_fetch_checkout.assert_not_called()
- mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
- checkout_info,
- lines,
- )
-
-
@freeze_time()
@pytest.mark.parametrize("prices_entered_with_tax", [True, False])
def test_generate_checkout_payload(
diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index be77205aaf..e5246ed9b1 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -1,4 +1,3 @@
-from decimal import Decimal
from unittest.mock import ANY, sentinel
import graphene
@@ -7,23 +6,17 @@ import pytest
from ...attribute import AttributeEntityType, AttributeInputType, AttributeType
from ...attribute.models import Attribute, AttributeValue
from ...attribute.utils import associate_attribute_values_to_instance
-from ...checkout import base_calculations
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
-from ...discount import DiscountType
-from ...discount.models import PromotionRule
from ...discount.utils.checkout import (
create_or_update_discount_objects_from_promotion_for_checkout,
)
from ...plugins.manager import get_plugins_manager
-from ...product.models import Product
-from ...product.utils.variant_prices import update_discounted_prices_for_promotion
-from ...product.utils.variants import fetch_variants_for_promotion_rules
from ..serializers import (
serialize_checkout_lines,
- serialize_checkout_lines_for_tax_calculation,
serialize_product_attributes,
serialize_variant_attributes,
+ serialize_variant_full_name,
)
@@ -224,7 +217,7 @@ def test_serialize_checkout_lines(
"quantity": line_info.line.quantity,
"base_price": str(quantize_price(base_price.amount, currency)),
"currency": channel.currency_code,
- "full_name": variant.display_product(),
+ "full_name": serialize_variant_full_name(variant),
"product_name": product.name,
"variant_name": variant.name,
"attributes": serialize_variant_attributes(variant),
@@ -266,257 +259,10 @@ def test_serialize_checkout_lines_with_promotion(checkout_with_item_on_promotion
"quantity": line_info.line.quantity,
"base_price": str(quantize_price(base_price.amount, currency)),
"currency": channel.currency_code,
- "full_name": variant.display_product(),
+ "full_name": serialize_variant_full_name(variant),
"product_name": product.name,
"variant_name": variant.name,
"attributes": serialize_variant_attributes(variant),
"variant_id": variant.get_global_id(),
}
assert len(checkout_lines_data) == len(list(checkout_lines))
-
-
- ("charge_taxes", "prices_entered_with_tax"),
- [(False, False), (False, True), (True, False), (True, True)],
-)
-def test_serialize_checkout_lines_for_tax_calculation(
- checkout_with_prices, charge_taxes, prices_entered_with_tax
-):
- # We should be sure that we always sends base prices to tax app.
- # We shouldn't use previously calculated prices because they can be
- # changed by tax app due to e.g.
- # Checkout discount
- # Propagating shipping tax to lines.
-
- # given
- checkout = checkout_with_prices
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- tax_configuration = checkout_info.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()
-
- # when
- checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
- checkout_info, lines
- )
-
- # then
- for data, line_info in zip(checkout_lines_data, lines, strict=False):
- line = line_info.line
- variant = line.variant
- product = variant.product
-
- total_price = base_calculations.calculate_base_line_total_price(
- line_info
- ).amount
- unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
-
- assert data == {
- "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
- "sku": variant.sku,
- "quantity": line.quantity,
- "charge_taxes": charge_taxes,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "product_metadata": product.metadata,
- "product_type_metadata": product.product_type.metadata,
- "unit_amount": unit_price,
- "total_amount": total_price,
- }
- assert len(checkout_lines_data) == len(list(lines))
-
-
-def test_serialize_checkout_lines_for_tax_calculation_with_promotion(
- checkout_with_prices, promotion_rule, product_list, product
-):
- # given
- checkout = checkout_with_prices
- product_list.append(product)
- promotion_rule.catalogue_predicate = {
- "productPredicate": {
- "ids": [
- graphene.Node.to_global_id("Product", product.id)
- for product in product_list
- ]
- },
- }
- promotion_rule.save(update_fields=["catalogue_predicate"])
-
- fetch_variants_for_promotion_rules(PromotionRule.objects.all())
- update_discounted_prices_for_promotion(Product.objects.all())
-
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
- create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
-
- tax_configuration = checkout_info.tax_configuration
- tax_configuration.country_exceptions.all().delete()
-
- # when
- checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
- checkout_info, lines
- )
-
- # then
- for data, line_info in zip(checkout_lines_data, lines, strict=False):
- line = line_info.line
- variant = line.variant
- product = variant.product
-
- total_price = base_calculations.calculate_base_line_total_price(
- line_info
- ).amount
- unit_price = base_calculations.calculate_base_line_unit_price(line_info).amount
-
- assert data == {
- "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
- "sku": variant.sku,
- "quantity": line.quantity,
- "charge_taxes": tax_configuration.charge_taxes,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "product_metadata": product.metadata,
- "product_type_metadata": product.product_type.metadata,
- "unit_amount": unit_price,
- "total_amount": total_price,
- }
-
- discount = line_info.discounts[0]
- assert discount.type == DiscountType.PROMOTION
- undiscounted_unit_price = variant.get_base_price(
- line_info.channel_listing,
- line_info.line.price_override,
- ).amount
- assert unit_price < undiscounted_unit_price
-
- assert len(checkout_lines_data) == len(list(lines))
-
-
-def test_serialize_checkout_lines_for_tax_calculation_with_order_discount(
- checkout_with_item_and_order_discount, product
-):
- # given
- checkout = checkout_with_item_and_order_discount
-
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- tax_configuration = checkout_info.tax_configuration
- tax_configuration.country_exceptions.all().delete()
-
- # when
- checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
- checkout_info, lines
- )
-
- # then
- line_info = lines[0]
- line = line_info.line
- variant = line.variant
- product = variant.product
-
- unit_price = variant.get_price(
- channel_listing=line_info.channel_listing,
- )
- total_price_amount = (unit_price * line.quantity).amount
-
- line_data = checkout_lines_data[0]
- # the line data shouldn't include order promotion discount
- assert line_data == {
- "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
- "sku": variant.sku,
- "quantity": line.quantity,
- "charge_taxes": tax_configuration.charge_taxes,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "product_metadata": product.metadata,
- "product_type_metadata": product.product_type.metadata,
- "unit_amount": unit_price.amount,
- "total_amount": total_price_amount,
- }
-
-
-def test_serialize_checkout_lines_for_tax_calculation_with_gift_promotion(
- checkout_with_item_and_gift_promotion, product
-):
- # given
- checkout = checkout_with_item_and_gift_promotion
-
- lines, _ = fetch_checkout_lines(checkout)
- manager = get_plugins_manager(allow_replica=False)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- tax_configuration = checkout_info.tax_configuration
- tax_configuration.country_exceptions.all().delete()
-
- # when
- checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
- checkout_info, lines
- )
-
- # then
- line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]
- line = line_info.line
- line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
- variant = line.variant
- product = variant.product
-
- unit_price = variant.get_price(
- channel_listing=line_info.channel_listing,
- )
- total_price_amount = (unit_price * line.quantity).amount
-
- line_data = [
- line_data for line_data in checkout_lines_data if line_data["id"] == line_id
- ][0]
- assert line_data == {
- "id": line_id,
- "sku": variant.sku,
- "quantity": line.quantity,
- "charge_taxes": tax_configuration.charge_taxes,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "product_metadata": product.metadata,
- "product_type_metadata": product.product_type.metadata,
- "unit_amount": unit_price.amount,
- "total_amount": total_price_amount,
- }
- gift_info = [line_info for line_info in lines if line_info.line.is_gift][0]
- gift_line = gift_info.line
- gift_line_id = graphene.Node.to_global_id("CheckoutLine", gift_info.line.pk)
- gift_line_data = [
- line_data
- for line_data in checkout_lines_data
- if line_data["id"] == gift_line_id
- ][0]
- assert gift_line_data == {
- "id": gift_line_id,
- "sku": gift_line.variant.sku,
- "quantity": 1,
- "charge_taxes": tax_configuration.charge_taxes,
- "full_name": gift_line.variant.display_product(),
- "product_name": gift_line.variant.product.name,
- "variant_name": gift_line.variant.name,
- "variant_id": graphene.Node.to_global_id(
- "ProductVariant", gift_line.variant.pk
- ),
- "product_metadata": gift_line.variant.product.metadata,
- "product_type_metadata": gift_line.variant.product.product_type.metadata,
- "unit_amount": Decimal("0.00"),
- "total_amount": Decimal("0.00"),
- }
diff --git a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
index 778ba08c1d..d8e67cf55f 100644
--- a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
+++ b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py
@@ -38,6 +38,7 @@ def fetch_kwargs(checkout_with_items, plugins_manager):
),
"manager": plugins_manager,
"lines": lines,
+ "requestor": None,
}
@@ -95,7 +96,7 @@ def test_generate_deferred_payload(
):
# given
checkout = checkout_with_item
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs).get()
deferred_request_time = datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC)
event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
@@ -159,7 +160,7 @@ def test_generate_deferred_payload_waits_for_replica_to_sync(
):
# given
checkout = checkout_with_item
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs).get()
deferred_request_time = datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC)
event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
@@ -205,7 +206,7 @@ def test_generate_deferred_payload_triggers_for_existing_deliveries(
):
# given
checkout = checkout_with_item
- fetch_checkout_data(**fetch_kwargs)
+ fetch_checkout_data(**fetch_kwargs).get()
deferred_request_time = datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC)
event_type = WebhookEventAsyncType.CHECKOUT_UPDATED
diff --git a/saleor/webhook/transport/synchronous/__init__.py b/saleor/webhook/transport/synchronous/__init__.py
index 4816f83b9a..6ff7eed1a6 100644
--- a/saleor/webhook/transport/synchronous/__init__.py
+++ b/saleor/webhook/transport/synchronous/__init__.py
@@ -1,11 +1,9 @@
from .transport import (
- trigger_taxes_all_webhooks_sync,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
)
__all__ = [
- "trigger_taxes_all_webhooks_sync",
"trigger_webhook_sync",
"trigger_webhook_sync_if_not_cached",
]
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
index 1e19c55ca5..73ade9758a 100644
--- a/saleor/webhook/transport/synchronous/transport.py
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -1,6 +1,5 @@
import json
import logging
-from collections.abc import Callable
from json import JSONDecodeError
from typing import TYPE_CHECKING, Any, TypeVar, Union
from urllib.parse import urlparse
@@ -15,7 +14,6 @@ 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, TaxDataError
from ....core.tracing import webhooks_otel_trace
from ....core.utils import get_domain
from ....core.utils.events import call_event
@@ -26,7 +24,6 @@ from ....graphql.webhook.subscription_payload import (
initialize_request,
)
from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
-from ....graphql.webhook.utils import get_pregenerated_subscription_payload
from ....payment import PaymentError
from ....payment.interface import TransactionActionData
from ....payment.models import TransactionEvent
@@ -35,7 +32,6 @@ 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,
)
@@ -62,8 +58,6 @@ from ..utils import (
if TYPE_CHECKING:
from ....account.models import User
from ....app.models import App
- from ....graphql.core.context import SaleorContext
- from ....graphql.core.dataloaders import DataLoader
from ....webhook.models import Webhook
R = TypeVar("R")
@@ -558,81 +552,6 @@ if breaker_board := initialize_breaker_board():
)
-def trigger_taxes_all_webhooks_sync(
- event_type: str,
- generate_payload: Callable,
- expected_lines_count: int,
- subscribable_object=None,
- requestor=None,
- pregenerated_subscription_payloads: dict | None = None,
-) -> TaxData | None:
- """Send all synchronous webhook request for given event type.
-
- Requests are send sequentially.
- If the current webhook does not return expected response,
- the next one is send.
- If no webhook responds with expected response,
- this function returns None.
- """
- if pregenerated_subscription_payloads is None:
- pregenerated_subscription_payloads = {}
-
- webhooks = get_webhooks_for_event(event_type)
- request_context = None
- event_payload = None
-
- dataloaders: dict[str, type[DataLoader]] = {}
- request_map: dict[int, SaleorContext] = {}
- is_sync_event = event_type in WebhookEventSyncType.ALL
-
- for webhook in webhooks:
- if webhook.subscription_query:
- request_context = request_map.get(webhook.app_id)
- if not request_context:
- request_context = initialize_request(
- app=webhook.app,
- requestor=requestor,
- sync_event=is_sync_event,
- event_type=event_type,
- dataloaders=dataloaders,
- )
-
- pregenerated_payload = get_pregenerated_subscription_payload(
- webhook, pregenerated_subscription_payloads
- )
-
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=subscribable_object,
- webhook=webhook,
- request=request_context,
- requestor=requestor,
- pregenerated_payload=pregenerated_payload,
- with_save=False,
- )
- if not delivery:
- return None
- else:
- if event_payload is None:
- event_payload = EventPayload(payload=generate_payload())
- delivery = EventDelivery(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
-
- response_data = send_webhook_request_sync(delivery)
- try:
- parsed_response = parse_tax_data(
- event_type, response_data, expected_lines_count
- )
- except TaxDataError:
- continue
- return parsed_response
- return None
-
-
def trigger_transaction_request(
transaction_data: "TransactionActionData", event_type: str, requestor
) -> None: