Skip to content

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

Explicitly pass lines to all utilities

Patryk Zawadzki227e8c5f0d55
diff --git a/pyproject.toml b/pyproject.toml
index 7ed2e71062..b5a152597a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,7 +39,6 @@ google-cloud-storage = "^1.18.0"
google-i18n-address = "^2.3.5"
google-measurement-protocol = "^1.0"
graphene-django = "^2.9.1"
-graphene-django-optimizer = "^0.6"
graphene-federation = "^0.1.0"
html-to-draftjs = "^1.0.1"
markdown = "^3.1.1"
diff --git a/requirements.txt b/requirements.txt
index bfccb0430d..57b6f6c05a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -49,7 +49,6 @@ google-resumable-media==0.5.0
googleapis-common-protos==1.51.0
graphene==2.1.8
graphene-django==2.9.1
-graphene-django-optimizer==0.6.2
graphene-federation==0.1.0
graphql-core==2.3.1
graphql-relay==2.0.1
diff --git a/requirements_dev.txt b/requirements_dev.txt
index c7a35ff968..851975d79d 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -71,7 +71,6 @@ google-resumable-media==0.5.0
googleapis-common-protos==1.51.0
graphene==2.1.8
graphene-django==2.9.1
-graphene-django-optimizer==0.6.2
graphene-federation==0.1.0
graphql-core==2.3.1
graphql-relay==2.0.1
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index f5be4aed71..e39a5faed0 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -16,7 +16,9 @@ if TYPE_CHECKING:
from .models import Checkout, CheckoutLine
-def base_checkout_shipping_price(checkout: "Checkout") -> TaxedMoney:
+def base_checkout_shipping_price(
+ checkout: "Checkout", lines: Iterable["CheckoutLine"]
+) -> TaxedMoney:
"""Return checkout shipping price."""
if not checkout.shipping_method or not checkout.is_shipping_required():
return zero_taxed_money(checkout.currency)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index d661d5db97..4273c20c83 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -9,27 +9,40 @@ if TYPE_CHECKING:
def checkout_shipping_price(
- checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
+ *,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "TaxedMoney":
"""Return checkout shipping price.
It takes in account all plugins.
"""
- return get_plugins_manager().calculate_checkout_shipping(checkout, discounts or [])
+ return get_plugins_manager().calculate_checkout_shipping(
+ checkout, lines, discounts or []
+ )
def checkout_subtotal(
- checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
+ *,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "TaxedMoney":
"""Return the total cost of all the checkout lines, taxes included.
It takes in account all plugins.
"""
- return get_plugins_manager().calculate_checkout_subtotal(checkout, discounts or [])
+ return get_plugins_manager().calculate_checkout_subtotal(
+ checkout, lines, discounts or []
+ )
def checkout_total(
- checkout: "Checkout", discounts: Optional[Iterable[DiscountInfo]] = None
+ *,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> "TaxedMoney":
"""Return the total cost of the checkout.
@@ -38,11 +51,13 @@ def checkout_total(
It takes in account all plugins.
"""
- return get_plugins_manager().calculate_checkout_total(checkout, discounts or [])
+ return get_plugins_manager().calculate_checkout_total(
+ checkout, lines, discounts or []
+ )
def checkout_line_total(
- line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
+ *, line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
) -> "TaxedMoney":
"""Return the total price of provided line, taxes included.
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 0a10eba738..e8e9d1709f 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -31,7 +31,6 @@ from ..discount.utils import (
remove_voucher_usage_by_customer,
validate_voucher_for_checkout,
)
-from ..plugins.manager import get_plugins_manager
from ..giftcard.utils import (
add_gift_card_code_to_checkout,
remove_gift_card_code_from_checkout,
@@ -39,6 +38,7 @@ from ..giftcard.utils import (
from ..order.actions import order_created
from ..order.emails import send_order_confirmation, send_staff_order_confirmation
from ..order.models import Order, OrderLine
+from ..plugins.manager import get_plugins_manager
from ..shipping.models import ShippingMethod
from ..warehouse.availability import check_stock_quantity
from ..warehouse.management import allocate_stock
@@ -208,7 +208,7 @@ def change_shipping_address_in_checkout(checkout, address):
def _get_shipping_voucher_discount_for_checkout(
- voucher, checkout, discounts: Optional[Iterable[DiscountInfo]] = None
+ voucher, checkout, lines, discounts: Optional[Iterable[DiscountInfo]] = None
):
"""Calculate discount value for a voucher of shipping type."""
if not checkout.is_shipping_required():
@@ -225,17 +225,19 @@ def _get_shipping_voucher_discount_for_checkout(
msg = "This offer is not valid in your country."
raise NotApplicable(msg)
- shipping_price = calculations.checkout_shipping_price(checkout, discounts).gross
+ shipping_price = calculations.checkout_shipping_price(
+ checkout=checkout, lines=lines, discounts=discounts
+ ).gross
return voucher.get_discount_amount_for(shipping_price)
def _get_products_voucher_discount(
- checkout, voucher, discounts: Optional[Iterable[DiscountInfo]] = None
+ lines, voucher, discounts: Optional[Iterable[DiscountInfo]] = None
):
"""Calculate products discount value for a voucher, depending on its type."""
prices = None
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- prices = get_prices_of_discounted_specific_product(checkout, voucher, discounts)
+ prices = get_prices_of_discounted_specific_product(lines, voucher, discounts)
if not prices:
msg = "This offer is only valid for selected items."
raise NotApplicable(msg)
@@ -276,7 +278,9 @@ def get_prices_of_discounted_specific_product(
discounted_lines.extend(list(lines))
for line in discounted_lines:
- line_total = calculations.checkout_line_total(line, discounts or []).gross
+ line_total = calculations.checkout_line_total(
+ line=line, discounts=discounts or []
+ ).gross
line_unit_price = quantize_price(
(line_total / line.quantity), line_total.currency
)
@@ -288,20 +292,25 @@ def get_prices_of_discounted_specific_product(
def get_voucher_discount_for_checkout(
voucher: Voucher,
checkout: Checkout,
+ lines: Iterable[CheckoutLine],
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> Money:
"""Calculate discount value depending on voucher and discount types.
Raise NotApplicable if voucher of given type cannot be applied.
"""
- validate_voucher_for_checkout(voucher, checkout, discounts)
+ validate_voucher_for_checkout(voucher, checkout, lines, discounts)
if voucher.type == VoucherType.ENTIRE_ORDER:
- subtotal = calculations.checkout_subtotal(checkout, discounts).gross
+ subtotal = calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=discounts
+ ).gross
return voucher.get_discount_amount_for(subtotal)
if voucher.type == VoucherType.SHIPPING:
- return _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts)
+ return _get_shipping_voucher_discount_for_checkout(
+ voucher, checkout, lines, discounts
+ )
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- return _get_products_voucher_discount(checkout, voucher, discounts)
+ return _get_products_voucher_discount(lines, voucher, discounts)
raise NotImplementedError("Unknown discount type")
@@ -323,7 +332,7 @@ def get_voucher_for_checkout(
def recalculate_checkout_discount(
- checkout: Checkout, discounts: Iterable[DiscountInfo]
+ checkout: Checkout, lines: Iterable[CheckoutLine], discounts: Iterable[DiscountInfo]
):
"""Recalculate `checkout.discount` based on the voucher.
@@ -333,11 +342,15 @@ def recalculate_checkout_discount(
voucher = get_voucher_for_checkout(checkout)
if voucher is not None:
try:
- discount = get_voucher_discount_for_checkout(voucher, checkout, discounts)
+ discount = get_voucher_discount_for_checkout(
+ voucher, checkout, lines, discounts
+ )
except NotApplicable:
remove_voucher_from_checkout(checkout)
else:
- subtotal = calculations.checkout_subtotal(checkout, discounts).gross
+ subtotal = calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=discounts
+ ).gross
checkout.discount = (
min(discount, subtotal)
if voucher.type != VoucherType.SHIPPING
@@ -363,6 +376,7 @@ def recalculate_checkout_discount(
def add_promo_code_to_checkout(
checkout: Checkout,
+ lines: Iterable[CheckoutLine],
promo_code: str,
discounts: Optional[Iterable[DiscountInfo]] = None,
):
@@ -371,7 +385,7 @@ def add_promo_code_to_checkout(
Raise InvalidPromoCode if promo code does not match to any voucher or gift card.
"""
if promo_code_is_voucher(promo_code):
- add_voucher_code_to_checkout(checkout, promo_code, discounts)
+ add_voucher_code_to_checkout(checkout, lines, promo_code, discounts)
elif promo_code_is_gift_card(promo_code):
add_gift_card_code_to_checkout(checkout, promo_code)
else:
@@ -380,6 +394,7 @@ def add_promo_code_to_checkout(
def add_voucher_code_to_checkout(
checkout: Checkout,
+ lines: Iterable[CheckoutLine],
voucher_code: str,
discounts: Optional[Iterable[DiscountInfo]] = None,
):
@@ -392,7 +407,7 @@ def add_voucher_code_to_checkout(
except Voucher.DoesNotExist:
raise InvalidPromoCode()
try:
- add_voucher_to_checkout(checkout, voucher, discounts)
+ add_voucher_to_checkout(checkout, lines, voucher, discounts)
except NotApplicable:
raise ValidationError(
{
@@ -406,6 +421,7 @@ def add_voucher_code_to_checkout(
def add_voucher_to_checkout(
checkout: Checkout,
+ lines: Iterable[CheckoutLine],
voucher: Voucher,
discounts: Optional[Iterable[DiscountInfo]] = None,
):
@@ -413,7 +429,7 @@ def add_voucher_to_checkout(
Raise NotApplicable if voucher of given type cannot be applied.
"""
- discount = get_voucher_discount_for_checkout(voucher, checkout, discounts)
+ discount = get_voucher_discount_for_checkout(voucher, checkout, lines, discounts)
checkout.voucher_code = voucher.code
checkout.discount_name = voucher.name
checkout.translated_discount_name = (
@@ -464,23 +480,26 @@ def remove_voucher_from_checkout(checkout: Checkout):
def get_valid_shipping_methods_for_checkout(
checkout: Checkout,
+ lines: Iterable[CheckoutLine],
discounts: Iterable[DiscountInfo],
country_code: Optional[str] = None,
):
manager = get_plugins_manager()
return ShippingMethod.objects.applicable_shipping_methods_for_instance(
checkout,
- price=manager.calculate_checkout_subtotal(checkout, discounts).gross,
+ price=manager.calculate_checkout_subtotal(checkout, lines, discounts).gross,
country_code=country_code,
)
-def is_valid_shipping_method(checkout: Checkout, discounts: Iterable[DiscountInfo]):
+def is_valid_shipping_method(
+ checkout: Checkout, lines: Iterable[CheckoutLine], discounts: Iterable[DiscountInfo]
+):
"""Check if shipping method is valid and remove (if not)."""
if not checkout.shipping_method:
return False
- valid_methods = get_valid_shipping_methods_for_checkout(checkout, discounts)
+ valid_methods = get_valid_shipping_methods_for_checkout(checkout, lines, discounts)
if valid_methods is None or checkout.shipping_method not in valid_methods:
clear_shipping_method(checkout)
return False
@@ -488,12 +507,15 @@ def is_valid_shipping_method(checkout: Checkout, discounts: Iterable[DiscountInf
def get_shipping_price_estimate(
- checkout: Checkout, discounts: Iterable[DiscountInfo], country_code: str
+ checkout: Checkout,
+ lines: Iterable[CheckoutLine],
+ discounts: Iterable[DiscountInfo],
+ country_code: str,
) -> Optional[TaxedMoneyRange]:
"""Return the estimated price range for shipping for given order."""
shipping_methods = get_valid_shipping_methods_for_checkout(
- checkout, discounts, country_code=country_code
+ checkout, lines, discounts, country_code=country_code
)
if shipping_methods is None:
@@ -653,7 +675,9 @@ def create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLine
return line
-def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) -> dict:
+def prepare_order_data(
+ *, checkout: Checkout, lines: Iterable[CheckoutLine], tracking_code: str, discounts
+) -> dict:
"""Run checks and return all the data from a given checkout to create an order.
:raises NotApplicable InsufficientStock:
@@ -661,14 +685,16 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) ->
order_data = {}
manager = get_plugins_manager()
- taxed_total = calculations.checkout_total(checkout=checkout, discounts=discounts)
+ taxed_total = calculations.checkout_total(
+ checkout=checkout, lines=lines, discounts=discounts
+ )
cards_total = checkout.get_total_gift_cards_balance()
taxed_total.gross -= cards_total
taxed_total.net -= cards_total
taxed_total = max(taxed_total, zero_taxed_money(checkout.currency))
- shipping_total = manager.calculate_checkout_shipping(checkout, discounts)
+ shipping_total = manager.calculate_checkout_shipping(checkout, lines, discounts)
order_data.update(_process_shipping_data_for_order(checkout, shipping_total))
order_data.update(_process_user_data_for_order(checkout))
order_data.update(
@@ -693,7 +719,7 @@ def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) ->
# assign gift cards to the order
order_data["total_price_left"] = (
- manager.calculate_checkout_subtotal(checkout, discounts)
+ manager.calculate_checkout_subtotal(checkout, list(checkout), discounts)
+ shipping_total
- checkout.discount
).gross
@@ -768,7 +794,9 @@ def create_order(
return order
-def is_fully_paid(checkout: Checkout, discounts: Iterable[DiscountInfo]):
+def is_fully_paid(
+ checkout: Checkout, lines: Iterable[CheckoutLine], discounts: Iterable[DiscountInfo]
+):
"""Check if provided payment methods cover the checkout's total amount.
Note that these payments may not be captured or charged at all.
@@ -776,7 +804,7 @@ def is_fully_paid(checkout: Checkout, discounts: Iterable[DiscountInfo]):
payments = [payment for payment in checkout.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
checkout_total = (
- calculations.checkout_total(checkout=checkout, discounts=discounts)
+ calculations.checkout_total(checkout=checkout, lines=lines, discounts=discounts)
- checkout.get_total_gift_cards_balance()
)
checkout_total = max(
@@ -785,7 +813,9 @@ def is_fully_paid(checkout: Checkout, discounts: Iterable[DiscountInfo]):
return total_paid >= checkout_total.amount
-def clean_checkout(checkout: Checkout, discounts: Iterable[DiscountInfo]):
+def clean_checkout(
+ checkout: Checkout, lines: Iterable[CheckoutLine], discounts: Iterable[DiscountInfo]
+):
"""Check if checkout can be completed."""
if checkout.is_shipping_required():
if not checkout.shipping_method:
@@ -798,7 +828,7 @@ def clean_checkout(checkout: Checkout, discounts: Iterable[DiscountInfo]):
"Shipping address is not set",
code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,
)
- if not is_valid_shipping_method(checkout, discounts):
+ if not is_valid_shipping_method(checkout, lines, discounts):
raise ValidationError(
"Shipping method is not valid for your shipping address",
code=CheckoutErrorCode.INVALID_SHIPPING_METHOD.value,
@@ -810,7 +840,7 @@ def clean_checkout(checkout: Checkout, discounts: Iterable[DiscountInfo]):
code=CheckoutErrorCode.BILLING_ADDRESS_NOT_SET.value,
)
- if not is_fully_paid(checkout, discounts):
+ if not is_fully_paid(checkout, lines, discounts):
raise ValidationError(
"Provided payment methods can not cover the checkout's total amount",
code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.value,
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index dae513a5cf..56f021aaa1 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -15,7 +15,7 @@ if TYPE_CHECKING:
# flake8: noqa
from .models import Voucher
from ..product.models import Collection, Product
- from ..checkout.models import Checkout
+ from ..checkout.models import Checkout, CheckoutLine
from ..order.models import Order
@@ -99,9 +99,12 @@ def calculate_discounted_price(
def validate_voucher_for_checkout(
voucher: "Voucher",
checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
discounts: Optional[Iterable[DiscountInfo]],
):
- subtotal = calculations.checkout_subtotal(checkout, discounts)
+ subtotal = calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=discounts
+ )
customer_email = checkout.get_customer_email()
validate_voucher(voucher, subtotal.gross, checkout.quantity, customer_email)
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
new file mode 100644
index 0000000000..3f76740927
--- /dev/null
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -0,0 +1,15 @@
+from collections import defaultdict
+
+from ...checkout.models import CheckoutLine
+from ..core.dataloaders import DataLoader
+
+
+class CheckoutLinesByCheckoutTokenLoader(DataLoader):
+ context_key = "checkoutlines_by_checkout"
+
+ def batch_load(self, keys):
+ lines = CheckoutLine.objects.filter(checkout_id__in=keys)
+ line_map = defaultdict(list)
+ for variant in lines.iterator():
+ line_map[variant.checkout_id].append(variant)
+ return [line_map.get(checkout_id, []) for checkout_id in keys]
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 997901a29d..ae4981f2d3 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -50,7 +50,10 @@ ERROR_DOES_NOT_SHIP = "This checkout doesn't need shipping"
def clean_shipping_method(
- checkout: models.Checkout, method: Optional[models.ShippingMethod], discounts
+ checkout: models.Checkout,
+ lines: List[models.CheckoutLine],
+ method: Optional[models.ShippingMethod],
+ discounts,
) -> bool:
"""Check if current shipping method is valid."""
@@ -70,23 +73,28 @@ def clean_shipping_method(
code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET.value,
)
- valid_methods = get_valid_shipping_methods_for_checkout(checkout, discounts)
+ valid_methods = get_valid_shipping_methods_for_checkout(checkout, lines, discounts)
return method in valid_methods
-def update_checkout_shipping_method_if_invalid(checkout: models.Checkout, discounts):
+def update_checkout_shipping_method_if_invalid(
+ checkout: models.Checkout, lines: List[models.CheckoutLine], discounts
+):
# remove shipping method when empty checkout
if checkout.quantity == 0 or not checkout.is_shipping_required():
checkout.shipping_method = None
checkout.save(update_fields=["shipping_method", "last_change"])
is_valid = clean_shipping_method(
- checkout=checkout, method=checkout.shipping_method, discounts=discounts
+ checkout=checkout,
+ lines=lines,
+ method=checkout.shipping_method,
+ discounts=discounts,
)
if not is_valid:
cheapest_alternative = get_valid_shipping_methods_for_checkout(
- checkout, discounts
+ checkout, lines, discounts
).first()
checkout.shipping_method = cheapest_alternative
checkout.save(update_fields=["shipping_method", "last_change"])
@@ -347,8 +355,12 @@ class CheckoutLinesAdd(BaseMutation):
f"Insufficient product stock: {exc.item}", code=exc.code
)
- update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)
- recalculate_checkout_discount(checkout, info.context.discounts)
+ lines = list(checkout)
+
+ update_checkout_shipping_method_if_invalid(
+ checkout, lines, info.context.discounts
+ )
+ recalculate_checkout_discount(checkout, lines, info.context.discounts)
return CheckoutLinesAdd(checkout=checkout)
@@ -390,8 +402,12 @@ class CheckoutLineDelete(BaseMutation):
if line and line in checkout.lines.all():
line.delete()
- update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)
- recalculate_checkout_discount(checkout, info.context.discounts)
+ lines = list(checkout)
+
+ update_checkout_shipping_method_if_invalid(
+ checkout, lines, info.context.discounts
+ )
+ recalculate_checkout_discount(checkout, lines, info.context.discounts)
return CheckoutLineDelete(checkout=checkout)
@@ -515,12 +531,16 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
shipping_address, instance=checkout.shipping_address, info=info
)
- update_checkout_shipping_method_if_invalid(checkout, info.context.discounts)
+ lines = list(checkout)
+
+ update_checkout_shipping_method_if_invalid(
+ checkout, lines, info.context.discounts
+ )
with transaction.atomic():
shipping_address.save()
change_shipping_address_in_checkout(checkout, shipping_address)
- recalculate_checkout_discount(checkout, info.context.discounts)
+ recalculate_checkout_discount(checkout, lines, info.context.discounts)
return CheckoutShippingAddressUpdate(checkout=checkout)
@@ -628,8 +648,12 @@ class CheckoutShippingMethodUpdate(BaseMutation):
field="shipping_method_id",
)
+ lines = list(checkout)
shipping_method_is_valid = clean_shipping_method(
- checkout=checkout, method=shipping_method, discounts=info.context.discounts
+ checkout=checkout,
+ lines=lines,
+ method=shipping_method,
+ discounts=info.context.discounts,
)
if not shipping_method_is_valid:
@@ -644,7 +668,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
checkout.shipping_method = shipping_method
checkout.save(update_fields=["shipping_method", "last_change"])
- recalculate_checkout_discount(checkout, info.context.discounts)
+ recalculate_checkout_discount(checkout, lines, info.context.discounts)
return CheckoutShippingMethodUpdate(checkout=checkout)
@@ -706,10 +730,11 @@ class CheckoutComplete(BaseMutation):
),
).select_related("shipping_method", "shipping_method__shipping_zone"),
)
+ lines = list(checkout)
discounts = info.context.discounts
user = info.context.user
- clean_checkout(checkout, discounts)
+ clean_checkout(checkout, list(checkout), discounts)
payment = checkout.get_last_active_payment()
@@ -717,6 +742,7 @@ class CheckoutComplete(BaseMutation):
try:
order_data = prepare_order_data(
checkout=checkout,
+ lines=lines,
tracking_code=analytics.get_client_id(info.context),
discounts=discounts,
)
@@ -811,7 +837,8 @@ class CheckoutAddPromoCode(BaseMutation):
checkout = cls.get_node_or_error(
info, checkout_id, only_type=Checkout, field="checkout_id"
)
- add_promo_code_to_checkout(checkout, promo_code, info.context.discounts)
+ lines = list(checkout)
+ add_promo_code_to_checkout(checkout, lines, promo_code, info.context.discounts)
return CheckoutAddPromoCode(checkout=checkout)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 5638ac8acd..153a52df58 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -1,5 +1,6 @@
import graphene
from graphql_jwt.exceptions import PermissionDenied
+from promise import Promise
from ...checkout import calculations, models
from ...checkout.utils import get_valid_shipping_methods_for_checkout
@@ -9,10 +10,12 @@ from ...plugins.manager import get_plugins_manager
from ..core.connection import CountableDjangoObjectType
from ..core.types.money import TaxedMoney
from ..decorators import permission_required
+from ..discount.dataloaders import DiscountsByDateTimeLoader
from ..giftcard.types import GiftCard
from ..meta.deprecated.resolvers import resolve_meta, resolve_private_meta
from ..meta.types import ObjectWithMetadata
from ..shipping.types import ShippingMethod
+from .dataloaders import CheckoutLinesByCheckoutTokenLoader
class GatewayConfigLine(graphene.ObjectType):
@@ -56,8 +59,15 @@ class CheckoutLine(CountableDjangoObjectType):
@staticmethod
def resolve_total_price(self, info):
- return info.context.plugins.calculate_checkout_line_total(
- checkout_line=self, discounts=info.context.discounts
+ def calculate_total_price(discounts):
+ return info.context.plugins.calculate_checkout_line_total(
+ checkout_line=self, discounts=discounts
+ )
+
+ return (
+ DiscountsByDateTimeLoader(info.context)
+ .load(info.context.request_time)
+ .then(calculate_total_price)
)
@staticmethod
@@ -140,49 +150,87 @@ class Checkout(CountableDjangoObjectType):
@staticmethod
def resolve_total_price(root: models.Checkout, info):
- taxed_total = (
- calculations.checkout_total(checkout=root, discounts=info.context.discounts)
- - root.get_total_gift_cards_balance()
+ def calculate_total_price(data):
+ lines, discounts = data
+ taxed_total = (
+ calculations.checkout_total(
+ checkout=root, lines=lines, discounts=discounts
+ )
+ - root.get_total_gift_cards_balance()
+ )
+ return max(taxed_total, zero_taxed_money())
+
+ lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
)
- return max(taxed_total, zero_taxed_money())
+
+ return Promise.all([lines, discounts]).then(calculate_total_price)
@staticmethod
def resolve_subtotal_price(root: models.Checkout, info):
- return calculations.checkout_subtotal(
- checkout=root, discounts=info.context.discounts
+ def calculate_subtotal_price(data):
+ lines, discounts = data
+ return calculations.checkout_subtotal(
+ checkout=root, lines=lines, discounts=discounts
+ )
+
+ lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
)
+ return Promise.all([lines, discounts]).then(calculate_subtotal_price)
+
@staticmethod
def resolve_shipping_price(root: models.Checkout, info):
- return calculations.checkout_shipping_price(
- checkout=root, discounts=info.context.discounts
+ def calculate_shipping_price(data):
+ lines, discounts = data
+ return calculations.checkout_shipping_price(
+ checkout=root, lines=lines, discounts=discounts
+ )
+
+ lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
)
+ return Promise.all([lines, discounts]).then(calculate_shipping_price)
+
@staticmethod
def resolve_lines(root: models.Checkout, *_args):
return root.lines.prefetch_related("variant")
@staticmethod
def resolve_available_shipping_methods(root: models.Checkout, info):
- available = get_valid_shipping_methods_for_checkout(
- root, info.context.discounts
+ def calculate_available_shipping_methods(data):
+ lines, discounts = data
+ available = get_valid_shipping_methods_for_checkout(root, lines, discounts)
+ if available is None:
+ return []
+
+ manager = get_plugins_manager()
+ display_gross = display_gross_prices()
+ for shipping_method in available:
+ # ignore mypy checking because it is checked in
+ # get_valid_shipping_methods_for_checkout
+ taxed_price = manager.apply_taxes_to_shipping(
+ shipping_method.price, root.shipping_address # type: ignore
+ )
+ if display_gross:
+ shipping_method.price = taxed_price.gross
+ else:
+ shipping_method.price = taxed_price.net
+ return available
+
+ lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
+ )
+
+ return Promise.all([lines, discounts]).then(
+ calculate_available_shipping_methods
)
- if available is None:
- return []
-
- manager = get_plugins_manager()
- display_gross = display_gross_prices()
- for shipping_method in available:
- # ignore mypy checking because it is checked in
- # get_valid_shipping_methods_for_checkout
- taxed_price = manager.apply_taxes_to_shipping(
- shipping_method.price, root.shipping_address # type: ignore
- )
- if display_gross:
- shipping_method.price = taxed_price.gross
- else:
- shipping_method.price = taxed_price.net
- return available
@staticmethod
def resolve_available_payment_gateways(_: models.Checkout, _info):
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index e2fc7dc67a..0e5d522b32 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -69,7 +69,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
def calculate_total(cls, info, checkout):
checkout_total = (
info.context.plugins.calculate_checkout_total(
- checkout, discounts=info.context.discounts
+ checkout, lines=list(checkout), discounts=info.context.discounts
)
- checkout.get_total_gift_cards_balance()
)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 7e94e35632..34e19afccc 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -38,7 +38,6 @@ def resolve_digital_contents(info):
def resolve_products(info, stock_availability=None, **_kwargs):
-
user = get_user_or_app_from_context(info.context)
qs = models.Product.objects.visible_to_user(user)
@@ -65,9 +64,7 @@ def resolve_product_variants(info, ids=None):
def resolve_report_product_sales(period):
- qs = models.ProductVariant.objects.prefetch_related(
- "product", "product__images", "order_lines__order"
- ).all()
+ qs = models.ProductVariant.objects.all()
# exclude draft and canceled orders
exclude_status = [OrderStatus.DRAFT, OrderStatus.CANCELED]
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 0e07ccaf87..402830ff12 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -113,6 +113,7 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_total(
self,
checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
@@ -155,6 +156,7 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_subtotal(
self,
checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
@@ -190,6 +192,7 @@ class AvataxPlugin(BasePlugin):
def calculate_checkout_shipping(
self,
checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
discounts: Iterable[DiscountInfo],
previous_value: TaxedMoney,
) -> TaxedMoney:
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index f186e6f7c7..fc575d1ffc 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -67,6 +67,7 @@ class BasePlugin:
def calculate_checkout_total(
self,
checkout: "Checkout",
+ lines: List["CheckoutLine"],
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
@@ -80,6 +81,7 @@ class BasePlugin:
def calculate_checkout_subtotal(
self,
checkout: "Checkout",
+ lines: List["CheckoutLine"],
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
@@ -93,6 +95,7 @@ class BasePlugin:
def calculate_checkout_shipping(
self,
checkout: "Checkout",
+ lines: List["CheckoutLine"],
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index e8f4edbd82..65b3ee1e74 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1,5 +1,5 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, List, Iterable, Optional, Union
+from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Union
import opentracing
from django.conf import settings
@@ -97,38 +97,47 @@ class PluginsManager(PaymentInterface):
self.__run_method_on_plugins("checkout_quantity_changed", None, checkout)
def calculate_checkout_total(
- self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
default_value = base_calculations.base_checkout_total(
- subtotal=self.calculate_checkout_subtotal(checkout, discounts),
- shipping_price=self.calculate_checkout_shipping(checkout, discounts),
+ subtotal=self.calculate_checkout_subtotal(checkout, lines, discounts),
+ shipping_price=self.calculate_checkout_shipping(checkout, lines, discounts),
discount=checkout.discount,
currency=checkout.currency,
)
return self.__run_method_on_plugins(
- "calculate_checkout_total", default_value, checkout, discounts
+ "calculate_checkout_total", default_value, checkout, lines, discounts
)
def calculate_checkout_subtotal(
- self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
line_totals = [
- self.calculate_checkout_line_total(line, discounts) for line in checkout
+ self.calculate_checkout_line_total(line, discounts) for line in lines
]
default_value = base_calculations.base_checkout_subtotal(
line_totals, checkout.currency
)
return self.__run_method_on_plugins(
- "calculate_checkout_subtotal", default_value, checkout, discounts
+ "calculate_checkout_subtotal", default_value, checkout, lines, discounts
)
def calculate_checkout_shipping(
- self, checkout: "Checkout", discounts: Iterable[DiscountInfo]
+ self,
+ checkout: "Checkout",
+ lines: Iterable["CheckoutLine"],
+ discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
- default_value = base_calculations.base_checkout_shipping_price(checkout)
+ default_value = base_calculations.base_checkout_shipping_price(checkout, lines)
return self.__run_method_on_plugins(
- "calculate_checkout_shipping", default_value, checkout, discounts
+ "calculate_checkout_shipping", default_value, checkout, lines, discounts
)
def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index df48ab1c3a..ae99b1945b 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -60,6 +60,7 @@ class VatlayerPlugin(BasePlugin):
def calculate_checkout_total(
self,
checkout: "Checkout",
+ lines: List["CheckoutLine"],
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
@@ -67,8 +68,12 @@ class VatlayerPlugin(BasePlugin):
return previous_value
return (
- calculations.checkout_subtotal(checkout, discounts)
- + calculations.checkout_shipping_price(checkout, discounts)
+ calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=discounts
+ )
+ + calculations.checkout_shipping_price(
+ checkout=checkout, lines=lines, discounts=discounts
+ )
- checkout.discount
)
@@ -90,6 +95,7 @@ class VatlayerPlugin(BasePlugin):
def calculate_checkout_shipping(
self,
checkout: "Checkout",
+ lines: List["CheckoutLine"],
discounts: List["DiscountInfo"],
previous_value: TaxedMoney,
) -> TaxedMoney:
diff --git a/tests/api/benchmark/conftest.py b/tests/api/benchmark/conftest.py
index 5135de38ce..414a67ac64 100644
--- a/tests/api/benchmark/conftest.py
+++ b/tests/api/benchmark/conftest.py
@@ -140,7 +140,7 @@ def checkout_with_billing_address(checkout_with_shipping_method, address):
def checkout_with_charged_payment(checkout_with_billing_address):
checkout = checkout_with_billing_address
- taxed_total = calculations.checkout_total(checkout)
+ taxed_total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = Payment.objects.create(
gateway="Dummy", is_active=True, total=taxed_total.gross.amount, currency="USD"
)
diff --git a/tests/api/benchmark/test_checkout_mutations.py b/tests/api/benchmark/test_checkout_mutations.py
index f7caad9cdc..02c9690f64 100644
--- a/tests/api/benchmark/test_checkout_mutations.py
+++ b/tests/api/benchmark/test_checkout_mutations.py
@@ -485,7 +485,8 @@ def test_checkout_payment_charge(
"checkoutId": Node.to_global_id("Checkout", checkout_with_billing_address.pk),
"input": {
"amount": calculations.checkout_total(
- checkout=checkout_with_billing_address
+ checkout=checkout_with_billing_address,
+ lines=list(checkout_with_billing_address),
).gross.amount,
"gateway": "Dummy",
"token": "charged",
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index b0ed4b1cc6..4859df06f8 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -59,7 +59,9 @@ def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(
checkout = checkout_with_single_item
checkout.shipping_address = address
- is_valid_method = clean_shipping_method(checkout, shipping_method, [])
+ is_valid_method = clean_shipping_method(
+ checkout, list(checkout), shipping_method, []
+ )
assert is_valid_method is True
@@ -71,7 +73,7 @@ def test_clean_shipping_method_does_nothing_if_no_shipping_method(
checkout = checkout_with_single_item
checkout.shipping_address = address
- is_valid_method = clean_shipping_method(checkout, None, [])
+ is_valid_method = clean_shipping_method(checkout, list(checkout), None, [])
assert is_valid_method is True
@@ -91,7 +93,7 @@ def test_update_checkout_shipping_method_if_invalid(
shipping_method.shipping_zone = shipping_zone_without_countries
shipping_method.save(update_fields=["shipping_zone"])
- update_checkout_shipping_method_if_invalid(checkout, None)
+ update_checkout_shipping_method_if_invalid(checkout, list(checkout), None)
assert checkout.shipping_method == other_shipping_method
@@ -642,7 +644,9 @@ def test_checkout_lines_add(
assert line.variant == variant
assert line.quantity == 1
- mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)
+ mocked_update_shipping_method.assert_called_once_with(
+ checkout, list(checkout), mock.ANY
+ )
def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock):
@@ -774,7 +778,9 @@ def test_checkout_lines_update(
assert line.variant == variant
assert line.quantity == 1
- mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)
+ mocked_update_shipping_method.assert_called_once_with(
+ checkout, list(checkout), mock.ANY
+ )
def test_checkout_lines_update_invalid_checkout_id(user_api_client):
@@ -877,7 +883,9 @@ def test_checkout_line_delete(
assert not data["errors"]
checkout.refresh_from_db()
assert checkout.lines.count() == 0
- mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)
+ mocked_update_shipping_method.assert_called_once_with(
+ checkout, list(checkout), mock.ANY
+ )
@mock.patch(
@@ -907,7 +915,9 @@ def test_checkout_line_delete_by_zero_quantity(
assert not data["errors"]
checkout.refresh_from_db()
assert checkout.lines.count() == 0
- mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)
+ mocked_update_shipping_method.assert_called_once_with(
+ checkout, list(checkout), mock.ANY
+ )
def test_checkout_customer_attach(
@@ -1054,7 +1064,9 @@ def test_checkout_shipping_address_update(
assert checkout.shipping_address.postal_code == shipping_address["postalCode"]
assert checkout.shipping_address.country == shipping_address["country"]
assert checkout.shipping_address.city == shipping_address["city"].upper()
- mocked_update_shipping_method.assert_called_once_with(checkout, mock.ANY)
+ mocked_update_shipping_method.assert_called_once_with(
+ checkout, list(checkout), mock.ANY
+ )
def test_checkout_shipping_address_with_invalid_phone_number_returns_error(
@@ -1269,7 +1281,7 @@ def test_checkout_complete(
checkout_line_variant = checkout_line.variant
gift_current_balance = checkout.get_total_gift_cards_balance()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1338,7 +1350,7 @@ def test_checkout_with_voucher_complete(
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1442,7 +1454,7 @@ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
checkout.billing_address = address
checkout.save()
- taxed_total = calculations.checkout_total(checkout)
+ taxed_total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1542,7 +1554,7 @@ def test_checkout_complete_confirmation_needed(
checkout.billing_address = address
checkout.save()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1585,7 +1597,7 @@ def test_checkout_confirm(
checkout.billing_address = address
checkout.save()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_txn_to_confirm
payment.is_active = True
payment.order = None
@@ -1624,7 +1636,7 @@ def test_checkout_complete_insufficient_stock(
checkout.shipping_method = shipping_method
checkout.billing_address = address
checkout.save()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1664,7 +1676,7 @@ def test_checkout_complete_without_redirect_url(
checkout_line_variant = checkout_line.variant
gift_current_balance = checkout.get_total_gift_cards_balance()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -1983,9 +1995,13 @@ def test_checkout_prices(user_api_client, checkout_with_item):
data = content["data"]["checkout"]
assert data["token"] == str(checkout_with_item.token)
assert len(data["lines"]) == checkout_with_item.lines.count()
- total = calculations.checkout_total(checkout_with_item)
+ total = calculations.checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
- subtotal = calculations.checkout_subtotal(checkout_with_item)
+ subtotal = calculations.checkout_subtotal(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
@@ -2030,7 +2046,7 @@ def test_checkout_shipping_method_update(
checkout.refresh_from_db()
mock_clean_shipping.assert_called_once_with(
- checkout=checkout, method=shipping_method, discounts=ANY
+ checkout=checkout, lines=list(checkout), method=shipping_method, discounts=ANY
)
if is_valid_shipping_method:
@@ -2121,7 +2137,7 @@ def test_clean_checkout(checkout_with_item, payment_dummy, address, shipping_met
checkout.shipping_method = shipping_method
checkout.billing_address = address
checkout.save()
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -2130,7 +2146,7 @@ def test_clean_checkout(checkout_with_item, payment_dummy, address, shipping_met
payment.checkout = checkout
payment.save()
# Shouldn't raise any errors
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
def test_clean_checkout_no_shipping_method(checkout_with_item, address):
@@ -2139,7 +2155,7 @@ def test_clean_checkout_no_shipping_method(checkout_with_item, address):
checkout.save()
with pytest.raises(ValidationError) as e:
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
msg = "Shipping method is not set"
assert e.value.error_list[0].message == msg
@@ -2151,7 +2167,7 @@ def test_clean_checkout_no_shipping_address(checkout_with_item, shipping_method)
checkout.save()
with pytest.raises(ValidationError) as e:
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
msg = "Shipping address is not set"
assert e.value.error_list[0].message == msg
@@ -2166,7 +2182,7 @@ def test_clean_checkout_invalid_shipping_method(
checkout.save()
with pytest.raises(ValidationError) as e:
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
msg = "Shipping method is not valid for your shipping address"
assert e.value.error_list[0].message == msg
@@ -2181,7 +2197,7 @@ def test_clean_checkout_no_billing_address(
checkout.save()
with pytest.raises(ValidationError) as e:
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
msg = "Billing address is not set"
assert e.value.error_list[0].message == msg
@@ -2194,7 +2210,7 @@ def test_clean_checkout_no_payment(checkout_with_item, shipping_method, address)
checkout.save()
with pytest.raises(ValidationError) as e:
- clean_checkout(checkout, None)
+ clean_checkout(checkout, list(checkout), None)
msg = "Provided payment methods can not cover the checkout's total amount"
assert e.value.error_list[0].message == msg
@@ -2202,7 +2218,7 @@ def test_clean_checkout_no_payment(checkout_with_item, shipping_method, address)
def test_is_fully_paid(checkout_with_item, payment_dummy):
checkout = checkout_with_item
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -2210,13 +2226,13 @@ def test_is_fully_paid(checkout_with_item, payment_dummy):
payment.currency = total.gross.currency
payment.checkout = checkout
payment.save()
- is_paid = is_fully_paid(checkout, None)
+ is_paid = is_fully_paid(checkout, list(checkout), None)
assert is_paid
def test_is_fully_paid_many_payments(checkout_with_item, payment_dummy):
checkout = checkout_with_item
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -2232,13 +2248,13 @@ def test_is_fully_paid_many_payments(checkout_with_item, payment_dummy):
payment2.currency = total.gross.currency
payment2.checkout = checkout
payment2.save()
- is_paid = is_fully_paid(checkout, None)
+ is_paid = is_fully_paid(checkout, list(checkout), None)
assert is_paid
def test_is_fully_paid_partially_paid(checkout_with_item, payment_dummy):
checkout = checkout_with_item
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -2246,11 +2262,11 @@ def test_is_fully_paid_partially_paid(checkout_with_item, payment_dummy):
payment.currency = total.gross.currency
payment.checkout = checkout
payment.save()
- is_paid = is_fully_paid(checkout, None)
+ is_paid = is_fully_paid(checkout, list(checkout), None)
assert not is_paid
def test_is_fully_paid_no_payment(checkout_with_item):
checkout = checkout_with_item
- is_paid = is_fully_paid(checkout, None)
+ is_paid = is_fully_paid(checkout, list(checkout), None)
assert not is_paid
diff --git a/tests/api/test_checkout_digital.py b/tests/api/test_checkout_digital.py
index 7ba8f8845e..20ebbad319 100644
--- a/tests/api/test_checkout_digital.py
+++ b/tests/api/test_checkout_digital.py
@@ -179,7 +179,7 @@ def test_checkout_complete(
checkout.save(update_fields=["billing_address"])
# Create a dummy payment to charge
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
payment = payment_dummy
payment.is_active = True
payment.order = None
@@ -209,7 +209,7 @@ def test_remove_shipping_method_if_only_digital_in_checkout(
checkout.save()
assert checkout.shipping_method
- update_checkout_shipping_method_if_invalid(checkout, None)
+ update_checkout_shipping_method_if_invalid(checkout, list(checkout), None)
checkout.refresh_from_db()
assert not checkout.shipping_method
diff --git a/tests/api/test_checkout_promo_codes.py b/tests/api/test_checkout_promo_codes.py
index 1540d1af9c..55a0d97f8c 100644
--- a/tests/api/test_checkout_promo_codes.py
+++ b/tests/api/test_checkout_promo_codes.py
@@ -17,11 +17,13 @@ from tests.api.utils import get_graphql_content
def test_checkout_lines_delete_with_not_applicable_voucher(
user_api_client, checkout_with_item, voucher
):
- subtotal = calculations.checkout_subtotal(checkout_with_item)
+ subtotal = calculations.checkout_subtotal(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
voucher.min_spent = subtotal.gross
voucher.save(update_fields=["min_spent_amount", "currency"])
- add_voucher_to_checkout(checkout_with_item, voucher)
+ add_voucher_to_checkout(checkout_with_item, list(checkout_with_item), voucher)
assert checkout_with_item.voucher_code == voucher.code
line = checkout_with_item.lines.first()
@@ -58,7 +60,7 @@ def test_checkout_shipping_address_update_with_not_applicable_voucher(
voucher = voucher_shipping_type
assert voucher.countries[0].code == address_other_country.country
- add_voucher_to_checkout(checkout_with_item, voucher)
+ add_voucher_to_checkout(checkout_with_item, list(checkout_with_item), voucher)
assert checkout_with_item.voucher_code == voucher.code
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
@@ -121,12 +123,14 @@ def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
collection_ids=set(),
)
]
- taxed_total = calculations.checkout_total(checkout, discounts=discounts)
+ taxed_total = calculations.checkout_total(
+ checkout=checkout, lines=list(checkout), discounts=discounts
+ )
assert data["totalPrice"]["gross"]["amount"] == taxed_total.gross.amount
assert data["subtotalPrice"]["gross"]["amount"] == taxed_total.gross.amount
line = checkout.lines.first()
- line_total = calculations.checkout_line_total(line, discounts=discounts)
+ line_total = calculations.checkout_line_total(line=line, discounts=discounts)
assert data["lines"][0]["totalPrice"]["gross"]["amount"] == line_total.gross.amount
@@ -231,9 +235,12 @@ def test_checkout_add_voucher_code(api_client, checkout_with_item, voucher):
def test_checkout_add_voucher_code_checkout_with_sale(
api_client, checkout_with_item, voucher_percentage, discount_info
):
+ lines = list(checkout_with_item)
assert calculations.checkout_subtotal(
- checkout_with_item
- ) > calculations.checkout_subtotal(checkout_with_item, discounts=[discount_info])
+ checkout=checkout_with_item, lines=lines
+ ) > calculations.checkout_subtotal(
+ checkout=checkout_with_item, lines=lines, discounts=[discount_info]
+ )
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
variables = {"checkoutId": checkout_id, "promoCode": voucher_percentage.code}
data = _mutate_checkout_add_promo_code(api_client, variables)
@@ -250,8 +257,11 @@ def test_checkout_add_specific_product_voucher_code_checkout_with_sale(
voucher = voucher_specific_product_type
checkout = checkout_with_item
expected_discount = Decimal(1.5)
- assert calculations.checkout_subtotal(checkout) > calculations.checkout_subtotal(
- checkout, discounts=[discount_info]
+ lines = list(checkout)
+ assert calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ) > calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=[discount_info]
)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id, "promoCode": voucher.code}
@@ -274,8 +284,11 @@ def test_checkout_add_products_voucher_code_checkout_with_sale(
voucher.save()
voucher.products.add(product)
- assert calculations.checkout_subtotal(checkout) > calculations.checkout_subtotal(
- checkout, discounts=[discount_info]
+ lines = list(checkout)
+ assert calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ) > calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=[discount_info]
)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id, "promoCode": voucher.code}
@@ -298,8 +311,11 @@ def test_checkout_add_collection_voucher_code_checkout_with_sale(
voucher.save()
voucher.collections.add(collection)
- assert calculations.checkout_subtotal(checkout) > calculations.checkout_subtotal(
- checkout, discounts=[discount_info]
+ lines = list(checkout)
+ assert calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ) > calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=[discount_info]
)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id, "promoCode": voucher.code}
@@ -321,8 +337,11 @@ def test_checkout_add_category_code_checkout_with_sale(
voucher.save()
voucher.categories.add(category)
- assert calculations.checkout_subtotal(checkout) > calculations.checkout_subtotal(
- checkout, discounts=[discount_info]
+ lines = list(checkout)
+ assert calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ) > calculations.checkout_subtotal(
+ checkout=checkout, lines=lines, discounts=[discount_info]
)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id, "promoCode": voucher.code}
@@ -380,7 +399,9 @@ def test_checkout_add_many_gift_card_code(
def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_card):
- taxed_total = calculations.checkout_total(checkout_with_item)
+ taxed_total = calculations.checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
total_with_gift_card = taxed_total.gross.amount - gift_card.current_balance_amount
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
@@ -396,7 +417,9 @@ def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_
def test_checkout_get_total_with_many_gift_card(
api_client, checkout_with_gift_card, gift_card_created_by_staff
):
- taxed_total = calculations.checkout_total(checkout_with_gift_card)
+ taxed_total = calculations.checkout_total(
+ checkout=checkout_with_gift_card, lines=list(checkout_with_gift_card)
+ )
taxed_total.gross -= checkout_with_gift_card.get_total_gift_cards_balance()
taxed_total.net -= checkout_with_gift_card.get_total_gift_cards_balance()
total_with_gift_card = (
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index 676fffe915..bc8cc52f92 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -96,7 +96,7 @@ def test_checkout_add_payment(user_api_client, checkout_with_item, address):
checkout.save()
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
variables = {
"checkoutId": checkout_id,
"input": {
@@ -133,7 +133,7 @@ def test_checkout_add_payment_default_amount(
checkout.save()
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
variables = {
"checkoutId": checkout_id,
@@ -166,7 +166,10 @@ def test_checkout_add_payment_bad_amount(user_api_client, checkout_with_item, ad
"gateway": "DUMMY",
"token": "sample-token",
"amount": str(
- calculations.checkout_total(checkout).gross.amount + Decimal(1)
+ calculations.checkout_total(
+ checkout=checkout, lines=list(checkout)
+ ).gross.amount
+ + Decimal(1)
),
},
}
@@ -184,7 +187,7 @@ def test_use_checkout_billing_address_as_payment_billing(
):
checkout = checkout_with_item
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
- total = calculations.checkout_total(checkout)
+ total = calculations.checkout_total(checkout=checkout, lines=list(checkout))
variables = {
"checkoutId": checkout_id,
"input": {
diff --git a/tests/plugins/sample_plugins.py b/tests/plugins/sample_plugins.py
index c91472eb53..36767715b0 100644
--- a/tests/plugins/sample_plugins.py
+++ b/tests/plugins/sample_plugins.py
@@ -49,15 +49,15 @@ class PluginSample(BasePlugin):
},
}
- def calculate_checkout_total(self, checkout, discounts, previous_value):
+ def calculate_checkout_total(self, checkout, lines, discounts, previous_value):
total = Money("1.0", currency=checkout.currency)
return TaxedMoney(total, total)
- def calculate_checkout_subtotal(self, checkout, discounts, previous_value):
+ def calculate_checkout_subtotal(self, checkout, lines, discounts, previous_value):
subtotal = Money("1.0", currency=checkout.currency)
return TaxedMoney(subtotal, subtotal)
- def calculate_checkout_shipping(self, checkout, discounts, previous_value):
+ def calculate_checkout_shipping(self, checkout, lines, discounts, previous_value):
price = Money("1.0", currency=checkout.currency)
return TaxedMoney(price, price)
diff --git a/tests/plugins/test_avatax.py b/tests/plugins/test_avatax.py
index 813511cf81..5dc14542f8 100644
--- a/tests/plugins/test_avatax.py
+++ b/tests/plugins/test_avatax.py
@@ -133,7 +133,9 @@ def test_calculate_checkout_total(
product.save()
discounts = [discount_info] if with_discount else None
- total = manager.calculate_checkout_total(checkout_with_item, discounts)
+ total = manager.calculate_checkout_total(
+ checkout_with_item, list(checkout_with_item), discounts
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -164,7 +166,7 @@ def test_calculate_checkout_shipping(
checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.save()
shipping_price = manager.calculate_checkout_shipping(
- checkout_with_item, [discount_info]
+ checkout_with_item, list(checkout_with_item), [discount_info]
)
shipping_price = quantize_price(shipping_price, shipping_price.currency)
assert shipping_price == TaxedMoney(
@@ -214,7 +216,9 @@ def test_calculate_checkout_subtotal(
discounts = [discount_info] if with_discount else None
add_variant_to_checkout(checkout_with_item, variant, 2)
- total = manager.calculate_checkout_subtotal(checkout_with_item, discounts)
+ total = manager.calculate_checkout_subtotal(
+ checkout_with_item, list(checkout_with_item), discounts
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
diff --git a/tests/plugins/test_manager.py b/tests/plugins/test_manager.py
index 88126022e4..3795462dae 100644
--- a/tests/plugins/test_manager.py
+++ b/tests/plugins/test_manager.py
@@ -33,7 +33,9 @@ def test_manager_calculates_checkout_total(
currency = checkout_with_item.currency
expected_total = Money(total_amount, currency)
manager = PluginsManager(plugins=plugins)
- taxed_total = manager.calculate_checkout_total(checkout_with_item, [discount_info])
+ taxed_total = manager.calculate_checkout_total(
+ checkout_with_item, list(checkout_with_item), [discount_info]
+ )
assert TaxedMoney(expected_total, expected_total) == taxed_total
@@ -47,7 +49,7 @@ def test_manager_calculates_checkout_subtotal(
currency = checkout_with_item.currency
expected_subtotal = Money(subtotal_amount, currency)
taxed_subtotal = PluginsManager(plugins=plugins).calculate_checkout_subtotal(
- checkout_with_item, [discount_info]
+ checkout_with_item, list(checkout_with_item), [discount_info]
)
assert TaxedMoney(expected_subtotal, expected_subtotal) == taxed_subtotal
@@ -62,7 +64,7 @@ def test_manager_calculates_checkout_shipping(
currency = checkout_with_item.currency
expected_shipping_price = Money(shipping_amount, currency)
taxed_shipping_price = PluginsManager(plugins=plugins).calculate_checkout_shipping(
- checkout_with_item, [discount_info]
+ checkout_with_item, list(checkout_with_item), [discount_info]
)
assert (
TaxedMoney(expected_shipping_price, expected_shipping_price)
diff --git a/tests/plugins/test_vatlayer.py b/tests/plugins/test_vatlayer.py
index b89a81f170..78f324c34f 100644
--- a/tests/plugins/test_vatlayer.py
+++ b/tests/plugins/test_vatlayer.py
@@ -236,7 +236,9 @@ def test_calculate_checkout_total(
site_settings.save()
discounts = [discount_info] if with_discount else None
- total = manager.calculate_checkout_total(checkout_with_item, discounts)
+ total = manager.calculate_checkout_total(
+ checkout_with_item, list(checkout_with_item), discounts
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -284,7 +286,9 @@ def test_calculate_checkout_subtotal(
discounts = [discount_info] if with_discount else None
add_variant_to_checkout(checkout_with_item, variant, 2)
- total = manager.calculate_checkout_subtotal(checkout_with_item, discounts)
+ total = manager.calculate_checkout_subtotal(
+ checkout_with_item, list(checkout_with_item), discounts
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -433,7 +437,9 @@ def test_calculations_checkout_total_with_vatlayer(
vatlayer, settings, checkout_with_item
):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
- checkout_subtotal = calculations.checkout_total(checkout_with_item)
+ checkout_subtotal = calculations.checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
assert checkout_subtotal == TaxedMoney(
net=Money("30", "USD"), gross=Money("30", "USD")
)
@@ -443,7 +449,9 @@ def test_calculations_checkout_subtotal_with_vatlayer(
vatlayer, settings, checkout_with_item
):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
- checkout_subtotal = calculations.checkout_subtotal(checkout_with_item)
+ checkout_subtotal = calculations.checkout_subtotal(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
assert checkout_subtotal == TaxedMoney(
net=Money("30", "USD"), gross=Money("30", "USD")
)
@@ -453,7 +461,9 @@ def test_calculations_checkout_shipping_price_with_vatlayer(
vatlayer, settings, checkout_with_item
):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
- checkout_shipping_price = calculations.checkout_shipping_price(checkout_with_item)
+ checkout_shipping_price = calculations.checkout_shipping_price(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ )
assert checkout_shipping_price == TaxedMoney(
net=Money("0", "USD"), gross=Money("0", "USD")
)
diff --git a/tests/settings.py b/tests/settings.py
index 3ba3c75615..57d8ffbce9 100644
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -37,16 +37,10 @@ EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
VATLAYER_ACCESS_KEY = ""
-if "sqlite" in DATABASES["default"]["ENGINE"]: # noqa
- DATABASES["default"]["TEST"] = { # noqa
- "SERIALIZE": False,
- "NAME": ":memory:",
- "MIRROR": None,
- }
-
COUNTRIES_ONLY = None
MEDIA_ROOT = None
+MEDIA_URL = "/media/"
MAX_CHECKOUT_LINE_QUANTITY = 50
AUTH_PASSWORD_VALIDATORS = []
diff --git a/tests/test_cart.py b/tests/test_cart.py
index cc7f1d5dd9..658d95f143 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -70,7 +70,10 @@ def test_adding_same_variant(checkout, product):
assert checkout.lines.count() == 1
assert checkout.quantity == 3
subtotal = TaxedMoney(Money("30.00", "USD"), Money("30.00", "USD"))
- assert calculations.checkout_subtotal(checkout) == subtotal
+ assert (
+ calculations.checkout_subtotal(checkout=checkout, lines=list(checkout))
+ == subtotal
+ )
def test_replacing_same_variant(checkout, product):
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 9797d4a7bb..abf7c0ab71 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -32,9 +32,9 @@ from saleor.core.exceptions import InsufficientStock
from saleor.core.taxes import zero_money, zero_taxed_money
from saleor.discount import DiscountValueType, VoucherType
from saleor.discount.models import NotApplicable, Voucher
-from saleor.plugins.manager import get_plugins_manager
from saleor.order import OrderEvents, OrderEventsEmails
from saleor.order.models import OrderEvent
+from saleor.plugins.manager import get_plugins_manager
from saleor.shipping.models import ShippingZone
from .utils import flush_post_commit_hooks
@@ -44,18 +44,19 @@ def test_is_valid_shipping_method(checkout_with_item, address, shipping_zone):
checkout = checkout_with_item
checkout.shipping_address = address
checkout.save()
+ lines = list(checkout)
# no shipping method assigned
- assert not is_valid_shipping_method(checkout, None)
+ assert not is_valid_shipping_method(checkout, lines, None)
shipping_method = shipping_zone.shipping_methods.first()
checkout.shipping_method = shipping_method
checkout.save()
- assert is_valid_shipping_method(checkout, None)
+ assert is_valid_shipping_method(checkout, lines, None)
zone = ShippingZone.objects.create(name="DE", countries=["DE"])
shipping_method.shipping_zone = zone
shipping_method.save()
- assert not is_valid_shipping_method(checkout, None)
+ assert not is_valid_shipping_method(checkout, lines, None)
def test_clear_shipping_method(checkout, shipping_method):
@@ -108,7 +109,10 @@ def test_create_order_creates_expected_events(
order = create_order(
checkout=checkout,
order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None
+ checkout=checkout,
+ lines=list(checkout),
+ tracking_code="tracking_code",
+ discounts=None,
),
user=customer_user if not is_anonymous_user else AnonymousUser(),
redirect_url="https://www.example.com",
@@ -163,7 +167,10 @@ def test_create_order_insufficient_stock(
with pytest.raises(InsufficientStock):
prepare_order_data(
- checkout=request_checkout, tracking_code="tracking_code", discounts=None
+ checkout=request_checkout,
+ lines=list(request_checkout),
+ tracking_code="tracking_code",
+ discounts=None,
)
@@ -177,7 +184,9 @@ def test_create_order_doesnt_duplicate_order(
checkout.shipping_method = shipping_method
checkout.save()
- order_data = prepare_order_data(checkout=checkout, tracking_code="", discounts=None)
+ order_data = prepare_order_data(
+ checkout=checkout, lines=list(checkout), tracking_code="", discounts=None
+ )
order_1 = create_order(
checkout=checkout,
@@ -208,8 +217,11 @@ def test_create_order_with_gift_card(
checkout.shipping_method = shipping_method
checkout.save()
- subtotal = calculations.checkout_subtotal(checkout)
- shipping_price = calculations.checkout_shipping_price(checkout)
+ lines = list(checkout)
+ subtotal = calculations.checkout_subtotal(checkout=checkout, lines=lines)
+ shipping_price = calculations.checkout_shipping_price(
+ checkout=checkout, lines=lines
+ )
total_gross_without_gift_cards = (
subtotal.gross + shipping_price.gross - checkout.discount
)
@@ -218,7 +230,10 @@ def test_create_order_with_gift_card(
order = create_order(
checkout=checkout,
order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None
+ checkout=checkout,
+ lines=lines,
+ tracking_code="tracking_code",
+ discounts=None,
),
user=customer_user if not is_anonymous_user else AnonymousUser(),
redirect_url="https://www.example.com",
@@ -239,7 +254,9 @@ def test_create_order_with_gift_card_partial_use(
checkout.shipping_method = shipping_method
checkout.save()
- price_without_gift_card = calculations.checkout_total(checkout)
+ price_without_gift_card = calculations.checkout_total(
+ checkout=checkout, lines=list(checkout)
+ )
gift_card_balance_before_order = gift_card_used.current_balance_amount
checkout.gift_cards.add(gift_card_used)
@@ -248,7 +265,10 @@ def test_create_order_with_gift_card_partial_use(
order = create_order(
checkout=checkout,
order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None
+ checkout=checkout,
+ lines=list(checkout),
+ tracking_code="tracking_code",
+ discounts=None,
),
user=customer_user,
redirect_url="https://www.example.com",
@@ -279,7 +299,9 @@ def test_create_order_with_many_gift_cards(
checkout.shipping_method = shipping_method
checkout.save()
- price_without_gift_card = calculations.checkout_total(checkout)
+ price_without_gift_card = calculations.checkout_total(
+ checkout=checkout, lines=list(checkout)
+ )
gift_cards_balance_before_order = (
gift_card_created_by_staff.current_balance.amount
+ gift_card.current_balance.amount
@@ -292,7 +314,10 @@ def test_create_order_with_many_gift_cards(
order = create_order(
checkout=checkout,
order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None
+ checkout=checkout,
+ lines=list(checkout),
+ tracking_code="tracking_code",
+ discounts=None,
),
user=customer_user,
redirect_url="https://www.example.com",
@@ -317,6 +342,7 @@ def test_note_in_created_order(request_checkout_with_item, address, customer_use
checkout=request_checkout_with_item,
order_data=prepare_order_data(
checkout=request_checkout_with_item,
+ lines=list(request_checkout_with_item),
tracking_code="tracking_code",
discounts=None,
),
@@ -360,13 +386,13 @@ def test_get_discount_for_checkout_value_voucher(
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
- discount = get_voucher_discount_for_checkout(voucher, checkout)
+ discount = get_voucher_discount_for_checkout(voucher, checkout, [], [])
assert discount == Money(expected_value, "USD")
@@ -374,9 +400,13 @@ def test_get_discount_for_checkout_value_voucher(
def test_get_voucher_discount_for_checkout_voucher_validation(
mock_validate_voucher, voucher, checkout_with_voucher
):
- get_voucher_discount_for_checkout(voucher, checkout_with_voucher)
+ get_voucher_discount_for_checkout(
+ voucher, checkout_with_voucher, list(checkout_with_voucher)
+ )
manager = get_plugins_manager()
- subtotal = manager.calculate_checkout_subtotal(checkout_with_voucher, [])
+ subtotal = manager.calculate_checkout_subtotal(
+ checkout_with_voucher, list(checkout_with_voucher), []
+ )
quantity = checkout_with_voucher.quantity
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
@@ -418,14 +448,14 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
with pytest.raises(NotApplicable):
- get_voucher_discount_for_checkout(voucher, checkout)
+ get_voucher_discount_for_checkout(voucher, checkout, [], [])
@pytest.mark.parametrize(
@@ -455,7 +485,9 @@ def test_get_discount_for_checkout_specific_products_voucher(
)
for product in product_list:
voucher.products.add(product)
- discount = get_voucher_discount_for_checkout(voucher, checkout_with_items)
+ discount = get_voucher_discount_for_checkout(
+ voucher, checkout_with_items, list(checkout_with_items)
+ )
assert discount == Money(discount_amount, "USD")
@@ -490,13 +522,13 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: TaxedMoney(
+ lambda checkout, lines, discounts: TaxedMoney(
Money(total, "USD"), Money(total, "USD")
),
)
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: TaxedMoney(
+ lambda checkout, lines, discounts: TaxedMoney(
Money(total, "USD"), Money(total, "USD")
),
)
@@ -513,7 +545,7 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
)
checkout = Mock(quantity=total_quantity, spec=Checkout)
with pytest.raises(NotApplicable):
- get_voucher_discount_for_checkout(voucher, checkout, discounts)
+ get_voucher_discount_for_checkout(voucher, checkout, [], discounts)
@pytest.mark.parametrize(
@@ -538,11 +570,11 @@ def test_get_discount_for_checkout_shipping_voucher(
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
shipping_total = Money(shipping_cost, "USD")
checkout = Mock(
@@ -559,7 +591,7 @@ def test_get_discount_for_checkout_shipping_voucher(
discount_value=discount_value,
countries=countries,
)
- discount = get_voucher_discount_for_checkout(voucher, checkout)
+ discount = get_voucher_discount_for_checkout(voucher, checkout, [])
assert discount == Money(expected_value, "USD")
@@ -567,16 +599,16 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(monkeypatch):
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
shipping_total = TaxedMoney(Money(10, "USD"), Money(10, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_shipping_price",
- lambda checkout, discounts: shipping_total,
+ lambda checkout, lines, discounts: shipping_total,
)
checkout = Mock(
spec=Checkout,
@@ -592,7 +624,7 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(monkeypatch):
countries=[],
)
- discount = get_voucher_discount_for_checkout(voucher, checkout)
+ discount = get_voucher_discount_for_checkout(voucher, checkout, [])
assert discount == Money(5, "USD")
@@ -602,7 +634,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatc
shipping_total = TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
checkout = Mock(
get_subtotal=Mock(return_value=subtotal),
@@ -619,7 +651,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatc
)
with pytest.raises(NotApplicable):
- get_voucher_discount_for_checkout(voucher, checkout)
+ get_voucher_discount_for_checkout(voucher, checkout, [])
@pytest.mark.parametrize(
@@ -716,11 +748,11 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
):
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
monkeypatch.setattr(
"saleor.discount.utils.calculations.checkout_subtotal",
- lambda checkout, discounts: subtotal,
+ lambda checkout, lines, discounts: subtotal,
)
checkout = Mock(
is_shipping_required=Mock(return_value=is_shipping_required),
@@ -741,7 +773,7 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
countries=countries,
)
with pytest.raises(NotApplicable) as e:
- get_voucher_discount_for_checkout(voucher, checkout)
+ get_voucher_discount_for_checkout(voucher, checkout, [])
assert str(e.value) == error_msg
@@ -780,7 +812,9 @@ def test_recalculate_checkout_discount(
voucher.discount_value = 10
voucher.save()
- recalculate_checkout_discount(checkout_with_voucher, None)
+ recalculate_checkout_discount(
+ checkout_with_voucher, list(checkout_with_voucher), None
+ )
assert (
checkout_with_voucher.translated_discount_name == voucher_translation_fr.name
) # noqa
@@ -791,10 +825,10 @@ def test_recalculate_checkout_discount_with_sale(
checkout_with_voucher_percentage, discount_info
):
checkout = checkout_with_voucher_percentage
- recalculate_checkout_discount(checkout, [discount_info])
+ recalculate_checkout_discount(checkout, list(checkout), [discount_info])
assert checkout.discount == Money("1.50", "USD")
assert calculations.checkout_total(
- checkout, discounts=[discount_info]
+ checkout=checkout, lines=list(checkout), discounts=[discount_info]
).gross == Money("13.50", "USD")
@@ -805,7 +839,9 @@ def test_recalculate_checkout_discount_voucher_not_applicable(
voucher.min_spent = Money(100, "USD")
voucher.save(update_fields=["min_spent_amount", "currency"])
- recalculate_checkout_discount(checkout_with_voucher, None)
+ recalculate_checkout_discount(
+ checkout_with_voucher, list(checkout_with_voucher), None
+ )
assert not checkout.voucher_code
assert not checkout.discount_name
@@ -818,7 +854,9 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
voucher.end_date = date_yesterday
voucher.save()
- recalculate_checkout_discount(checkout_with_voucher, None)
+ recalculate_checkout_discount(
+ checkout_with_voucher, list(checkout_with_voucher), None
+ )
assert not checkout.voucher_code
assert not checkout.discount_name
@@ -832,18 +870,19 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping
):
checkout = checkout_with_voucher_percentage_and_shipping
- shipping_method.price = calculations.checkout_subtotal(checkout).gross + Money(
- "10.00", "USD"
- )
+ lines = list(checkout)
+ shipping_method.price = calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ).gross + Money("10.00", "USD")
shipping_method.save()
- recalculate_checkout_discount(checkout, None)
+ recalculate_checkout_discount(checkout, lines, None)
assert checkout.discount == shipping_method.price
assert checkout.discount_name == "Free shipping"
- assert calculations.checkout_total(checkout) == calculations.checkout_subtotal(
- checkout
- )
+ assert calculations.checkout_total(
+ checkout=checkout, lines=lines
+ ) == calculations.checkout_subtotal(checkout=checkout, lines=lines)
def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shipping(
@@ -853,18 +892,19 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
):
checkout = checkout_with_voucher_percentage_and_shipping
- shipping_method.price = calculations.checkout_subtotal(checkout).gross - Money(
- "1.00", "USD"
- )
+ lines = list(checkout)
+ shipping_method.price = calculations.checkout_subtotal(
+ checkout=checkout, lines=lines
+ ).gross - Money("1.00", "USD")
shipping_method.save()
- recalculate_checkout_discount(checkout, None)
+ recalculate_checkout_discount(checkout, lines, None)
assert checkout.discount == shipping_method.price
assert checkout.discount_name == "Free shipping"
- assert calculations.checkout_total(checkout) == calculations.checkout_subtotal(
- checkout
- )
+ assert calculations.checkout_total(
+ checkout=checkout, lines=lines
+ ) == calculations.checkout_subtotal(checkout=checkout, lines=lines)
def test_recalculate_checkout_discount_free_shipping_for_checkout_without_shipping(
@@ -872,7 +912,7 @@ def test_recalculate_checkout_discount_free_shipping_for_checkout_without_shippi
):
checkout = checkout_with_voucher_percentage
- recalculate_checkout_discount(checkout, None)
+ recalculate_checkout_discount(checkout, list(checkout), None)
assert not checkout.discount_name
assert not checkout.voucher_code
@@ -953,7 +993,7 @@ def test_change_address_in_checkout_from_user_address_to_other(
def test_add_voucher_to_checkout(checkout_with_item, voucher):
assert checkout_with_item.voucher_code is None
- add_voucher_to_checkout(checkout_with_item, voucher)
+ add_voucher_to_checkout(checkout_with_item, list(checkout_with_item), voucher)
assert checkout_with_item.voucher_code == voucher.code
@@ -962,7 +1002,11 @@ def test_add_voucher_to_checkout_fail(
checkout_with_item, voucher_with_high_min_spent_amount
):
with pytest.raises(NotApplicable):
- add_voucher_to_checkout(checkout_with_item, voucher_with_high_min_spent_amount)
+ add_voucher_to_checkout(
+ checkout_with_item,
+ list(checkout_with_item),
+ voucher_with_high_min_spent_amount,
+ )
assert checkout_with_item.voucher_code is None
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index bc24f9d00e..f6e5e40872 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -129,7 +129,9 @@ def test_specific_products_voucher_checkout_discount(
)
voucher.save()
checkout = checkout_with_item
- discount = get_voucher_discount_for_checkout(voucher, checkout, discounts)
+ discount = get_voucher_discount_for_checkout(
+ voucher, checkout, list(checkout), discounts
+ )
assert discount == Money(expected_value, "USD")
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 5e3c8588e4..b9f22f7e48 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -101,7 +101,9 @@ def test_create_payment(checkout_with_item, address):
data = {
"gateway": "Dummy",
"payment_token": "token",
- "total": checkout_total(checkout_with_item).gross.amount,
+ "total": checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ ).gross.amount,
"currency": checkout_with_item.currency,
"email": "[email protected]",
"customer_ip_address": "127.0.0.1",
@@ -127,16 +129,16 @@ def test_create_payment_requires_order_or_checkout(settings):
assert e.value.args[0] == "Must provide checkout or order to create a payment."
-def test_create_payment_from_checkout_requires_billing_address(
- checkout_with_item, settings
-):
+def test_create_payment_from_checkout_requires_billing_address(checkout_with_item):
checkout_with_item.billing_address = None
checkout_with_item.save()
data = {
"gateway": "Dummy",
"payment_token": "token",
- "total": checkout_total(checkout_with_item),
+ "total": checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ ),
"currency": checkout_with_item.currency,
"email": "[email protected]",
"checkout": checkout_with_item,
@@ -146,7 +148,7 @@ def test_create_payment_from_checkout_requires_billing_address(
assert e.value.code == PaymentErrorCode.BILLING_ADDRESS_NOT_SET.value
-def test_create_payment_from_order_requires_billing_address(draft_order, settings):
+def test_create_payment_from_order_requires_billing_address(draft_order):
draft_order.billing_address = None
draft_order.save()
@@ -170,7 +172,9 @@ def test_create_payment_information_for_checkout_payment(address, checkout_with_
data = {
"gateway": "Dummy",
"payment_token": "token",
- "total": checkout_total(checkout_with_item).gross.amount,
+ "total": checkout_total(
+ checkout=checkout_with_item, lines=list(checkout_with_item)
+ ).gross.amount,
"currency": checkout_with_item.currency,
"email": "[email protected]",
"customer_ip_address": "127.0.0.1",