Skip to content

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

Introduce anonymous checkout (#8533)

Iga Karbowiak3363947b98cf
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 9f11897ee9..06c61ccfb5 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -1,5 +1,5 @@
from datetime import date
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, cast
import graphene
from django.contrib.sites.models import Site
@@ -29,8 +29,9 @@ from ..giftcard.utils import fulfill_non_shippable_gift_cards
from ..graphql.checkout.utils import (
prepare_insufficient_stock_checkout_validation_error,
)
-from ..order import OrderLineData, OrderOrigin, OrderStatus
+from ..order import OrderOrigin, OrderStatus
from ..order.actions import order_created
+from ..order.fetch import OrderInfo, OrderLineInfo
from ..order.models import Order, OrderLine
from ..order.notifications import send_order_confirmation
from ..order.search import prepare_order_search_document_value
@@ -74,7 +75,8 @@ def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
if voucher.usage_limit:
increase_voucher_usage(voucher)
if voucher.apply_once_per_customer:
- add_voucher_usage_by_customer(voucher, checkout_info.get_customer_email())
+ customer_email = cast(str, checkout_info.get_customer_email())
+ add_voucher_usage_by_customer(voucher, customer_email)
return {
"voucher": voucher,
}
@@ -148,7 +150,7 @@ def _create_line_for_order(
products_translation: Dict[int, Optional[str]],
variants_translation: Dict[int, Optional[str]],
taxes_included_in_prices: bool,
-) -> OrderLineData:
+) -> OrderLineInfo:
"""Create a line for the given order.
:raises InsufficientStock: when there is not enough items in stock for this variant.
@@ -250,10 +252,13 @@ def _create_line_for_order(
unit_discount_reason=unit_discount_reason,
unit_discount_value=discount_amount.amount, # we store value as fixed discount
)
- line_info = OrderLineData(
+ is_digital = line.is_digital
+ line_info = OrderLineInfo(
line=line,
quantity=quantity,
+ is_digital=is_digital,
variant=variant,
+ digital_content=variant.digital_content if is_digital and variant else None,
warehouse_pk=checkout_info.delivery_method_info.warehouse_pk,
)
@@ -267,7 +272,7 @@ def _create_lines_for_order(
discounts: Iterable[DiscountInfo],
check_reservations: bool,
taxes_included_in_prices: bool,
-) -> Iterable[OrderLineData]:
+) -> Iterable[OrderLineInfo]:
"""Create a lines for the given order.
:raises InsufficientStock: when there is not enough items in stock for this variant.
@@ -526,13 +531,23 @@ def _create_order(
order, order_lines, site_settings, user, app, manager
)
+ order_info = OrderInfo(
+ order=order,
+ customer_email=order_data["user_email"],
+ channel=checkout_info.channel,
+ payment=order.get_last_payment(),
+ lines_data=order_lines_info,
+ )
+
transaction.on_commit(
- lambda: order_created(order=order, user=user, app=app, manager=manager)
+ lambda: order_created(
+ order_info=order_info, user=user, app=app, manager=manager
+ )
)
# Send the order confirmation email
transaction.on_commit(
- lambda: send_order_confirmation(order, checkout.redirect_url, manager)
+ lambda: send_order_confirmation(order_info, checkout.redirect_url, manager)
)
return order
diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.py
index 2bf89fcbec..7fde5c785a 100644
--- a/saleor/checkout/error_codes.py
+++ b/saleor/checkout/error_codes.py
@@ -27,3 +27,4 @@ class CheckoutErrorCode(Enum):
MISSING_CHANNEL_SLUG = "missing_channel_slug"
CHANNEL_INACTIVE = "channel_inactive"
UNAVAILABLE_VARIANT_IN_CHANNEL = "unavailable_variant_in_channel"
+ EMAIL_NOT_SET = "email_not_set"
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 62336c7b9f..c4bee26ae3 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -68,7 +68,7 @@ class CheckoutInfo:
return self.checkout.country.code
return address.country.code
- def get_customer_email(self) -> str:
+ def get_customer_email(self) -> Optional[str]:
return self.user.email if self.user else self.checkout.email
diff --git a/saleor/checkout/migrations/0039_alter_checkout_email.py b/saleor/checkout/migrations/0039_alter_checkout_email.py
new file mode 100644
index 0000000000..befe15d5a9
--- /dev/null
+++ b/saleor/checkout/migrations/0039_alter_checkout_email.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.6 on 2021-10-06 08:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0038_merge_20210903_1048"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="checkout",
+ name="email",
+ field=models.EmailField(blank=True, max_length=254, null=True),
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index cb90e50af1..19f905db9c 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -46,7 +46,7 @@ class Checkout(ModelWithMetadata):
related_name="checkouts",
on_delete=models.CASCADE,
)
- email = models.EmailField()
+ email = models.EmailField(blank=True, null=True)
token = models.UUIDField(primary_key=True, default=uuid4, editable=False)
channel = models.ForeignKey(
Channel,
@@ -116,7 +116,7 @@ class Checkout(ModelWithMetadata):
def __iter__(self):
return iter(self.lines.all())
- def get_customer_email(self) -> str:
+ def get_customer_email(self) -> Optional[str]:
return self.user.email if self.user else self.email
def is_shipping_required(self) -> bool:
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
new file mode 100644
index 0000000000..2fb0282e70
--- /dev/null
+++ b/saleor/checkout/tasks.py
@@ -0,0 +1,30 @@
+from celery.utils.log import get_task_logger
+from django.conf import settings
+from django.db.models import Q
+from django.utils import timezone
+
+from ..celeryconf import app
+from .models import Checkout
+
+task_logger = get_task_logger(__name__)
+
+
+def delete_expired_checkouts():
+ now = timezone.now()
+ expired_anonymous_checkouts = (
+ Q(email__isnull=True)
+ & Q(user__isnull=True)
+ & Q(last_change__lt=now - settings.ANONYMOUS_CHECKOUTS_TIMEDELTA)
+ )
+ expired_user_checkout = (Q(email__isnull=False) | Q(user__isnull=False)) & Q(
+ last_change__lt=now - settings.USER_CHECKOUTS_TIMEDELTA
+ )
+ empty_checkouts = Q(lines__isnull=True) & Q(
+ last_change__lt=now - settings.EMPTY_CHECKOUTS_TIMEDELTA
+ )
+ count, _ = Checkout.objects.filter(
+ empty_checkouts | expired_anonymous_checkouts | expired_user_checkout
+ ).delete()
+ if count:
+ task_logger.debug("Removed %s checkouts.", count)
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
new file mode 100644
index 0000000000..8033a8f30e
--- /dev/null
+++ b/saleor/checkout/tests/test_tasks.py
@@ -0,0 +1,242 @@
+from datetime import timedelta
+
+import pytest
+from django.utils import timezone
+
+from ..models import Checkout
+from ..tasks import delete_expired_checkouts
+
+
+def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_user):
+ # given
+ now = timezone.now()
+ checkout_count = Checkout.objects.count()
+
+ expired_anonymous_checkout = checkouts_list[0]
+ expired_anonymous_checkout.email = None
+ expired_anonymous_checkout.user = None
+ expired_anonymous_checkout.created = now - timedelta(days=40)
+ expired_anonymous_checkout.last_change = now - timedelta(days=35)
+ expired_anonymous_checkout.lines.create(
+ checkout=expired_anonymous_checkout, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_1 = checkouts_list[1]
+ not_expired_checkout_1.email = None
+ not_expired_checkout_1.user = None
+ not_expired_checkout_1.created = now - timedelta(days=35)
+ not_expired_checkout_1.last_change = now - timedelta(days=29)
+ not_expired_checkout_1.lines.create(
+ checkout=not_expired_checkout_1, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_2 = checkouts_list[2]
+ not_expired_checkout_2.email = None
+ not_expired_checkout_2.user = customer_user
+ not_expired_checkout_2.created = now - timedelta(days=45)
+ not_expired_checkout_2.last_change = now - timedelta(days=40)
+ not_expired_checkout_2.lines.create(
+ checkout=not_expired_checkout_2, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_3 = checkouts_list[3]
+ not_expired_checkout_3.email = "[email protected]"
+ not_expired_checkout_3.user = None
+ not_expired_checkout_3.created = now - timedelta(days=45)
+ not_expired_checkout_3.last_change = now - timedelta(days=40)
+ not_expired_checkout_3.lines.create(
+ checkout=not_expired_checkout_3, variant=variant, quantity=1
+ )
+
+ empty_checkout = checkouts_list[4]
+ empty_checkout.last_change = now - timedelta(hours=8)
+ assert empty_checkout.lines.count() == 0
+
+ Checkout.objects.bulk_update(
+ [
+ expired_anonymous_checkout,
+ not_expired_checkout_1,
+ not_expired_checkout_2,
+ not_expired_checkout_3,
+ ],
+ ["created", "last_change", "email", "user"],
+ )
+
+ # when
+ delete_expired_checkouts()
+
+ # then
+ assert Checkout.objects.count() == checkout_count - 1
+ with pytest.raises(Checkout.DoesNotExist):
+ expired_anonymous_checkout.refresh_from_db()
+
+
+def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
+ # given
+ now = timezone.now()
+ checkout_count = Checkout.objects.count()
+
+ expired_user_checkout_1 = checkouts_list[0]
+ expired_user_checkout_1.email = None
+ expired_user_checkout_1.user = customer_user
+ expired_user_checkout_1.created = now - timedelta(days=100)
+ expired_user_checkout_1.last_change = now - timedelta(days=98)
+ expired_user_checkout_1.lines.create(
+ checkout=expired_user_checkout_1, variant=variant, quantity=1
+ )
+
+ expired_user_checkout_2 = checkouts_list[1]
+ expired_user_checkout_2.email = "[email protected]"
+ expired_user_checkout_2.user = None
+ expired_user_checkout_2.created = now - timedelta(days=100)
+ expired_user_checkout_2.last_change = now - timedelta(days=91)
+ expired_user_checkout_2.lines.create(
+ checkout=expired_user_checkout_2, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_1 = checkouts_list[2]
+ not_expired_checkout_1.email = None
+ not_expired_checkout_1.user = None
+ not_expired_checkout_1.created = now - timedelta(days=35)
+ not_expired_checkout_1.last_change = now - timedelta(days=29)
+ not_expired_checkout_1.lines.create(
+ checkout=not_expired_checkout_1, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_2 = checkouts_list[3]
+ not_expired_checkout_2.email = "[email protected]"
+ not_expired_checkout_2.user = None
+ not_expired_checkout_2.created = now - timedelta(days=100)
+ not_expired_checkout_2.last_change = now - timedelta(days=60)
+ not_expired_checkout_2.lines.create(
+ checkout=not_expired_checkout_2, variant=variant, quantity=1
+ )
+
+ not_expired_checkout_3 = checkouts_list[4]
+ not_expired_checkout_3.email = None
+ not_expired_checkout_3.user = customer_user
+ not_expired_checkout_3.created = now - timedelta(days=100)
+ not_expired_checkout_3.last_change = now - timedelta(days=89)
+ not_expired_checkout_3.lines.create(
+ checkout=not_expired_checkout_3, variant=variant, quantity=1
+ )
+
+ Checkout.objects.bulk_update(
+ [
+ expired_user_checkout_1,
+ expired_user_checkout_2,
+ not_expired_checkout_1,
+ not_expired_checkout_2,
+ not_expired_checkout_3,
+ ],
+ ["created", "last_change", "email", "user"],
+ )
+
+ # when
+ delete_expired_checkouts()
+
+ # then
+ assert Checkout.objects.count() == checkout_count - 2
+ for checkout in [expired_user_checkout_1, expired_user_checkout_2]:
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+
+def test_delete_empty_checkouts(checkouts_list, customer_user, variant):
+ # given
+ now = timezone.now()
+ checkout_count = Checkout.objects.count()
+
+ empty_checkout_1 = checkouts_list[0]
+ empty_checkout_1.last_change = now - timedelta(hours=8)
+ assert empty_checkout_1.lines.count() == 0
+
+ empty_checkout_2 = checkouts_list[1]
+ empty_checkout_2.email = "[email protected]"
+ empty_checkout_2.user = customer_user
+ empty_checkout_2.last_change = now - timedelta(hours=8)
+ assert empty_checkout_2.lines.count() == 0
+
+ empty_checkout_3 = checkouts_list[2]
+ empty_checkout_3.last_change = now - timedelta(hours=2)
+ assert empty_checkout_3.lines.count() == 0
+
+ not_empty_checkout = checkouts_list[3]
+ not_empty_checkout.last_change = now - timedelta(days=2)
+ not_empty_checkout.lines.create(
+ checkout=not_empty_checkout, variant=variant, quantity=1
+ )
+
+ Checkout.objects.bulk_update(
+ [
+ empty_checkout_1,
+ empty_checkout_2,
+ empty_checkout_3,
+ not_empty_checkout,
+ ],
+ ["last_change", "email", "user"],
+ )
+
+ # when
+ delete_expired_checkouts()
+
+ # then
+ for checkout in [empty_checkout_1, empty_checkout_2]:
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+ assert Checkout.objects.count() == checkout_count - 2
+
+
+def test_delete_expired_checkouts(checkouts_list, customer_user, variant):
+ # given
+ now = timezone.now()
+ checkout_count = Checkout.objects.count()
+
+ expired_anonymous_checkout = checkouts_list[0]
+ expired_anonymous_checkout.email = None
+ expired_anonymous_checkout.created = now - timedelta(days=40)
+ expired_anonymous_checkout.last_change = now - timedelta(days=35)
+ expired_anonymous_checkout.lines.create(
+ checkout=expired_anonymous_checkout, variant=variant, quantity=1
+ )
+
+ expired_user_checkout = checkouts_list[2]
+ expired_user_checkout.user = customer_user
+ expired_user_checkout.created = now - timedelta(days=100)
+ expired_user_checkout.last_change = now - timedelta(days=95)
+ expired_user_checkout.lines.create(
+ checkout=expired_user_checkout, variant=variant, quantity=1
+ )
+
+ empty_checkout = checkouts_list[4]
+ empty_checkout.last_change = now - timedelta(hours=8)
+ assert empty_checkout.lines.count() == 0
+
+ Checkout.objects.bulk_update(
+ [
+ expired_anonymous_checkout,
+ expired_user_checkout,
+ empty_checkout,
+ ],
+ ["created", "last_change", "email", "user"],
+ )
+
+ # when
+ delete_expired_checkouts()
+
+ # then
+ assert Checkout.objects.count() == checkout_count - 3
+ for checkout in [expired_anonymous_checkout, expired_user_checkout, empty_checkout]:
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+
+def test_delete_expired_checkouts_no_checkouts_to_delete(checkout):
+ # given
+ checkout_count = Checkout.objects.count()
+
+ # when
+ delete_expired_checkouts()
+
+ # then
+ assert Checkout.objects.count() == checkout_count
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index c7aa226e55..3915ccb2e5 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,5 +1,5 @@
"""Checkout-related utility functions."""
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union, cast
import graphene
from django.core.exceptions import ValidationError
@@ -536,9 +536,10 @@ def add_promo_code_to_checkout(
manager, checkout_info, lines, promo_code, discounts
)
elif promo_code_is_gift_card(promo_code):
+ user_email = cast(str, checkout_info.get_customer_email())
add_gift_card_code_to_checkout(
checkout_info.checkout,
- checkout_info.get_customer_email(),
+ user_email,
promo_code,
checkout_info.channel.currency_code,
)
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 583ba52da9..3e44ba863e 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -11,6 +11,7 @@ from typing import (
Optional,
Set,
Tuple,
+ cast,
)
from django.db.models import F
@@ -205,7 +206,7 @@ def validate_voucher_for_checkout(
discounts=discounts,
)
- customer_email = checkout_info.get_customer_email()
+ customer_email = cast(str, checkout_info.get_customer_email())
validate_voucher(
voucher,
subtotal,
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 9ffb93db8f..cf866e3380 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -275,6 +275,14 @@ def group_quantity_by_variants(lines: List[Dict[str, Any]]) -> List[int]:
return list(variant_quantity_map.values())
+def validate_checkout_email(checkout: models.Checkout):
+ if not checkout.email:
+ raise ValidationError(
+ "Checkout email must be set.",
+ code=CheckoutErrorCode.EMAIL_NOT_SET.value,
+ )
+
+
class CheckoutLineInput(graphene.InputObjectType):
quantity = graphene.Int(required=True, description="The number of items purchased.")
variant_id = graphene.ID(required=True, description="ID of the product variant.")
@@ -1143,6 +1151,18 @@ class CheckoutEmailUpdate(BaseMutation):
error_type_class = CheckoutError
error_type_field = "checkout_errors"
+ @staticmethod
+ def clean_email(email):
+ if not email:
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "This field cannot be blank.",
+ code=CheckoutErrorCode.REQUIRED.value,
+ )
+ }
+ )
+
@classmethod
def perform_mutation(cls, _root, info, email, checkout_id=None, token=None):
# DEPRECATED
@@ -1150,6 +1170,8 @@ class CheckoutEmailUpdate(BaseMutation):
CheckoutErrorCode, "checkout_id", checkout_id, "token", token
)
+ cls.clean_email(email)
+
if token:
checkout = get_checkout_by_token(token)
# DEPRECATED
@@ -1648,6 +1670,8 @@ class CheckoutComplete(BaseMutation):
)
raise e
+ validate_checkout_email(checkout)
+
manager = info.context.plugins
lines = fetch_checkout_lines(checkout)
validate_variants_in_checkout_lines(lines)
@@ -1722,6 +1746,8 @@ class CheckoutAddPromoCode(BaseMutation):
info, checkout_id or token, only_type=Checkout, field="checkout_id"
)
+ validate_checkout_email(checkout)
+
manager = info.context.plugins
discounts = info.context.discounts
lines = fetch_checkout_lines(checkout)
diff --git a/saleor/graphql/checkout/tests/benchmark/conftest.py b/saleor/graphql/checkout/tests/benchmark/conftest.py
index 5c66ae78d3..7bae18e021 100644
--- a/saleor/graphql/checkout/tests/benchmark/conftest.py
+++ b/saleor/graphql/checkout/tests/benchmark/conftest.py
@@ -161,6 +161,47 @@ def checkout_with_charged_payment(checkout_with_voucher):
return checkout
+def checkout_with_digital_line_with_charged_payment(
+ checkout_with_billing_address, digital_content, site_settings
+):
+ checkout = checkout_with_billing_address
+ variant = digital_content.product_variant
+
+ site_settings.automatic_fulfillment_digital_products = True
+ site_settings.save(update_fields=["automatic_fulfillment_digital_products"])
+
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 1)
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ taxed_total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout.shipping_address,
+ )
+ payment = Payment.objects.create(
+ gateway="mirumee.payments.dummy",
+ is_active=True,
+ total=taxed_total.gross.amount,
+ currency="USD",
+ )
+
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.checkout = checkout
+ payment.save()
+
+ payment.transactions.create(
+ amount=payment.total,
+ kind=TransactionKind.CAPTURE,
+ gateway_response={},
+ is_success=True,
+ )
+ return checkout
+
+
@pytest.fixture()
def checkout_with_charged_payment_for_cc(checkout_with_billing_address_for_cc):
checkout = checkout_with_billing_address_for_cc
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 6afc17d4f4..0cbc5ccc74 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -1339,6 +1339,21 @@ def test_complete_checkout_with_single_line(
assert not response["data"]["checkoutComplete"]["errors"]
[email protected]_queries(autouse=False)
+def test_complete_checkout_with_digital_line(
+ api_client, checkout_with_digital_line_with_charged_payment, count_queries
+):
+ query = COMPLETE_CHECKOUT_MUTATION
+
+ variables = {
+ "token": checkout_with_digital_line_with_charged_payment.token,
+ }
+
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+ assert not response["data"]["checkoutComplete"]["errors"]
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_customer_complete_checkout(
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_email_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_email_update.py
index e33c8fe914..7bcf437a4d 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_email_update.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_email_update.py
@@ -26,7 +26,8 @@ CHECKOUT_EMAIL_UPDATE_MUTATION = """
def test_checkout_email_update_by_id(user_api_client, checkout_with_item):
checkout = checkout_with_item
- assert not checkout.email
+ checkout.email = None
+ checkout.save(update_fields=["email"])
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
@@ -44,7 +45,8 @@ def test_checkout_email_update_neither_token_and_id_given(
user_api_client, checkout_with_item
):
checkout = checkout_with_item
- assert not checkout.email
+ checkout.email = None
+ checkout.save(update_fields=["email"])
variables = {"email": email}
@@ -61,10 +63,12 @@ def test_checkout_email_update_both_token_and_id_given(
user_api_client, checkout_with_item
):
checkout = checkout_with_item
- assert not checkout.email
- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ checkout.email = None
+ checkout.save(update_fields=["email"])
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+
variables = {"checkoutId": checkout_id, "token": checkout.token, "email": email}
response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index c94c82ed32..0e89b95ba8 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -611,6 +611,47 @@ def test_checkout_create(api_client, stock, graphql_address_data, channel_USD):
assert not Reservation.objects.exists()
+def test_checkout_create_no_email(api_client, stock, graphql_address_data, channel_USD):
+ """Create checkout object using GraphQL API."""
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ new_checkout = Checkout.objects.first()
+ assert new_checkout is not None
+ checkout_data = content["checkout"]
+ assert checkout_data["token"] == str(new_checkout.token)
+ assert new_checkout.lines.count() == 1
+ checkout_line = new_checkout.lines.first()
+ assert checkout_line.variant == variant
+ assert checkout_line.quantity == 1
+ assert new_checkout.shipping_address is not None
+ assert new_checkout.email is None
+ assert new_checkout.shipping_address.first_name == shipping_address["firstName"]
+ assert new_checkout.shipping_address.last_name == shipping_address["lastName"]
+ assert (
+ new_checkout.shipping_address.street_address_1
+ == shipping_address["streetAddress1"]
+ )
+ assert (
+ new_checkout.shipping_address.street_address_2
+ == shipping_address["streetAddress2"]
+ )
+ assert new_checkout.shipping_address.postal_code == shipping_address["postalCode"]
+ assert new_checkout.shipping_address.country == shipping_address["country"]
+ assert new_checkout.shipping_address.city == shipping_address["city"].upper()
+
+
def test_checkout_create_with_invalid_channel_slug(
api_client, stock, graphql_address_data, channel_USD
):
@@ -862,29 +903,6 @@ def test_checkout_create_reuse_checkout(checkout, user_api_client, stock):
assert len(checkout_data["lines"]) == 1
-def test_checkout_create_required_email(api_client, stock, channel_USD):
- variant = stock.product_variant
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- variables = {
- "checkoutInput": {
- "channel": channel_USD.slug,
- "lines": [{"quantity": 1, "variantId": variant_id}],
- "email": "",
- }
- }
-
- response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
- content = get_graphql_content(response)
-
- errors = content["data"]["checkoutCreate"]["errors"]
- assert errors
- assert errors[0]["field"] == "email"
- assert errors[0]["message"] == "This field cannot be blank."
-
- checkout_errors = content["data"]["checkoutCreate"]["errors"]
- assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.name
-
-
def test_checkout_create_required_country_shipping_address(
api_client, stock, graphql_address_data, channel_USD
):
@@ -2759,7 +2777,8 @@ CHECKOUT_EMAIL_UPDATE_MUTATION = """
def test_checkout_email_update(user_api_client, checkout_with_item):
checkout = checkout_with_item
- assert not checkout.email
+ checkout.email = None
+ checkout.save(update_fields=["email"])
variables = {"token": checkout.token, "email": email}
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 3deb594310..94fb782c2f 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -480,6 +480,24 @@ def test_checkout_complete_gift_card_bought(
assert Fulfillment.objects.count() == 1
+def test_checkout_complete_no_checkout_email(
+ user_api_client,
+ checkout_with_gift_card,
+):
+ checkout = checkout_with_gift_card
+ checkout.email = None
+ checkout.save(update_fields=["email"])
+
+ redirect_url = "https://www.example.com"
+ variables = {"token": checkout.token, "redirectUrl": redirect_url}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name
+
+
def test_checkout_complete_with_variant_without_sku(
site_settings,
user_api_client,
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index fb42a86d74..617fd71ece 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -845,6 +845,19 @@ def test_checkout_add_promo_code_invalidate_shipping_method(
assert shipping_method_id not in data["checkout"]["availableShippingMethods"]
+def test_checkout_add_promo_code_no_checkout_email(
+ api_client, checkout_with_item, voucher
+):
+ checkout_with_item.email = None
+ checkout_with_item.save(update_fields=["email"])
+
+ variables = {"token": checkout_with_item.token, "promoCode": voucher.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name
+
+
MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """
mutation($token: UUID, $promoCode: String, $promoCodeId: ID) {
checkoutRemovePromoCode(
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 149a209442..8d202a132a 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -203,7 +203,7 @@ class Checkout(CountableDjangoObjectType):
description="List of available payment gateways.",
required=True,
)
- email = graphene.String(description="Email of a customer.", required=True)
+ email = graphene.String(description="Email of a customer.", required=False)
gift_cards = graphene.List(
GiftCard, description="List of gift cards associated with this checkout."
)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index efa1352845..c3d73a8798 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -10,9 +10,10 @@ from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
-from ....order import OrderLineData, OrderOrigin, OrderStatus, events, models
+from ....order import OrderOrigin, OrderStatus, events, models
from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderInfo, OrderLineInfo
from ....order.search import (
prepare_order_search_document_value,
update_order_search_document,
@@ -453,12 +454,15 @@ class DraftOrderComplete(BaseMutation):
order.search_document = prepare_order_search_document_value(order)
order.save()
+ channel = order.channel
+ channel_slug = channel.slug
+ order_lines_info = []
for line in order.lines.all():
if line.variant.track_inventory or line.variant.is_preorder_active():
- line_data = OrderLineData(
+ line_data = OrderLineInfo(
line=line, quantity=line.quantity, variant=line.variant
)
- channel_slug = order.channel.slug
+ order_lines_info.append(line_data)
try:
with traced_atomic_transaction():
allocate_stocks(
@@ -480,8 +484,17 @@ class DraftOrderComplete(BaseMutation):
except InsufficientStock as exc:
errors = prepare_insufficient_stock_order_validation_errors(exc)
raise ValidationError({"lines": errors})
+
+ order_info = OrderInfo(
+ order=order,
+ customer_email=order.get_customer_email(),
+ channel=channel,
+ payment=order.get_last_payment(),
+ lines_data=order_lines_info,
+ )
+
order_created(
- order,
+ order_info=order_info,
user=info.context.user,
app=info.context.app,
manager=info.context.plugins,
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 78b3ab54b4..9935991a76 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -8,7 +8,7 @@ from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....giftcard.utils import order_has_gift_card_lines
-from ....order import FulfillmentLineData, FulfillmentStatus, OrderLineData
+from ....order import FulfillmentLineData, FulfillmentStatus
from ....order import models as order_models
from ....order.actions import (
approve_fulfillment,
@@ -20,6 +20,7 @@ from ....order.actions import (
fulfillment_tracking_updated,
)
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo
from ....order.notifications import send_fulfillment_update
from ...core.descriptions import ADDED_IN_31
from ...core.mutations import BaseMutation
@@ -693,7 +694,7 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
)
cleaned_order_lines.append(
- OrderLineData(line=line, quantity=quantity, replace=replace)
+ OrderLineInfo(line=line, quantity=quantity, replace=replace)
)
cleaned_input["order_lines"] = cleaned_order_lines
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index adc94e8731..2211b8c8a3 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -8,7 +8,7 @@ from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....giftcard.utils import deactivate_order_gift_cards, order_has_gift_card_lines
-from ....order import FulfillmentStatus, OrderLineData, OrderStatus, events, models
+from ....order import FulfillmentStatus, OrderStatus, events, models
from ....order.actions import (
cancel_order,
clean_mark_order_as_paid,
@@ -20,6 +20,7 @@ from ....order.actions import (
order_voided,
)
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo, fetch_order_info
from ....order.search import (
prepare_order_search_document_value,
update_order_search_document,
@@ -546,7 +547,8 @@ class OrderCapture(BaseMutation):
)
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- payment = order.get_last_payment()
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
clean_order_capture(payment)
transaction = try_payment_action(
@@ -560,11 +562,12 @@ class OrderCapture(BaseMutation):
amount=amount,
channel_slug=order.channel.slug,
)
+ order_info.payment.refresh_from_db()
# Confirm that we changed the status to capture. Some payment can receive
# asynchronous webhook with update status
if transaction.kind == TransactionKind.CAPTURE:
order_captured(
- order,
+ order_info,
info.context.user,
info.context.app,
amount,
@@ -720,14 +723,15 @@ class OrderConfirm(ModelMutation):
order = cls.get_instance(info, **data)
order.status = OrderStatus.UNFULFILLED
order.save(update_fields=["status"])
- payment = order.get_last_payment()
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
manager = info.context.plugins
if payment and payment.is_authorized and payment.can_capture():
gateway.capture(
payment, info.context.plugins, channel_slug=order.channel.slug
)
order_captured(
- order,
+ order_info,
info.context.user,
info.context.app,
payment.total,
@@ -897,7 +901,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
if order.is_unconfirmed()
else None
)
- line_info = OrderLineData(
+ line_info = OrderLineInfo(
line=line,
quantity=line.quantity,
variant=line.variant,
@@ -977,7 +981,7 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
if instance.order.is_unconfirmed()
else None
)
- line_info = OrderLineData(
+ line_info = OrderLineInfo(
line=instance,
quantity=instance.quantity,
variant=instance.variant,
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 6039910ef5..ab13407de9 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -6,10 +6,11 @@ import pytest
from ....core.exceptions import InsufficientStock, InsufficientStockData
from ....giftcard import GiftCardEvents
from ....giftcard.models import GiftCard, GiftCardEvent
-from ....order import OrderLineData, OrderStatus
+from ....order import OrderStatus
from ....order.actions import fulfill_order_lines
from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
+from ....order.fetch import OrderLineInfo
from ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatus, OrderLine
from ....plugins.manager import get_plugins_manager
from ....product.models import Product, ProductVariant
@@ -1849,12 +1850,12 @@ def test_fulfillment_approve_gift_cards_created(
fulfill_order_lines(
[
- OrderLineData(
+ OrderLineInfo(
line=gift_card_line_1,
quantity=gift_card_line_1.quantity,
warehouse_pk=stock_1.warehouse.pk,
),
- OrderLineData(
+ OrderLineInfo(
line=gift_card_line_2,
quantity=gift_card_line_2.quantity,
warehouse_pk=stock_2.warehouse.pk,
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 2fd3edc6f9..cdc27bf016 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,4 +1,4 @@
-from typing import List
+from typing import TYPE_CHECKING, List
import graphene
from django.core.exceptions import ValidationError
@@ -29,6 +29,9 @@ from ..meta.mutations import MetadataInput
from .types import Payment, PaymentInitialized
from .utils import metadata_contains_empty_key
+if TYPE_CHECKING:
+ from ...checkout import models as checkout_models
+
def description(enum):
if enum is None:
@@ -189,6 +192,14 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
}
)
+ @staticmethod
+ def validate_checkout_email(checkout: "checkout_models.Checkout"):
+ if not checkout.email:
+ raise ValidationError(
+ "Checkout email must be set.",
+ code=PaymentErrorCode.CHECKOUT_EMAIL_NOT_SET.value,
+ )
+
@classmethod
def perform_mutation(cls, _root, info, checkout_id=None, token=None, **data):
# DEPRECATED
@@ -204,6 +215,8 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
info, checkout_id or token, only_type=Checkout, field="checkout_id"
)
+ cls.validate_checkout_email(checkout)
+
data = data["input"]
gateway = data["gateway"]
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index fa2fa40785..f8ff819e58 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -325,6 +325,37 @@ def test_checkout_add_payment_bad_amount(
)
+def test_checkout_add_payment_no_checkout_email(
+ user_api_client, checkout_without_shipping_required, address, customer_user
+):
+ checkout = checkout_without_shipping_required
+ checkout.email = None
+ checkout.save(update_fields=["email"])
+
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.checkout_total(
+ manager=manager, checkout_info=checkout_info, lines=lines, address=address
+ )
+ return_url = "https://www.example.com"
+ variables = {
+ "token": checkout.token,
+ "input": {
+ "gateway": DUMMY_GATEWAY,
+ "token": "sample-token",
+ "amount": total.gross.amount,
+ "returnUrl": return_url,
+ },
+ }
+ response = user_api_client.post_graphql(CREATE_PAYMENT_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutPaymentCreate"]
+
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == PaymentErrorCode.CHECKOUT_EMAIL_NOT_SET.name
+
+
def test_checkout_add_payment_not_supported_gateways(
user_api_client, checkout_without_shipping_required, address
):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b3024ae56a..f3334ca969 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1025,7 +1025,7 @@ type Checkout implements Node & ObjectWithMetadata {
availableShippingMethods: [ShippingMethod]!
availableCollectionPoints: [Warehouse!]!
availablePaymentGateways: [PaymentGateway!]!
- email: String!
+ email: String
isShippingRequired: Boolean!
quantity: Int!
stockReservationExpires: DateTime
@@ -1144,6 +1144,7 @@ enum CheckoutErrorCode {
MISSING_CHANNEL_SLUG
CHANNEL_INACTIVE
UNAVAILABLE_VARIANT_IN_CHANNEL
+ EMAIL_NOT_SET
}
input CheckoutFilterInput {
@@ -4966,6 +4967,7 @@ enum PaymentErrorCode {
NOT_SUPPORTED_GATEWAY
CHANNEL_INACTIVE
BALANCE_CHECK_ERROR
+ CHECKOUT_EMAIL_NOT_SET
}
input PaymentFilterInput {
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index d00c755374..84f627a229 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -1,9 +1,8 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from ..product.models import ProductVariant
- from .models import FulfillmentLine, OrderLine
+ from .models import FulfillmentLine
class OrderStatus:
@@ -205,15 +204,6 @@ class OrderEventsEmails:
]
-@dataclass
-class OrderLineData:
- line: "OrderLine"
- quantity: int
- variant: Optional["ProductVariant"] = None
- replace: bool = False
- warehouse_pk: Optional[str] = None
-
-
@dataclass
class FulfillmentLineData:
line: "FulfillmentLine"
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 595b71fc27..3ceba77d53 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -33,7 +33,6 @@ from ..warehouse.models import Stock
from . import (
FulfillmentLineData,
FulfillmentStatus,
- OrderLineData,
OrderOrigin,
OrderStatus,
events,
@@ -47,6 +46,7 @@ from .events import (
order_replacement_created,
order_returned_event,
)
+from .fetch import OrderLineInfo
from .models import Fulfillment, FulfillmentLine, Order, OrderLine
from .notifications import (
send_fulfillment_confirmation_to_customer,
@@ -67,6 +67,7 @@ if TYPE_CHECKING:
from ..plugins.manager import PluginsManager
from ..site.models import SiteSettings
from ..warehouse.models import Warehouse
+ from .fetch import OrderInfo
logger = logging.getLogger(__name__)
@@ -76,19 +77,20 @@ QuantityType = int
def order_created(
- order: "Order",
+ order_info: "OrderInfo",
user: "User",
app: Optional["App"],
manager: "PluginsManager",
from_draft: bool = False,
):
+ order = order_info.order
events.order_created_event(order=order, user=user, app=app, from_draft=from_draft)
manager.order_created(order)
- payment = order.get_last_payment()
+ payment = order_info.payment
if payment:
if order.is_captured():
order_captured(
- order=order,
+ order_info=order_info,
user=user,
app=app,
amount=payment.total,
@@ -128,16 +130,16 @@ def order_confirmed(
def handle_fully_paid_order(
manager: "PluginsManager",
- order: "Order",
+ order_info: "OrderInfo",
user: Optional["User"] = None,
app: Optional["App"] = None,
):
+ order = order_info.order
events.order_fully_paid_event(order=order, user=user, app=app)
- if order.get_customer_email():
- send_payment_confirmation(order, manager)
-
- if utils.order_needs_automatic_fulfillment(order):
- automatically_fulfill_digital_lines(order, manager)
+ if order_info.customer_email:
+ send_payment_confirmation(order_info, manager)
+ if utils.order_needs_automatic_fulfillment(order_info.lines_data):
+ automatically_fulfill_digital_lines(order_info, manager)
try:
analytics.report_order(order.tracking_client_id, order)
except Exception:
@@ -289,19 +291,20 @@ def order_authorized(
def order_captured(
- order: "Order",
+ order_info: "OrderInfo",
user: Optional["User"],
app: Optional["App"],
amount: "Decimal",
payment: "Payment",
manager: "PluginsManager",
):
+ order = order_info.order
events.payment_captured_event(
order=order, user=user, app=app, amount=amount, payment=payment
)
manager.order_updated(order)
if order.is_fully_paid():
- handle_fully_paid_order(manager, order, user, app)
+ handle_fully_paid_order(manager, order_info, user, app)
def fulfillment_tracking_updated(
@@ -426,7 +429,7 @@ def approve_fulfillment(
warehouse_pk = stock.warehouse_id
lines_to_fulfill.append(
- OrderLineData(
+ OrderLineInfo(
line=order_line,
quantity=fulfillment_line.quantity,
variant=variant,
@@ -545,7 +548,7 @@ def _increase_order_line_quantity(order_lines_info):
@traced_atomic_transaction()
def fulfill_order_lines(
- order_lines_info: Iterable["OrderLineData"],
+ order_lines_info: Iterable["OrderLineInfo"],
manager: "PluginsManager",
allow_stock_to_be_exceeded: bool = False,
):
@@ -555,42 +558,40 @@ def fulfill_order_lines(
@traced_atomic_transaction()
-def automatically_fulfill_digital_lines(order: "Order", manager: "PluginsManager"):
+def automatically_fulfill_digital_lines(
+ order_info: "OrderInfo", manager: "PluginsManager"
+):
"""Fulfill all digital lines which have enabled automatic fulfillment setting.
Send confirmation email afterward.
"""
- digital_lines = order.lines.filter(
- is_shipping_required=False, variant__digital_content__isnull=False
- )
- digital_lines = digital_lines.prefetch_related("variant__digital_content")
-
- if not digital_lines:
+ order = order_info.order
+ digital_lines_data = [
+ line_data
+ for line_data in order_info.lines_data
+ if not line_data.line.is_shipping_required and line_data.digital_content
+ ]
+
+ if not digital_lines_data:
return
fulfillment, _ = Fulfillment.objects.get_or_create(order=order)
fulfillments = []
lines_info = []
- for line in digital_lines:
- if not order_line_needs_automatic_fulfillment(line):
+ for line_data in digital_lines_data:
+ if not order_line_needs_automatic_fulfillment(line_data):
continue
- variant = line.variant
- if variant:
- digital_content = variant.digital_content
+ digital_content = line_data.digital_content
+ line = line_data.line
+ if digital_content:
digital_content.urls.create(line=line)
- quantity = line.quantity
+ quantity = line_data.quantity
fulfillments.append(
FulfillmentLine(fulfillment=fulfillment, order_line=line, quantity=quantity)
)
- warehouse_pk = line.allocations.first().stock.warehouse.pk # type: ignore
- lines_info.append(
- OrderLineData(
- line=line,
- quantity=quantity,
- variant=line.variant,
- warehouse_pk=warehouse_pk,
- )
- )
+ allocation = line.allocations.first()
+ line_data.warehouse_pk = allocation.stock.warehouse.pk # type: ignore
+ lines_info.append(line_data)
FulfillmentLine.objects.bulk_create(fulfillments)
fulfill_order_lines(lines_info, manager)
@@ -675,15 +676,17 @@ def _create_fulfillment_lines(
insufficient_stocks.append(error_data)
continue
+ is_digital = order_line.is_digital
lines_info.append(
- OrderLineData(
+ OrderLineInfo(
line=order_line,
+ is_digital=is_digital,
quantity=quantity,
variant=variant,
warehouse_pk=warehouse_pk,
)
)
- if order_line.is_digital:
+ if is_digital:
variant.digital_content.urls.create(line=order_line)
fulfillment_line = FulfillmentLine(
order_line=order_line,
@@ -846,7 +849,7 @@ def _get_fulfillment_line(
@traced_atomic_transaction()
def _move_order_lines_to_target_fulfillment(
- order_lines_to_move: List[OrderLineData],
+ order_lines_to_move: List[OrderLineInfo],
target_fulfillment: Fulfillment,
manager: "PluginsManager",
) -> List[FulfillmentLine]:
@@ -854,7 +857,7 @@ def _move_order_lines_to_target_fulfillment(
fulfillment_lines_to_create: List[FulfillmentLine] = []
order_lines_to_update: List[OrderLine] = []
- lines_to_dellocate: List[OrderLineData] = []
+ lines_to_dellocate: List[OrderLineInfo] = []
for line_data in order_lines_to_move:
line_to_move = line_data.line
quantity_to_move = line_data.quantity
@@ -878,7 +881,7 @@ def _move_order_lines_to_target_fulfillment(
line_allocations_exists = line_to_move.allocations.exists()
if line_allocations_exists:
lines_to_dellocate.append(
- OrderLineData(line=line_to_move, quantity=unfulfilled_to_move)
+ OrderLineInfo(line=line_to_move, quantity=unfulfilled_to_move)
)
if lines_to_dellocate:
@@ -968,7 +971,7 @@ def create_refund_fulfillment(
app: Optional["App"],
order,
payment,
- order_lines_to_refund: List[OrderLineData],
+ order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
manager: "PluginsManager",
amount=None,
@@ -1064,7 +1067,7 @@ def create_replace_order(
user: Optional[User],
app: Optional["App"],
original_order: "Order",
- order_lines_to_replace: List[OrderLineData],
+ order_lines_to_replace: List[OrderLineInfo],
fulfillment_lines_to_replace: List[FulfillmentLineData],
) -> "Order":
"""Create draft order with lines to replace."""
@@ -1125,7 +1128,7 @@ def create_replace_order(
def _move_lines_to_return_fulfillment(
- order_lines: List[OrderLineData],
+ order_lines: List[OrderLineInfo],
fulfillment_lines: List[FulfillmentLineData],
fulfillment_status: str,
order: "Order",
@@ -1184,7 +1187,7 @@ def _move_lines_to_return_fulfillment(
def _move_lines_to_replace_fulfillment(
- order_lines_to_replace: List[OrderLineData],
+ order_lines_to_replace: List[OrderLineInfo],
fulfillment_lines_to_replace: List[FulfillmentLineData],
order: "Order",
manager: "PluginsManager",
@@ -1210,7 +1213,7 @@ def create_return_fulfillment(
user: Optional["User"],
app: Optional["App"],
order: "Order",
- order_lines: List[OrderLineData],
+ order_lines: List[OrderLineInfo],
fulfillment_lines: List[FulfillmentLineData],
total_refund_amount: Optional[Decimal],
shipping_refund_amount: Optional[Decimal],
@@ -1265,7 +1268,7 @@ def process_replace(
user: Optional["User"],
app: Optional["App"],
order: "Order",
- order_lines: List[OrderLineData],
+ order_lines: List[OrderLineInfo],
fulfillment_lines: List[FulfillmentLineData],
manager: "PluginsManager",
) -> Tuple[Fulfillment, Optional["Order"]]:
@@ -1310,7 +1313,7 @@ def create_fulfillments_for_returned_products(
app: Optional["App"],
order: "Order",
payment: Optional[Payment],
- order_lines: List[OrderLineData],
+ order_lines: List[OrderLineInfo],
fulfillment_lines: List[FulfillmentLineData],
manager: "PluginsManager",
refund: bool = False,
@@ -1396,7 +1399,7 @@ def create_fulfillments_for_returned_products(
def _calculate_refund_amount(
- return_order_lines: List[OrderLineData],
+ return_order_lines: List[OrderLineInfo],
return_fulfillment_lines: List[FulfillmentLineData],
lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]],
) -> Decimal:
@@ -1434,7 +1437,7 @@ def _process_refund(
app: Optional["App"],
order: "Order",
payment: Payment,
- order_lines_to_refund: List[OrderLineData],
+ order_lines_to_refund: List[OrderLineInfo],
fulfillment_lines_to_refund: List[FulfillmentLineData],
amount: Optional[Decimal],
refund_shipping_costs: bool,
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
new file mode 100644
index 0000000000..81a9004d75
--- /dev/null
+++ b/saleor/order/fetch.py
@@ -0,0 +1,61 @@
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Iterable, List, Optional
+
+if TYPE_CHECKING:
+ from ..channel.models import Channel
+ from ..payment.models import Payment
+ from ..product.models import DigitalContent, ProductVariant
+ from .models import Order, OrderLine
+
+
+@dataclass
+class OrderInfo:
+ order: "Order"
+ customer_email: "str"
+ channel: "Channel"
+ payment: "Payment"
+ lines_data: Iterable["OrderLineInfo"]
+
+
+@dataclass
+class OrderLineInfo:
+ line: "OrderLine"
+ quantity: int
+ variant: Optional["ProductVariant"] = None
+ is_digital: Optional[bool] = None
+ digital_content: Optional["DigitalContent"] = None
+ replace: bool = False
+ warehouse_pk: Optional[str] = None
+
+
+def fetch_order_info(order: "Order") -> OrderInfo:
+ order_lines_info = fetch_order_lines(order)
+ order_data = OrderInfo(
+ order=order,
+ customer_email=order.get_customer_email(),
+ channel=order.channel,
+ payment=order.get_last_payment(),
+ lines_data=order_lines_info,
+ )
+ return order_data
+
+
+def fetch_order_lines(order: "Order") -> List[OrderLineInfo]:
+ lines = order.lines.prefetch_related("variant__digital_content")
+ lines_info = []
+ for line in lines:
+ is_digital = line.is_digital
+ variant = line.variant
+ lines_info.append(
+ OrderLineInfo(
+ line=line,
+ quantity=line.quantity,
+ is_digital=is_digital,
+ variant=variant,
+ digital_content=variant.digital_content
+ if is_digital and variant
+ else None,
+ )
+ )
+
+ return lines_info
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index 202c4c9195..3b1927d53d 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -300,15 +300,17 @@ def prepare_order_details_url(order: Order, redirect_url: str) -> str:
return prepare_url(params, redirect_url)
-def send_order_confirmation(order, redirect_url, manager):
+def send_order_confirmation(order_info, redirect_url, manager):
"""Send notification with order confirmation."""
payload = {
- "order": get_default_order_payload(order, redirect_url),
- "recipient_email": order.get_customer_email(),
+ "order": get_default_order_payload(order_info.order, redirect_url),
+ "recipient_email": order_info.customer_email,
**get_site_context(),
}
manager.notify(
- NotifyEventType.ORDER_CONFIRMATION, payload, channel_slug=order.channel.slug
+ NotifyEventType.ORDER_CONFIRMATION,
+ payload,
+ channel_slug=order_info.channel.slug,
)
# Prepare staff notification for this order
@@ -359,13 +361,13 @@ def send_fulfillment_update(order, fulfillment, manager):
)
-def send_payment_confirmation(order, manager):
+def send_payment_confirmation(order_info, manager):
"""Send notification with the payment confirmation."""
- payment = order.get_last_payment()
+ payment = order_info.payment
payment_currency = payment.currency
payload = {
- "order": get_default_order_payload(order),
- "recipient_email": order.get_customer_email(),
+ "order": get_default_order_payload(order_info.order),
+ "recipient_email": order_info.customer_email,
"payment": {
"created": payment.created,
"modified": payment.modified,
@@ -381,7 +383,7 @@ def send_payment_confirmation(order, manager):
manager.notify(
NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
payload,
- channel_slug=order.channel.slug,
+ channel_slug=order_info.channel.slug,
)
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index 7a3ac6a70d..62dea38b85 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -9,6 +9,7 @@ from ...core.notify_events import NotifyEventType
from ...core.prices import quantize_price
from ...discount import DiscountValueType
from ...order import notifications
+from ...order.fetch import fetch_order_info
from ...plugins.manager import get_plugins_manager
from ...product.models import DigitalContentUrl
from ..notifications import (
@@ -305,6 +306,7 @@ def test_get_default_fulfillment_payload(
def test_send_email_payment_confirmation(mocked_notify, site_settings, payment_dummy):
manager = get_plugins_manager()
order = payment_dummy.order
+ order_info = fetch_order_info(order)
expected_payload = {
"order": get_default_order_payload(order),
"recipient_email": order.get_customer_email(),
@@ -319,7 +321,7 @@ def test_send_email_payment_confirmation(mocked_notify, site_settings, payment_d
"site_name": "mirumee.com",
"domain": "mirumee.com",
}
- notifications.send_payment_confirmation(order, manager)
+ notifications.send_payment_confirmation(order_info, manager)
mocked_notify.assert_called_once_with(
NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
expected_payload,
@@ -331,8 +333,9 @@ def test_send_email_payment_confirmation(mocked_notify, site_settings, payment_d
def test_send_email_order_confirmation(mocked_notify, order, site_settings):
manager = get_plugins_manager()
redirect_url = "https://www.example.com"
+ order_info = fetch_order_info(order)
- notifications.send_order_confirmation(order, redirect_url, manager)
+ notifications.send_order_confirmation(order_info, redirect_url, manager)
expected_payload = {
"order": get_default_order_payload(order, redirect_url),
@@ -353,10 +356,9 @@ def test_send_email_order_confirmation_for_cc(
):
manager = get_plugins_manager()
redirect_url = "https://www.example.com"
+ order_info = fetch_order_info(order_with_lines_for_cc)
- notifications.send_order_confirmation(
- order_with_lines_for_cc, redirect_url, manager
- )
+ notifications.send_order_confirmation(order_info, redirect_url, manager)
expected_payload = {
"order": get_default_order_payload(order_with_lines_for_cc, redirect_url),
@@ -397,8 +399,9 @@ def test_send_confirmation_emails_without_addresses_for_payment(
order.shipping_method = None
order.billing_address = None
order.save(update_fields=["shipping_address", "shipping_method", "billing_address"])
+ order_info = fetch_order_info(order)
- notifications.send_payment_confirmation(order, info.context.plugins)
+ notifications.send_payment_confirmation(order_info, info.context.plugins)
expected_payload = {
"order": get_default_order_payload(order),
@@ -443,10 +446,13 @@ def test_send_confirmation_emails_without_addresses_for_order(
order.shipping_method = None
order.billing_address = None
order.save(update_fields=["shipping_address", "shipping_method", "billing_address"])
+ order_info = fetch_order_info(order)
redirect_url = "https://www.example.com"
- notifications.send_order_confirmation(order, redirect_url, info.context.plugins)
+ notifications.send_order_confirmation(
+ order_info, redirect_url, info.context.plugins
+ )
expected_payload = {
"order": get_default_order_payload(order, redirect_url),
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 4f377725c1..1abde05fc2 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -4,7 +4,7 @@ from unittest.mock import patch
import pytest
from prices import Money, TaxedMoney
-from ...order import OrderLineData
+from ...order.fetch import OrderLineInfo, fetch_order_info
from ...payment import ChargeStatus, PaymentError, TransactionKind
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
@@ -87,15 +87,17 @@ def test_handle_fully_paid_order_digital_lines(
order = order_with_digital_line
order.redirect_url = redirect_url
order.save()
+ order_info = fetch_order_info(order)
manager = get_plugins_manager()
- handle_fully_paid_order(manager, order)
+
+ handle_fully_paid_order(manager, order_info)
fulfillment = order.fulfillments.first()
event_order_paid = order.events.get()
assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID
- mock_send_payment_confirmation.assert_called_once_with(order, manager)
+ mock_send_payment_confirmation.assert_called_once_with(order_info, manager)
send_fulfillment_confirmation_to_customer.assert_called_once_with(
order, fulfillment, user=order.user, app=None, manager=manager
)
@@ -109,12 +111,14 @@ def test_handle_fully_paid_order(mock_send_payment_confirmation, order):
manager = get_plugins_manager()
order.payments.add(Payment.objects.create())
- handle_fully_paid_order(manager, order)
- event_order_paid = order.events.get()
+ order_info = fetch_order_info(order)
+
+ handle_fully_paid_order(manager, order_info)
+ event_order_paid = order.events.get()
assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID
- mock_send_payment_confirmation.assert_called_once_with(order, manager)
+ mock_send_payment_confirmation.assert_called_once_with(order_info, manager)
@patch("saleor.order.notifications.send_payment_confirmation")
@@ -122,8 +126,9 @@ def test_handle_fully_paid_order_no_email(mock_send_payment_confirmation, order)
order.user = None
order.user_email = ""
manager = get_plugins_manager()
+ order_info = fetch_order_info(order)
- handle_fully_paid_order(manager, order)
+ handle_fully_paid_order(manager, order_info)
event = order.events.get()
assert event.type == OrderEvents.ORDER_FULLY_PAID
assert not mock_send_payment_confirmation.called
@@ -298,7 +303,7 @@ def test_fulfill_order_lines(order_with_lines):
fulfill_order_lines(
[
- OrderLineData(
+ OrderLineInfo(
line=line,
quantity=line.quantity,
variant=variant,
@@ -331,13 +336,13 @@ def test_fulfill_order_lines_multiple_lines(order_with_lines):
fulfill_order_lines(
[
- OrderLineData(
+ OrderLineInfo(
line=lines[0],
quantity=lines[0].quantity,
variant=variant_1,
warehouse_pk=stock_1.warehouse.pk,
),
- OrderLineData(
+ OrderLineInfo(
line=lines[1],
quantity=lines[1].quantity,
variant=variant_2,
@@ -367,7 +372,7 @@ def test_fulfill_order_lines_with_variant_deleted(order_with_lines):
line.refresh_from_db()
fulfill_order_lines(
- [OrderLineData(line=line, quantity=line.quantity)], get_plugins_manager()
+ [OrderLineInfo(line=line, quantity=line.quantity)], get_plugins_manager()
)
@@ -385,7 +390,7 @@ def test_fulfill_order_lines_without_inventory_tracking(order_with_lines):
fulfill_order_lines(
[
- OrderLineData(
+ OrderLineInfo(
line=line,
quantity=line.quantity,
variant=variant,
@@ -410,6 +415,12 @@ def test_fulfill_digital_lines(
image_file, image_name = create_image()
variant = line.variant
+
+ product_type = variant.product.product_type
+ product_type.is_digital = True
+ product_type.is_shipping_required = False
+ product_type.save(update_fields=["is_digital", "is_shipping_required"])
+
digital_content = DigitalContent.objects.create(
content_file=image_file, product_variant=variant, use_default_settings=True
)
@@ -419,9 +430,10 @@ def test_fulfill_digital_lines(
line.save()
order_with_lines.refresh_from_db()
+ order_info = fetch_order_info(order_with_lines)
manager = get_plugins_manager()
- automatically_fulfill_digital_lines(order_with_lines, manager)
+ automatically_fulfill_digital_lines(order_info, manager)
line.refresh_from_db()
fulfillment = Fulfillment.objects.get(order=order_with_lines)
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index bf68554073..c9615b9646 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -6,14 +6,9 @@ from prices import Money, TaxedMoney
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation, Stock
-from .. import (
- FulfillmentLineData,
- FulfillmentStatus,
- OrderEvents,
- OrderLineData,
- OrderOrigin,
-)
+from .. import FulfillmentLineData, FulfillmentStatus, OrderEvents, OrderOrigin
from ..actions import create_fulfillments_for_returned_products
+from ..fetch import OrderLineInfo
from ..models import Fulfillment, FulfillmentLine
@@ -45,7 +40,7 @@ def test_create_return_fulfillment_only_order_lines(
order=order_with_lines,
payment=payment,
order_lines=[
- OrderLineData(line=line, quantity=2, replace=False)
+ OrderLineInfo(line=line, quantity=2, replace=False)
for line in order_lines_to_return
],
fulfillment_lines=[],
@@ -119,7 +114,7 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
order=order_with_lines,
payment=payment,
order_lines=[
- OrderLineData(line=line, quantity=2, replace=False)
+ OrderLineInfo(line=line, quantity=2, replace=False)
for line in order_lines_to_return
],
fulfillment_lines=[],
@@ -191,7 +186,7 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
order=order_with_lines,
payment=payment,
order_lines=[
- OrderLineData(line=line, quantity=2, replace=False)
+ OrderLineInfo(line=line, quantity=2, replace=False)
for line in order_lines_to_return
],
fulfillment_lines=[],
@@ -263,7 +258,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(
lines_count = order_with_lines.lines.count()
quantity_to_replace = 2
order_lines_data = [
- OrderLineData(line=line, quantity=2, replace=False)
+ OrderLineInfo(line=line, quantity=2, replace=False)
for line in order_lines_to_return
]
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index 6710871400..f5ea1c0d20 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -5,8 +5,9 @@ from ...payment import ChargeStatus
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation
-from .. import FulfillmentLineData, FulfillmentStatus, OrderLineData
+from .. import FulfillmentLineData, FulfillmentStatus
from ..actions import create_refund_fulfillment
+from ..fetch import OrderLineInfo
from ..models import FulfillmentLine
@@ -37,7 +38,7 @@ def test_create_refund_fulfillment_only_order_lines(
order=order_with_lines,
payment=payment,
order_lines_to_refund=[
- OrderLineData(line=line, quantity=2) for line in order_lines_to_refund
+ OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
],
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
@@ -96,7 +97,7 @@ def test_create_refund_fulfillment_included_shipping_costs(
order=order_with_lines,
payment=payment,
order_lines_to_refund=[
- OrderLineData(line=line, quantity=2) for line in order_lines_to_refund
+ OrderLineInfo(line=line, quantity=2) for line in order_lines_to_refund
],
fulfillment_lines_to_refund=[],
manager=get_plugins_manager(),
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 583d28e762..adbe5b8931 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -10,8 +10,9 @@ from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
from ...order.interface import OrderTaxedPricesData
from ...plugins.manager import get_plugins_manager
-from .. import OrderLineData, OrderStatus
+from .. import OrderStatus
from ..events import OrderEvents
+from ..fetch import OrderLineInfo
from ..models import Order, OrderEvent
from ..utils import (
add_gift_cards_to_order,
@@ -48,7 +49,7 @@ def test_change_quantity_generates_proper_event(
line = order_with_lines.lines.last()
line.quantity = previous_quantity
- line_info = OrderLineData(
+ line_info = OrderLineInfo(
line=line,
quantity=line.quantity,
variant=line.variant,
@@ -96,7 +97,7 @@ def test_change_quantity_update_line_fields(
):
# given
line = order_with_lines.lines.last()
- line_info = OrderLineData(
+ line_info = OrderLineInfo(
line=line,
quantity=line.quantity,
variant=line.variant,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 926c8daf2f..7290944947 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,7 +1,7 @@
import copy
from decimal import Decimal
from functools import partial, wraps
-from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union, cast
import graphene
from django.conf import settings
@@ -21,7 +21,8 @@ from ..discount.utils import (
)
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
-from ..order import FulfillmentStatus, OrderLineData, OrderStatus
+from ..order import FulfillmentStatus, OrderStatus
+from ..order.fetch import OrderLineInfo
from ..order.models import Order, OrderLine
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.models import ShippingMethod
@@ -51,11 +52,11 @@ def get_order_country(order: Order) -> str:
return address.country.code
-def order_line_needs_automatic_fulfillment(line: OrderLine) -> bool:
+def order_line_needs_automatic_fulfillment(line_data: OrderLineInfo) -> bool:
"""Check if given line is digital and should be automatically fulfilled."""
digital_content_settings = get_default_digital_content_settings()
default_automatic_fulfillment = digital_content_settings["automatic_fulfillment"]
- content = line.variant.digital_content if line.variant else None
+ content = line_data.digital_content
if not content:
return False
if default_automatic_fulfillment and content.use_default_settings:
@@ -65,10 +66,10 @@ def order_line_needs_automatic_fulfillment(line: OrderLine) -> bool:
return False
-def order_needs_automatic_fulfillment(order: Order) -> bool:
+def order_needs_automatic_fulfillment(lines_data: Iterable["OrderLineInfo"]) -> bool:
"""Check if order has digital products which should be automatically fulfilled."""
- for line in order.lines.digital(): # type: ignore
- if order_line_needs_automatic_fulfillment(line):
+ for line_data in lines_data:
+ if line_data.is_digital and order_line_needs_automatic_fulfillment(line_data):
return True
return False
@@ -286,7 +287,6 @@ def _calculate_quantity_including_returns(order):
def update_order_status(order):
"""Update order status depending on fulfillments."""
-
(
total_quantity,
quantity_fulfilled,
@@ -339,7 +339,7 @@ def add_variant_to_order(
line = order.lines.get(variant=variant)
old_quantity = line.quantity
new_quantity = old_quantity + quantity
- line_info = OrderLineData(line=line, quantity=old_quantity)
+ line_info = OrderLineInfo(line=line, quantity=old_quantity)
change_order_line_quantity(
user,
app,
@@ -456,7 +456,7 @@ def add_variant_to_order(
if allocate_stock:
increase_allocations(
[
- OrderLineData(
+ OrderLineInfo(
line=line,
quantity=quantity,
variant=variant,
@@ -481,7 +481,7 @@ def add_gift_cards_to_order(
gift_cards_to_update = []
balance_data: List[Tuple[GiftCard, float]] = []
used_by_user = checkout_info.user
- used_by_email = checkout_info.get_customer_email()
+ used_by_email = cast(str, checkout_info.get_customer_email())
for gift_card in checkout_info.checkout.gift_cards.select_for_update():
if total_price_left > zero_money(total_price_left.currency):
order_gift_cards.append(gift_card)
@@ -535,7 +535,7 @@ def set_gift_card_user(
def _update_allocations_for_line(
- line_info: OrderLineData,
+ line_info: OrderLineInfo,
old_quantity: int,
new_quantity: int,
channel_slug: str,
@@ -637,12 +637,12 @@ def restock_order_lines(order, manager):
shipping_zones__countries__contains=country
).first()
- dellocating_stock_lines: List[OrderLineData] = []
+ dellocating_stock_lines: List[OrderLineInfo] = []
for line in order.lines.all():
if line.variant and line.variant.track_inventory:
if line.quantity_unfulfilled > 0:
dellocating_stock_lines.append(
- OrderLineData(line=line, quantity=line.quantity_unfulfilled)
+ OrderLineInfo(line=line, quantity=line.quantity_unfulfilled)
)
if line.quantity_fulfilled > 0:
allocation = line.allocations.first()
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index 829f05993f..d11bbbbcd3 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -16,3 +16,4 @@ class PaymentErrorCode(Enum):
NOT_SUPPORTED_GATEWAY = "not_supported_gateway"
CHANNEL_INACTIVE = "channel_inactive"
BALANCE_CHECK_ERROR = "balance_check_error"
+ CHECKOUT_EMAIL_NOT_SET = "checkout_email_not_set"
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 7f0916d92c..d00c376068 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -37,6 +37,7 @@ from ....order.actions import (
order_refunded,
)
from ....order.events import external_notification_event
+from ....order.fetch import fetch_order_info
from ....payment.models import Payment, Transaction
from ....plugins.manager import get_plugins_manager
from ... import ChargeStatus, PaymentError, TransactionKind, gateway
@@ -259,8 +260,9 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
if new_transaction.is_success:
gateway_postprocess(new_transaction, payment)
if adyen_auto_capture:
+ order_info = fetch_order_info(payment.order)
order_captured(
- payment.order,
+ order_info,
None,
None,
new_transaction.amount,
@@ -357,8 +359,9 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
)
if new_transaction.is_success and not capture_transaction:
gateway_postprocess(new_transaction, payment)
+ order_info = fetch_order_info(payment.order)
order_captured(
- payment.order, None, None, new_transaction.amount, payment, manager
+ order_info, None, None, new_transaction.amount, payment, manager
)
reason = notification.get("reason", "-")
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index 3aca6697c3..61c24c29ad 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -15,6 +15,7 @@ from ....checkout.models import Checkout
from ....core.transactions import transaction_with_commit_on_errors
from ....discount.utils import fetch_active_discounts
from ....order.actions import order_captured, order_refunded, order_voided
+from ....order.fetch import fetch_order_info
from ....order.models import Order
from ....plugins.manager import get_plugins_manager
from ... import ChargeStatus, TransactionKind
@@ -373,8 +374,9 @@ def handle_successful_payment_intent(
payment_intent.amount_received,
payment_intent.currency,
)
+ order_info = fetch_order_info(payment.order) # type: ignore
order_captured(
- payment.order, # type: ignore
+ order_info,
None,
None,
capture_transaction.amount,
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 05b61a26b7..b42be75bd3 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,7 +1,7 @@
import json
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, List, Optional
+from typing import TYPE_CHECKING, Dict, List, Optional, cast
import graphene
from babel.numbers import get_currency_precision
@@ -55,7 +55,7 @@ def create_payment_information(
if checkout := payment.checkout:
billing = checkout.billing_address
shipping = checkout.shipping_address
- email = checkout.get_customer_email()
+ email = cast(str, checkout.get_customer_email())
user_id = checkout.user_id
checkout_token = str(checkout.token)
checkout_metadata = checkout.metadata
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index fc59e55086..748fdad51a 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -3,7 +3,7 @@ import logging
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union, cast
from urllib.parse import urljoin
import opentracing
@@ -439,12 +439,13 @@ def generate_request_data_from_checkout(
lines = get_checkout_lines_data(checkout_info, lines_info, config, discounts)
currency = checkout_info.checkout.currency
+ customer_email = cast(str, checkout_info.get_customer_email())
data = generate_request_data(
transaction_type=transaction_type,
lines=lines,
transaction_token=transaction_token or str(checkout_info.checkout.token),
address=address.as_data() if address else {},
- customer_email=checkout_info.get_customer_email(),
+ customer_email=customer_email,
config=config,
currency=currency,
)
diff --git a/saleor/settings.py b/saleor/settings.py
index f1ff119670..05801fdd23 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -11,6 +11,7 @@ import jaeger_client.config
import pkg_resources
import sentry_sdk
import sentry_sdk.utils
+from celery.schedules import crontab
from django.core.exceptions import ImproperlyConfigured
from django.core.management.utils import get_random_secret_key
from graphql.utils import schema_printer
@@ -468,6 +469,17 @@ AUTHENTICATION_BACKENDS = [
"saleor.core.auth_backend.PluginBackend",
]
+# Expired checkouts settings - defines after what time checkouts will be deleted
+ANONYMOUS_CHECKOUTS_TIMEDELTA = timedelta(
+ seconds=parse(os.environ.get("ANONYMOUS_CHECKOUTS_TIMEDELTA", "30 days"))
+)
+USER_CHECKOUTS_TIMEDELTA = timedelta(
+ seconds=parse(os.environ.get("USER_CHECKOUTS_TIMEDELTA", "90 days"))
+)
+EMPTY_CHECKOUTS_TIMEDELTA = timedelta(
+ seconds=parse(os.environ.get("EMPTY_CHECKOUTS_TIMEDELTA", "6 hours"))
+)
+
# CELERY SETTINGS
CELERY_TIMEZONE = TIME_ZONE
CELERY_BROKER_URL = (
@@ -492,6 +504,10 @@ CELERY_BEAT_SCHEDULE = {
"task": "saleor.warehouse.tasks.delete_expired_reservations_task",
"schedule": timedelta(days=1),
},
+ "delete-expired-checkouts": {
+ "task": "saleor.checkout.tasks.delete_expired_checkouts",
+ "schedule": crontab(hour=0, minute=0),
+ },
}
# Change this value if your application is running behind a proxy,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 17ca3165a3..d263f091ed 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -59,13 +59,14 @@ from ..discount.models import (
from ..giftcard import GiftCardEvents
from ..giftcard.models import GiftCard, GiftCardEvent
from ..menu.models import Menu, MenuItem, MenuItemTranslation
-from ..order import OrderLineData, OrderOrigin, OrderStatus
+from ..order import OrderOrigin, OrderStatus
from ..order.actions import cancel_fulfillment, fulfill_order_lines
from ..order.events import (
OrderEvents,
fulfillment_refunded_event,
order_added_products_event,
)
+from ..order.fetch import OrderLineInfo
from ..order.models import (
FulfillmentLine,
FulfillmentStatus,
@@ -283,7 +284,7 @@ def site_settings_with_reservations(site_settings):
@pytest.fixture
def checkout(db, channel_USD):
checkout = Checkout.objects.create(
- currency=channel_USD.currency_code, channel=channel_USD
+ currency=channel_USD.currency_code, channel=channel_USD, email="[email protected]"
)
checkout.set_country("US", commit=True)
return checkout
@@ -683,6 +684,7 @@ def user_checkout(customer_user, channel_USD):
def user_checkout_for_cc(customer_user, channel_USD, warehouse_for_cc):
checkout = Checkout.objects.create(
user=customer_user,
+ email=customer_user.email,
channel=channel_USD,
billing_address=customer_user.default_billing_address,
shipping_address=warehouse_for_cc.address,
@@ -3511,7 +3513,7 @@ def order_fulfill_data(order_with_lines, warehouse):
@pytest.fixture
def lines_info(order_with_lines):
return [
- OrderLineData(
+ OrderLineInfo(
line=line,
quantity=line.quantity,
variant=line.variant,
@@ -3818,10 +3820,10 @@ def fulfilled_order(order_with_lines):
fulfillment.lines.create(order_line=line_2, quantity=line_2.quantity, stock=stock_2)
fulfill_order_lines(
[
- OrderLineData(
+ OrderLineInfo(
line=line_1, quantity=line_1.quantity, warehouse_pk=warehouse_1_pk
),
- OrderLineData(
+ OrderLineInfo(
line=line_2, quantity=line_2.quantity, warehouse_pk=warehouse_2_pk
),
],
@@ -3843,7 +3845,7 @@ def fulfilled_order_without_inventory_tracking(
warehouse_pk = stock.warehouse.pk
fulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)
fulfill_order_lines(
- [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
+ [OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
get_plugins_manager(),
)
order.status = OrderStatus.FULFILLED
@@ -5250,6 +5252,7 @@ def checkout_for_cc(channel_USD, customer_user, product_variant_list):
shipping_address=customer_user.default_shipping_address,
note="Test notes",
currency="USD",
+ email=customer_user.email,
)
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 4299318e49..9fb286f717 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -13,7 +13,7 @@ from ..core.exceptions import (
PreorderAllocationError,
)
from ..core.tracing import traced_atomic_transaction
-from ..order import OrderLineData
+from ..order.fetch import OrderLineInfo
from ..plugins.manager import PluginsManager
from ..product.models import ProductVariant, ProductVariantChannelListing
from .models import (
@@ -34,7 +34,7 @@ StockData = namedtuple("StockData", ["pk", "quantity"])
@traced_atomic_transaction()
def allocate_stocks(
- order_lines_info: Iterable["OrderLineData"],
+ order_lines_info: Iterable["OrderLineInfo"],
country_code: str,
channel_slug: str,
manager: PluginsManager,
@@ -144,7 +144,7 @@ def allocate_stocks(
def _create_allocations(
- line_info: "OrderLineData",
+ line_info: "OrderLineInfo",
stocks: List[StockData],
stocks_allocations: dict,
stocks_reservations: dict,
@@ -185,7 +185,7 @@ def _create_allocations(
@traced_atomic_transaction()
def deallocate_stock(
- order_lines_data: Iterable["OrderLineData"], manager: PluginsManager
+ order_lines_data: Iterable["OrderLineInfo"], manager: PluginsManager
):
"""Deallocate stocks for given `order_lines`.
@@ -301,7 +301,7 @@ def increase_stock(
@traced_atomic_transaction()
def increase_allocations(
- lines_info: Iterable["OrderLineData"], channel_slug: str, manager: PluginsManager
+ lines_info: Iterable["OrderLineInfo"], channel_slug: str, manager: PluginsManager
):
"""Increase allocation for order lines with appropriate quantity."""
line_pks = [info.line.pk for info in lines_info]
@@ -332,7 +332,7 @@ def increase_allocations(
)
-def decrease_allocations(lines_info: Iterable["OrderLineData"], manager):
+def decrease_allocations(lines_info: Iterable["OrderLineInfo"], manager):
"""Decreate allocations for provided order lines."""
tracked_lines = get_order_lines_with_track_inventory(lines_info)
if not tracked_lines:
@@ -342,7 +342,7 @@ def decrease_allocations(lines_info: Iterable["OrderLineData"], manager):
@traced_atomic_transaction()
def decrease_stock(
- order_lines_info: Iterable["OrderLineData"],
+ order_lines_info: Iterable["OrderLineInfo"],
manager,
update_stocks=True,
allow_stock_to_be_exceeded: bool = False,
@@ -414,7 +414,7 @@ def decrease_stock(
def _decrease_stocks_quantity(
- order_lines_info: Iterable["OrderLineData"],
+ order_lines_info: Iterable["OrderLineInfo"],
variant_and_warehouse_to_stock: Dict[int, Dict[str, Stock]],
quantity_allocation_for_stocks: Dict[int, int],
allow_stock_to_be_exceeded: bool = False,
@@ -460,8 +460,8 @@ def _decrease_stocks_quantity(
def get_order_lines_with_track_inventory(
- order_lines_info: Iterable["OrderLineData"],
-) -> Iterable["OrderLineData"]:
+ order_lines_info: Iterable["OrderLineInfo"],
+) -> Iterable["OrderLineInfo"]:
"""Return order lines with variants with track inventory set to True."""
return [
line_info
@@ -490,7 +490,7 @@ def deallocate_stock_for_order(order: "Order", manager: PluginsManager):
@traced_atomic_transaction()
def allocate_preorders(
- order_lines_info: Iterable["OrderLineData"],
+ order_lines_info: Iterable["OrderLineInfo"],
channel_slug: str,
check_reservations: bool = False,
checkout_lines: Optional[Iterable["CheckoutLine"]] = None,
@@ -591,8 +591,8 @@ def allocate_preorders(
def get_order_lines_with_preorder(
- order_lines_info: Iterable["OrderLineData"],
-) -> Iterable["OrderLineData"]:
+ order_lines_info: Iterable["OrderLineInfo"],
+) -> Iterable["OrderLineInfo"]:
"""Return order lines with variants with preorder flag set to True."""
return [
line_info
@@ -602,7 +602,7 @@ def get_order_lines_with_preorder(
def _create_preorder_allocation(
- line_info: "OrderLineData",
+ line_info: "OrderLineInfo",
variant_channel_data: Tuple[int, Optional[int]],
variant_global_allocation: int,
variants_channel_listings: List[int],
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 1bfb715686..fff706a626 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -5,7 +5,7 @@ from django.db.models import Sum
from django.db.models.functions import Coalesce
from ...core.exceptions import InsufficientStock
-from ...order import OrderLineData
+from ...order.fetch import OrderLineInfo
from ...order.models import OrderLine
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
@@ -28,7 +28,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):
stock.quantity = 100
stock.save(update_fields=["quantity"])
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=50)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
@@ -58,10 +58,10 @@ def test_allocate_stocks_multiple_lines(order_line, order, product, stock, chann
quantity_1 = 50
quantity_2 = 5
- line_data_1 = OrderLineData(
+ line_data_1 = OrderLineInfo(
line=order_line, variant=order_line.variant, quantity=quantity_1
)
- line_data_2 = OrderLineData(
+ line_data_2 = OrderLineInfo(
line=order_line_2, variant=variant_2, quantity=quantity_2
)
@@ -86,7 +86,7 @@ def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channe
variant = variant_with_many_stocks
stocks = variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=5)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=5)
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
)
@@ -105,7 +105,7 @@ def test_allocate_stock_with_reservations(
variant = variant_with_many_stocks
stocks = variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=3)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=3)
allocate_stocks(
[line_data],
COUNTRY_CODE,
@@ -128,7 +128,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations(
variant = variant_with_many_stocks
variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=5)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=5)
with pytest.raises(InsufficientStock):
allocate_stocks(
@@ -152,7 +152,7 @@ def test_allocate_stock_many_stocks_partially_allocated(
variant = allocated_line.variant
stocks = variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=3)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=3)
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
)
@@ -169,7 +169,7 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(
variant = allocated_line.variant
stocks = variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=6)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=6)
with pytest.raises(InsufficientStock):
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
@@ -186,7 +186,7 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_US
stock.quantity = 100
stock.save(update_fields=["quantity"])
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=50)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)
with pytest.raises(InsufficientStock):
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
@@ -199,7 +199,7 @@ def test_allocate_stock_insufficient_stocks(
variant = variant_with_many_stocks
stocks = variant.stocks.all()
- line_data = OrderLineData(line=order_line, variant=order_line.variant, quantity=10)
+ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=10)
with pytest.raises(InsufficientStock):
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
@@ -228,10 +228,10 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines(
quantity_1 = 100
quantity_2 = 100
- line_data_1 = OrderLineData(
+ line_data_1 = OrderLineInfo(
line=order_line, variant=order_line.variant, quantity=quantity_1
)
- line_data_2 = OrderLineData(
+ line_data_2 = OrderLineInfo(
line=order_line_2, variant=variant_2, quantity=quantity_2
)
@@ -259,7 +259,7 @@ def test_deallocate_stock(allocation):
deallocate_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line, quantity=80, variant=stock.product_variant
)
],
@@ -281,7 +281,7 @@ def test_deallocate_stock_when_quantity_less_than_zero(allocation):
deallocate_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line, quantity=80, variant=stock.product_variant
)
],
@@ -303,7 +303,7 @@ def test_deallocate_stock_partially(allocation):
deallocate_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line, quantity=50, variant=stock.product_variant
)
],
@@ -322,7 +322,7 @@ def test_deallocate_stock_many_allocations(
order_line = order_line_with_allocation_in_many_stocks
deallocate_stock(
- [OrderLineData(line=order_line, quantity=3, variant=order_line.variant)],
+ [OrderLineInfo(line=order_line, quantity=3, variant=order_line.variant)],
manager=get_plugins_manager(),
)
@@ -337,7 +337,7 @@ def test_deallocate_stock_many_allocations_partially(
order_line = order_line_with_allocation_in_many_stocks
deallocate_stock(
- [OrderLineData(line=order_line, quantity=1, variant=order_line.variant)],
+ [OrderLineInfo(line=order_line, quantity=1, variant=order_line.variant)],
manager=get_plugins_manager(),
)
@@ -392,7 +392,7 @@ def test_increase_stock_with_new_allocation(order_line, stock):
@pytest.mark.parametrize("quantity", (19, 20))
def test_increase_allocations(quantity, allocation):
order_line = allocation.order_line
- order_line_info = OrderLineData(
+ order_line_info = OrderLineInfo(
line=order_line,
quantity=quantity,
variant=order_line.variant,
@@ -421,7 +421,7 @@ def test_increase_allocations(quantity, allocation):
def test_increase_allocation_insufficient_stock(allocation):
order_line = allocation.order_line
- order_line_info = OrderLineData(
+ order_line_info = OrderLineInfo(
line=order_line,
quantity=21,
variant=order_line.variant,
@@ -477,7 +477,7 @@ def test_decrease_stock(allocation):
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line,
quantity=50,
variant=stock.product_variant,
@@ -504,7 +504,7 @@ def test_decrease_stock_without_stock_update(quantity, expected_allocated, alloc
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line,
quantity=quantity,
variant=stock.product_variant,
@@ -538,13 +538,13 @@ def test_decrease_stock_multiple_lines(allocations):
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation_1.order_line,
quantity=50,
variant=allocation_1.order_line.variant,
warehouse_pk=warehouse_pk_1,
),
- OrderLineData(
+ OrderLineInfo(
line=allocation_2.order_line,
quantity=20,
variant=allocation_2.order_line.variant,
@@ -570,7 +570,7 @@ def test_decrease_stock_partially(allocation):
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line,
quantity=80,
variant=stock.product_variant,
@@ -595,7 +595,7 @@ def test_decrease_stock_many_allocations(
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=order_line,
quantity=3,
variant=order_line.variant,
@@ -620,7 +620,7 @@ def test_decrease_stock_many_allocations_partially(
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=order_line,
quantity=2,
variant=order_line.variant,
@@ -649,7 +649,7 @@ def test_decrease_stock_more_then_allocated(
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=order_line,
quantity=4,
variant=order_line.variant,
@@ -677,7 +677,7 @@ def test_decrease_stock_insufficient_stock(allocation):
with pytest.raises(InsufficientStock):
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line,
quantity=50,
variant=stock.product_variant,
@@ -753,7 +753,7 @@ def test_decrease_stock_with_out_of_stock_webhook_triggered(
decrease_stock(
[
- OrderLineData(
+ OrderLineInfo(
line=allocation.order_line,
quantity=50,
variant=stock.product_variant,
@@ -776,7 +776,7 @@ def test_allocate_preorders(
channel_listing.preorder_quantity_threshold = 100
channel_listing.save(update_fields=["preorder_quantity_threshold"])
- line_data = OrderLineData(line=order_line, variant=variant, quantity=50)
+ line_data = OrderLineInfo(line=order_line, variant=variant, quantity=50)
allocate_preorders([line_data], channel_USD.slug)
@@ -801,7 +801,7 @@ def test_allocate_preorders_with_allocation(
channel_listing.save(update_fields=["preorder_quantity_threshold"])
quantity_to_allocate = 2
- line_data = OrderLineData(
+ line_data = OrderLineInfo(
line=order_line, variant=variant, quantity=quantity_to_allocate
)
@@ -823,7 +823,7 @@ def test_allocate_preorders_insufficient_stocks_channel_threshold(
channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
channel_listings = variant.channel_listings.all()
- line_data = OrderLineData(
+ line_data = OrderLineInfo(
line=order_line,
variant=variant,
quantity=channel_listing.preorder_quantity_threshold + 1,
@@ -851,7 +851,7 @@ def test_allocate_preorders_insufficient_stocks_global_threshold(
)
available_preorder_quantity = variant.preorder_global_threshold - global_allocation
- line_data = OrderLineData(
+ line_data = OrderLineInfo(
line=order_line,
variant=variant,
quantity=available_preorder_quantity + 1,
@@ -873,7 +873,7 @@ def test_allocate_preorders_with_channel_reservations(
channel_listing.preorder_quantity_threshold = 5
channel_listing.save(update_fields=["preorder_quantity_threshold"])
- line_data = OrderLineData(line=order_line, variant=variant, quantity=5)
+ line_data = OrderLineInfo(line=order_line, variant=variant, quantity=5)
with pytest.raises(InsufficientStock):
allocate_preorders(
@@ -899,7 +899,7 @@ def test_allocate_preorders_with_global_reservations(
variant.preorder_global_threshold = 5
variant.save()
- line_data = OrderLineData(line=order_line, variant=variant, quantity=5)
+ line_data = OrderLineInfo(line=order_line, variant=variant, quantity=5)
with pytest.raises(InsufficientStock):
allocate_preorders(
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 474b7cab8b..0bf128e8a6 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -14,8 +14,9 @@ from ... import __version__
from ...core.utils.json_serializer import CustomJsonEncoder
from ...discount import DiscountValueType, OrderDiscountType
from ...graphql.utils import get_user_or_app_from_context
-from ...order import OrderLineData, OrderOrigin
+from ...order import OrderOrigin
from ...order.actions import fulfill_order_lines
+from ...order.fetch import OrderLineInfo
from ...order.models import Order
from ...plugins.manager import get_plugins_manager
from ...plugins.webhook.utils import from_payment_app_id
@@ -144,7 +145,7 @@ def test_generate_fulfillment_lines_payload(order_with_lines):
order_line=line, quantity=line.quantity, stock=stock
)
fulfill_order_lines(
- [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
+ [OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
get_plugins_manager(),
)
payload = json.loads(generate_fulfillment_lines_payload(fulfillment))[0]
@@ -192,7 +193,7 @@ def test_generate_fulfillment_lines_payload_deleted_variant(order_with_lines):
warehouse_pk = stock.warehouse.pk
fulfillment.lines.create(order_line=line, quantity=line.quantity, stock=stock)
fulfill_order_lines(
- [OrderLineData(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
+ [OrderLineInfo(line=line, quantity=line.quantity, warehouse_pk=warehouse_pk)],
get_plugins_manager(),
)