Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove double check of stock and prevent creating lines when unneeded
NyanKiyoshi9171616062a4
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex e0b5502071..48a72a3f2a 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1,6 +1,7 @@"""Checkout-related utility functions."""from datetime import date, timedeltafrom functools import wraps+from typing import Optional, Tuplefrom uuid import UUIDfrom django.contrib import messages@@ -254,19 +255,28 @@ def get_or_create_anonymous_checkout_from_token()[0]-def get_or_create_user_checkout(user: User, checkout_queryset=Checkout.objects.all()):+def get_user_checkout(+ user: User, checkout_queryset=Checkout.objects.all()+) -> Optional[Checkout]:+ """Return an open checkout for given user or None."""+ return checkout_queryset.filter(user=user).first()+++def get_or_create_user_checkout(+ user: User, checkout_queryset=Checkout.objects.all()+) -> Tuple[Checkout, bool]:"""Return an open checkout for given user or create a new one."""defaults = {"shipping_address": user.default_shipping_address,"billing_address": user.default_billing_address,}- created = False- checkout = checkout_queryset.filter(user=user).first()+ checkout = get_user_checkout(user, checkout_queryset=checkout_queryset)+if checkout is None:checkout = Checkout.objects.create(user=user, **defaults)- created = True- return checkout, created+ return checkout, True+ return checkout, Falsedef get_anonymous_checkout_from_token(token, checkout_queryset=Checkout.objects.all()):@@ -274,11 +284,6 @@ def get_anonymous_checkout_from_token(token, checkout_queryset=Checkout.objects.return checkout_queryset.filter(token=token, user=None).first()-def get_user_checkout(user, checkout_queryset=Checkout.objects.all()):- """Return an open checkout for given user if any."""- return checkout_queryset.filter(user=user).first()--def get_or_create_checkout_from_request(request, checkout_queryset=Checkout.objects.all()):@@ -360,39 +365,67 @@ def update_checkout_quantity(checkout):checkout.save(update_fields=["quantity"])-def add_variant_to_checkout(+def check_variant_in_stock(checkout, variant, quantity=1, replace=False, check_quantity=True-):- """Add a product variant to checkout.+) -> Tuple[int, Optional[CheckoutLine]]:+ """Check if a given variant is in stock and return the new quantity + line"""+ line = checkout.lines.filter(variant=variant).first()+ line_quantity = 0 if line is None else line.quantity- The `data` parameter may be used to differentiate between items with- different customization options.-- If `replace` is truthy then any previous quantity is discarded instead- of added to.- """- line, _ = checkout.lines.get_or_create(- variant=variant, defaults={"quantity": 0, "data": {}}- )- new_quantity = quantity if replace else (quantity + line.quantity)+ new_quantity = quantity if replace else (quantity + line_quantity)if new_quantity < 0:raise ValueError("%r is not a valid quantity (results in %r)" % (quantity, new_quantity))+ if new_quantity > 0 and check_quantity:+ variant.check_quantity(new_quantity)++ return new_quantity, line+++def update_or_create_checkout_line(+ checkout, variant, new_quantity, line: CheckoutLine = None+):+ """Updates the quantity of a given checkout line to a given quantity.+ If the line doesn't exist, it will be created."""++ if line is None:+ line = checkout.lines.filter(variant=variant).first()+if new_quantity == 0:- line.delete()+ if line is not None:+ line.delete()+ elif line is None:+ checkout.lines.create(checkout=checkout, variant=variant, quantity=new_quantity)else:- if check_quantity:- variant.check_quantity(new_quantity)-line.quantity = new_quantityline.save(update_fields=["quantity"])update_checkout_quantity(checkout)+def add_variant_to_checkout(+ checkout, variant, quantity=1, replace=False, check_quantity=True+):+ """Add a product variant to checkout.++ If `replace` is truthy then any previous quantity is discarded instead+ of added to.+ """++ new_quantity, line = check_variant_in_stock(+ checkout,+ variant,+ quantity=quantity,+ replace=replace,+ check_quantity=check_quantity,+ )++ update_or_create_checkout_line(checkout, variant, new_quantity, line=line)++def get_shipping_address_forms(checkout, user_addresses, data, country):"""Forms initialized with data depending on shipping address in checkout."""shipping_address = (diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex ee40cde5a4..b06d7f4cdf 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -16,12 +16,13 @@ from ...checkout.utils import (change_shipping_address_in_checkout,clean_checkout,create_order,- get_or_create_user_checkout,+ get_user_checkout,get_voucher_for_checkout,prepare_order_data,recalculate_checkout_discount,remove_promo_code_from_checkout,remove_voucher_from_checkout,+ update_or_create_checkout_line,)from ...core import analyticsfrom ...core.exceptions import InsufficientStock@@ -75,6 +76,10 @@ def clean_shipping_method(checkout, method, discounts, country_code=None, removedef check_lines_quantity(variants, quantities):"""Check if stock is sufficient for each line in the list of dicts."""for variant, quantity in zip(variants, quantities):+ if quantity < 1:+ raise ValidationError(+ {"quantity": "The quantity should be higher than zero."}+ )if quantity > settings.MAX_CHECKOUT_LINE_QUANTITY:raise ValidationError({@@ -112,7 +117,7 @@ class CheckoutCreateInput(graphene.InputObjectType):)email = graphene.String(description="The customer's email address.")shipping_address = AddressInput(- description=("The mailing address to where the checkout will be shipped.")+ description="The mailing address to where the checkout will be shipped.")billing_address = AddressInput(description="Billing address of the customer.")@@ -144,7 +149,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):def retrieve_shipping_address(cls, user, data: dict) -> Optional[models.Address]:if "shipping_address" in data:return cls.validate_address(data["shipping_address"])- elif user.is_authenticated:+ if user.is_authenticated:return user.default_shipping_addressreturn None@@ -152,7 +157,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):def retrieve_billing_address(cls, user, data: dict) -> Optional[models.Address]:if "billing_address" in data:return cls.validate_address(data["billing_address"])- elif user.is_authenticated:+ if user.is_authenticated:return user.default_billing_addressreturn None@@ -179,9 +184,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):return cleaned_input@classmethod+ @transaction.atomic()def save(cls, info, instance, cleaned_input):- # FIXME: we should add a atomic transaction here?-shipping_address = cleaned_input.get("shipping_address")billing_address = cleaned_input.get("billing_address")@@ -197,11 +201,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):variants = cleaned_input.get("variants")quantities = cleaned_input.get("quantities")- # FIXME: move this logic out of save and then add by ignoring quantities check++ # Update/create checkout linesif variants and quantities:for variant, quantity in zip(variants, quantities):- # FIXME: should we catch ValueError- add_variant_to_checkout(instance, variant, quantity)+ update_or_create_checkout_line(instance, variant, quantity)@classmethoddef perform_mutation(cls, _root, info, **data):@@ -210,14 +214,17 @@ class CheckoutCreate(ModelMutation, I18nMixin):# `perform_mutation` is overridden to properly get or create a checkout# instance here and abort mutation if needed.if user.is_authenticated:- checkout, created = get_or_create_user_checkout(user)- # If user has an active checkout, return it without any- # modifications.- if not created:+ checkout = get_user_checkout(user)++ if checkout is not None:+ # If user has an active checkout, return it without any+ # modifications.# FIXME: should we raise an error?# Nothing was created--which is invalid,# the user knows nothing about this.return CheckoutCreate(checkout=checkout)++ checkout = models.Checkout(user=user)else:checkout = models.Checkout()diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 914117db22..70f77424ca 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -74,8 +74,16 @@ def test_checkout_create(api_client, variant, graphql_address_data):assert new_checkout.shipping_address.city == shipping_address["city"].upper()-def test_checkout_create_cannot_add_too_many_quantities(- api_client, variant, graphql_address_data+ "quantity, expected_error_message",+ (+ (-1, "The quantity should be higher than zero."),+ (0, "The quantity should be higher than zero."),+ (51, "Cannot add more than 50 times this item."),+ ),+)+def test_checkout_create_cannot_add_invalid_quantities(+ api_client, variant, graphql_address_data, quantity, expected_error_message):variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)@@ -83,7 +91,7 @@ def test_checkout_create_cannot_add_too_many_quantities(shipping_address = graphql_address_datavariables = {"checkoutInput": {- "lines": [{"quantity": 51, "variantId": variant_id}],+ "lines": [{"quantity": quantity, "variantId": variant_id}],"email": test_email,"shippingAddress": shipping_address,}@@ -93,7 +101,7 @@ def test_checkout_create_cannot_add_too_many_quantities(content = get_graphql_content(response)["data"]["checkoutCreate"]assert content["errors"]assert content["errors"] == [- {"field": "quantity", "message": "Cannot add more than 50 times this item."}+ {"field": "quantity", "message": expected_error_message}]