Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop checkout forms and unused utils functions
IKarbowiak87d8c2d1a05d
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pydeleted file mode 100644index 0860f2ab08..0000000000--- a/saleor/checkout/forms.py+++ /dev/null@@ -1,410 +0,0 @@-"""Checkout-related forms and fields."""-from typing import Any--from django import forms-from django.conf import settings-from django.core.exceptions import NON_FIELD_ERRORS-from django.utils import timezone-from django.utils.encoding import smart_text-from django.utils.safestring import mark_safe-from django.utils.translation import npgettext_lazy, pgettext_lazy-from django_countries.fields import Country, LazyTypedChoiceField--from ..core.exceptions import InsufficientStock-from ..core.taxes import display_gross_prices-from ..core.utils import format_money-from ..discount.models import NotApplicable, Voucher-from ..extensions.manager import get_extensions_manager-from ..shipping.models import ShippingMethod, ShippingZone-from .models import Checkout---class QuantityField(forms.IntegerField):- """A specialized integer field with initial quantity and min/max values."""-- def __init__(self, **kwargs):- super().__init__(- min_value=0,- max_value=settings.MAX_CHECKOUT_LINE_QUANTITY,- initial=1,- **kwargs,- )---class AddToCheckoutForm(forms.Form):- """Add-to-checkout form.-- Allows selection of a product variant and quantity.-- The save method adds it to the checkout.- """-- quantity = QuantityField(- label=pgettext_lazy("Add to checkout form field label", "Quantity")- )- error_messages = {- "not-available": pgettext_lazy(- "Add to checkout form error",- "Sorry. This product is currently not available.",- ),- "empty-stock": pgettext_lazy(- "Add to checkout form error",- "Sorry. This product is currently out of stock.",- ),- "variant-too-many-in-checkout": pgettext_lazy(- "Add to checkout form error",- "Sorry. You can't add more than %d times this item.",- ),- "variant-does-not-exists": pgettext_lazy(- "Add to checkout form error", "Oops. We could not find that product."- ),- "insufficient-stock": npgettext_lazy(- "Add to checkout form error",- "Only %d remaining in stock.",- "Only %d remaining in stock.",- ),- }-- def __init__(self, *args, **kwargs):- self.checkout = kwargs.pop("checkout")- self.product = kwargs.pop("product")- self.discounts = kwargs.pop("discounts", ())- self.country = kwargs.pop("country", {})- self.extensions = kwargs.pop("extensions", None)- super().__init__(*args, **kwargs)-- def add_error_i18n(self, field, error_name, fmt: Any = tuple()):- self.add_error(field, self.error_messages[error_name] % fmt)-- def clean(self):- """Clean the form.-- Makes sure the total quantity in checkout (taking into account what was- already there) does not exceed available quantity.- """- cleaned_data = super().clean()- quantity = cleaned_data.get("quantity")- if quantity is None:- return cleaned_data- variant = self.get_variant(cleaned_data)- if variant is None:- self.add_error_i18n(NON_FIELD_ERRORS, "variant-does-not-exists")- else:- line = self.checkout.get_line(variant)- used_quantity = line.quantity if line else 0- new_quantity = quantity + used_quantity-- if new_quantity > settings.MAX_CHECKOUT_LINE_QUANTITY:- self.add_error_i18n(- "quantity",- "variant-too-many-in-checkout",- settings.MAX_CHECKOUT_LINE_QUANTITY,- )- return cleaned_data-- try:- variant.check_quantity(new_quantity)- except InsufficientStock as e:- remaining = e.item.quantity_available - used_quantity- if remaining:- self.add_error_i18n("quantity", "insufficient-stock", remaining)- else:- self.add_error_i18n("quantity", "empty-stock")- return cleaned_data-- def save(self):- """Add the selected product variant and quantity to the checkout."""- from .utils import add_variant_to_checkout-- variant = self.get_variant(self.cleaned_data)- quantity = self.cleaned_data["quantity"]- add_variant_to_checkout(self.checkout, variant, quantity)-- def get_variant(self, cleaned_data):- """Return a product variant that matches submitted values.-- This allows specialized implementations to select the variant based on- multiple fields (like size and color) instead of having a single- variant selection widget.- """- raise NotImplementedError()---class ReplaceCheckoutLineForm(AddToCheckoutForm):- """Replace quantity in checkout form.-- Similar to AddToCheckoutForm but its save method replaces the quantity.- """-- def __init__(self, *args, **kwargs):- self.variant = kwargs.pop("variant")- super().__init__(*args, product=self.variant.product, **kwargs)- self.fields["quantity"].widget.attrs = {- "min": 1,- "max": settings.MAX_CHECKOUT_LINE_QUANTITY,- }-- def clean_quantity(self):- """Clean the quantity field.-- Checks if target quantity does not exceed the currently available- quantity.- """- quantity = self.cleaned_data["quantity"]- try:- self.variant.check_quantity(quantity)- except InsufficientStock as e:- msg = self.error_messages["insufficient-stock"]- raise forms.ValidationError(msg % e.item.quantity_available, code=e.code)- return quantity-- def clean(self):- """Clean the form skipping the add-to-form checks."""- # explicitly skip parent's implementation- # pylint: disable=E1003- return super(AddToCheckoutForm, self).clean()-- def get_variant(self, cleaned_data):- """Return the matching variant.-- In this case we explicitly know the variant as we're modifying an- existing line in checkout.- """- return self.variant-- def save(self):- """Replace the selected product's quantity in checkout."""- from .utils import add_variant_to_checkout-- variant = self.get_variant(self.cleaned_data)- quantity = self.cleaned_data["quantity"]- add_variant_to_checkout(self.checkout, variant, quantity, replace=True)---class CountryForm(forms.Form):- """Country selection form."""-- country = LazyTypedChoiceField(- label=pgettext_lazy("Country form field label", "Country"), choices=[]- )-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- available_countries = {- (country.code, country.name)- for shipping_zone in ShippingZone.objects.all()- for country in shipping_zone.countries- }- self.fields["country"].choices = sorted(- available_countries, key=lambda choice: choice[1]- )-- def get_shipping_price_estimate(self, checkout, discounts):- """Return a shipping price range for given order for the selected country."""- from .utils import get_shipping_price_estimate-- country = self.cleaned_data["country"]- if isinstance(country, str):- country = Country(country)- return get_shipping_price_estimate(checkout, discounts, country)---class AnonymousUserShippingForm(forms.ModelForm):- """Additional shipping information form for users who are not logged in."""-- email = forms.EmailField(- widget=forms.EmailInput(attrs={"autocomplete": "shipping email"}),- label=pgettext_lazy("Address form field label", "Email"),- )-- class Meta:- model = Checkout- fields = ["email"]---class AnonymousUserBillingForm(forms.ModelForm):- """Additional billing information form for users who are not logged in."""-- email = forms.EmailField(- widget=forms.EmailInput(attrs={"autocomplete": "billing email"}),- label=pgettext_lazy("Address form field label", "Email"),- )-- class Meta:- model = Checkout- fields = ["email"]---class AddressChoiceForm(forms.Form):- """Choose one of user's addresses or to create new one."""-- NEW_ADDRESS = "new_address"- CHOICES = [- (- NEW_ADDRESS,- pgettext_lazy("Shipping addresses form choice", "Enter a new address"),- )- ]-- address = forms.ChoiceField(- label=pgettext_lazy("Shipping addresses form field label", "Address"),- choices=CHOICES,- initial=NEW_ADDRESS,- widget=forms.RadioSelect,- )-- def __init__(self, *args, **kwargs):- addresses = kwargs.pop("addresses")- super().__init__(*args, **kwargs)- address_choices = [(address.id, str(address)) for address in addresses]- self.fields["address"].choices = self.CHOICES + address_choices---class BillingAddressChoiceForm(AddressChoiceForm):- """Choose one of user's addresses, a shipping one or to create new."""-- NEW_ADDRESS = "new_address"- SHIPPING_ADDRESS = "shipping_address"- CHOICES = [- (- NEW_ADDRESS,- pgettext_lazy("Billing addresses form choice", "Enter a new address"),- ),- (- SHIPPING_ADDRESS,- pgettext_lazy("Billing addresses form choice", "Same as shipping"),- ),- ]-- address = forms.ChoiceField(- label=pgettext_lazy("Billing addresses form field label", "Address"),- choices=CHOICES,- initial=SHIPPING_ADDRESS,- widget=forms.RadioSelect,- )---class ShippingMethodChoiceField(forms.ModelChoiceField):- """Shipping method choice field.-- Uses a radio group instead of a dropdown and includes estimated shipping- prices.- """-- shipping_address = None- extensions = None- widget = forms.RadioSelect()-- def label_from_instance(self, obj):- """Return a friendly label for the shipping method."""- if display_gross_prices():- price = self.extensions.apply_taxes_to_shipping(- obj.price, shipping_address=self.shipping_address- ).gross- else:- price = obj.price- price_html = format_money(price)- label = mark_safe("%s %s" % (obj.name, price_html))- return label---class CheckoutShippingMethodForm(forms.ModelForm):- shipping_method = ShippingMethodChoiceField(- queryset=ShippingMethod.objects.all(),- label=pgettext_lazy("Shipping method form field label", "Shipping method"),- empty_label=None,- )-- class Meta:- model = Checkout- fields = ["shipping_method"]-- def __init__(self, *args, **kwargs):- from .utils import get_valid_shipping_methods_for_checkout-- discounts = kwargs.pop("discounts")- extensions = get_extensions_manager()- super().__init__(*args, **kwargs)- shipping_address = self.instance.shipping_address- country_code = shipping_address.country.code- qs = get_valid_shipping_methods_for_checkout(- self.instance, discounts, country_code=country_code- )- self.fields["shipping_method"].queryset = qs- self.fields["shipping_method"].shipping_address = shipping_address- self.fields["shipping_method"].extensions = extensions-- if self.initial.get("shipping_method") is None:- shipping_methods = qs.all()- if shipping_methods:- self.initial["shipping_method"] = shipping_methods[0]---class CheckoutNoteForm(forms.ModelForm):- """Save note in checkout."""-- note = forms.CharField(- max_length=250,- required=False,- strip=True,- label=False,- widget=forms.Textarea({"rows": 3}),- )-- class Meta:- model = Checkout- fields = ["note"]---class VoucherField(forms.ModelChoiceField):-- default_error_messages = {- "invalid_choice": pgettext_lazy(- "Voucher form error", "Discount code incorrect or expired"- )- }---class CheckoutVoucherForm(forms.ModelForm):- """Apply voucher to a checkout form."""-- voucher = VoucherField(- queryset=Voucher.objects.none(),- to_field_name="code",- help_text=pgettext_lazy(- "Checkout discount form label for voucher field",- "Gift card or discount code",- ),- widget=forms.TextInput,- )-- class Meta:- model = Checkout- fields = ["voucher"]-- def __init__(self, *args, **kwargs):- super().__init__(*args, **kwargs)- self.fields["voucher"].queryset = Voucher.objects.active(date=timezone.now())-- def clean(self):- from .utils import get_voucher_discount_for_checkout-- cleaned_data = super().clean()- if "voucher" in cleaned_data:- voucher = cleaned_data["voucher"]- try:- discount = get_voucher_discount_for_checkout(voucher, self.instance)- cleaned_data["discount"] = discount- except NotApplicable as e:- self.add_error("voucher", smart_text(e))- return cleaned_data-- def save(self, commit=True):- voucher = self.cleaned_data["voucher"]- self.instance.voucher_code = voucher.code- self.instance.discount_name = voucher.name- self.instance.translated_discount_name = (- voucher.translated.name if voucher.translated.name != voucher.name else ""- )- self.instance.discount = self.cleaned_data["discount"]- return super().save(commit)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 141a053cbe..8b70fdea1d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -1,26 +1,20 @@"""Checkout-related utility functions."""-from datetime import date, timedelta-from functools import wraps+from datetime import datefrom typing import TYPE_CHECKING, List, Optional, Tuple-from uuid import UUID-from django.contrib import messagesfrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.db.models import Max, Min, Sumfrom django.utils import timezonefrom django.utils.encoding import smart_text-from django.utils.translation import get_language, pgettext, pgettext_lazy+from django.utils.translation import get_language, pgettextfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from ..account.forms import get_address_form-from ..account.models import Address, User+from ..account.models import Userfrom ..account.utils import store_user_addressfrom ..checkout import calculationsfrom ..checkout.error_codes import CheckoutErrorCode-from ..core.exceptions import InsufficientStockfrom ..core.taxes import quantize_price, zero_taxed_money-from ..core.utils import to_local_currencyfrom ..core.utils.promo_code import (InvalidPromoCode,promo_code_is_gift_card,@@ -45,13 +39,7 @@ from ..order.actions import order_createdfrom ..order.emails import send_order_confirmationfrom ..order.models import Order, OrderLinefrom ..shipping.models import ShippingMethod-from . import AddressType, logger-from .forms import (- AddressChoiceForm,- AnonymousUserBillingForm,- AnonymousUserShippingForm,- BillingAddressChoiceForm,-)+from . import AddressTypefrom .models import Checkout, CheckoutLineif TYPE_CHECKING:@@ -60,135 +48,20 @@ if TYPE_CHECKING:COOKIE_NAME = "checkout"-def set_checkout_cookie(simple_checkout, response):- """Update response with a checkout token cookie."""- # FIXME: document why session is not used- max_age = int(timedelta(days=30).total_seconds())- response.set_signed_cookie(COOKIE_NAME, simple_checkout.token, max_age=max_age)---def contains_unavailable_variants(checkout):- """Return `True` if checkout contains any unfulfillable lines."""- try:- for line in checkout:- line.variant.check_quantity(line.quantity)- except InsufficientStock:- return True- return False---def token_is_valid(token):- """Validate a checkout token."""- if token is None:- return False- if isinstance(token, UUID):- return True- try:- UUID(token)- except ValueError:- return False- return True---def remove_unavailable_variants(checkout):- """Remove any unavailable items from checkout."""- for line in checkout:- try:- add_variant_to_checkout(checkout, line.variant, line.quantity, replace=True)- except InsufficientStock as e:- quantity = e.item.quantity_available- add_variant_to_checkout(checkout, line.variant, quantity, replace=True)---def get_prices_of_discounted_specific_product(- lines: List[CheckoutLine], voucher: Voucher, discounts: "DiscountsListType" = None-) -> List[Money]:- """Get prices of variants belonging to the discounted specific products.-- Specific products are products, collections and categories.- Product must be assigned directly to the discounted category, assigning- product to child category won't work.- """- discounted_products = voucher.products.all()- discounted_categories = set(voucher.categories.all())- discounted_collections = set(voucher.collections.all())-- line_prices = []- discounted_lines = []- if discounted_products or discounted_collections or discounted_categories:- for line in lines:- line_product = line.variant.product- line_category = line.variant.product.category- line_collections = set(line.variant.product.collections.all())- if line.variant and (- line_product in discounted_products- or line_category in discounted_categories- or line_collections.intersection(discounted_collections)- ):- discounted_lines.append(line)+def get_checkout_from_request(request, checkout_queryset=Checkout.objects.all()):+ """Fetch checkout from database or return a new instance based on cookie."""+ if request.user.is_authenticated:+ checkout, _ = get_user_checkout(request.user, checkout_queryset)+ user = request.userelse:- # If there's no discounted products, collections or categories,- # it means that all products are discounted- discounted_lines.extend(list(lines))-- for line in discounted_lines:- line_total = calculations.checkout_line_total(line, discounts or []).gross- line_unit_price = quantize_price(- (line_total / line.quantity), line_total.currency- )- line_prices.extend([line_unit_price] * line.quantity)-- return line_prices---def check_product_availability_and_warn(request, checkout):- """Warn if checkout contains any lines that cannot be fulfilled."""- if contains_unavailable_variants(checkout):- msg = pgettext_lazy(- "Checkout warning message",- "Sorry. We don't have that many items in stock. "- "Quantity was set to maximum available for now.",- )- messages.warning(request, msg)- remove_unavailable_variants(checkout)---def find_and_assign_anonymous_checkout(queryset=Checkout.objects.all()):- """Assign checkout from cookie to request user."""-- def get_checkout(view):- @wraps(view)- def func(request, *args, **kwargs):- response = view(request, *args, **kwargs)- token = request.get_signed_cookie(COOKIE_NAME, default=None)- if not token_is_valid(token):- return response- checkout = get_anonymous_checkout_from_token(- token=token, checkout_queryset=queryset- )- if checkout is None:- return response- if request.user.is_authenticated:- with transaction.atomic():- change_checkout_user(checkout, request.user)- checkouts_to_close = Checkout.objects.filter(user=request.user)- checkouts_to_close = checkouts_to_close.exclude(token=token)- checkouts_to_close.delete()- response.delete_cookie(COOKIE_NAME)- return response-- return func-- return get_checkout---def get_or_create_anonymous_checkout_from_token(- token, checkout_queryset=Checkout.objects.all()-):- """Return an open unassigned checkout with given token or create a new one."""- return checkout_queryset.filter(token=token, user=None).get_or_create(- defaults={"user": None}- )[0]+ token = request.get_signed_cookie(COOKIE_NAME, default=None)+ checkout = get_anonymous_checkout_from_token(token, checkout_queryset)+ user = None+ if checkout is not None:+ return checkout+ if user:+ return Checkout(user=user)+ return Checkout()def get_user_checkout(@@ -215,76 +88,6 @@ def get_anonymous_checkout_from_token(token, checkout_queryset=Checkout.objects.return checkout_queryset.filter(token=token, user=None).first()-def get_or_create_checkout_from_request(- request, checkout_queryset=Checkout.objects.all()-) -> Checkout:- """Fetch checkout from database or create a new one based on cookie."""- if request.user.is_authenticated:- return get_user_checkout(request.user, checkout_queryset, auto_create=True)[0]- token = request.get_signed_cookie(COOKIE_NAME, default=None)- return get_or_create_anonymous_checkout_from_token(token, checkout_queryset)---def get_checkout_from_request(request, checkout_queryset=Checkout.objects.all()):- """Fetch checkout from database or return a new instance based on cookie."""- if request.user.is_authenticated:- checkout, _ = get_user_checkout(request.user, checkout_queryset)- user = request.user- else:- token = request.get_signed_cookie(COOKIE_NAME, default=None)- checkout = get_anonymous_checkout_from_token(token, checkout_queryset)- user = None- if checkout is not None:- return checkout- if user:- return Checkout(user=user)- return Checkout()---def get_or_empty_db_checkout(checkout_queryset=Checkout.objects.all()):- """Decorate view to receive a checkout if one exists.-- Changes the view signature from `func(request, ...)` to- `func(request, checkout, ...)`.-- If no matching checkout is found, an unsaved `Checkout` instance will be used.- """- # FIXME: behave like middleware and assign checkout to request instead- def get_checkout(view):- @wraps(view)- def func(request, *args, **kwargs):- checkout = get_checkout_from_request(request, checkout_queryset)- return view(request, checkout, *args, **kwargs)-- return func-- return get_checkout---def find_open_checkout_for_user(user):- """Find an open checkout for the given user."""- checkouts = user.checkouts.all()- open_checkout = checkouts.first()- if len(checkouts) > 1:- logger.warning("%s has more than one open basket", user)- checkouts.exclude(token=open_checkout.token).delete()- return open_checkout---def change_checkout_user(checkout, user):- """Assign checkout to a user.-- If the user already has an open checkout assigned, cancel it.- """- open_checkout = find_open_checkout_for_user(user)- if open_checkout is not None:- open_checkout.delete()- checkout.user = user- checkout.shipping_address = user.default_shipping_address- checkout.billing_address = user.default_billing_address- checkout.save(update_fields=["user", "shipping_address", "billing_address"])--def update_checkout_quantity(checkout):"""Update the total quantity in checkout."""total_lines = checkout.lines.aggregate(total_quantity=Sum("quantity"))[@@ -348,265 +151,6 @@ def add_variant_to_checkout(update_checkout_quantity(checkout)-def get_shipping_address_forms(checkout, user_addresses, data, country):- """Retrieve a form initialized with data based on the checkout shipping address."""- shipping_address = (- checkout.shipping_address or checkout.user.default_shipping_address- )-- if shipping_address and shipping_address in user_addresses:- address_form, preview = get_address_form(- data, country_code=country.code, initial={"country": country}- )- addresses_form = AddressChoiceForm(- data, addresses=user_addresses, initial={"address": shipping_address.id}- )- elif shipping_address:- address_form, preview = get_address_form(- data, country_code=shipping_address.country.code, instance=shipping_address- )- addresses_form = AddressChoiceForm(data, addresses=user_addresses)- else:- address_form, preview = get_address_form(- data, country_code=country.code, initial={"country": country}- )- addresses_form = AddressChoiceForm(data, addresses=user_addresses)-- return address_form, addresses_form, preview---def update_shipping_address_in_checkout(checkout, user_addresses, data, country):- """Return shipping address choice forms and if an address was updated."""- address_form, addresses_form, preview = get_shipping_address_forms(- checkout, user_addresses, data, country- )-- updated = False-- if addresses_form.is_valid() and not preview:- use_existing_address = (- addresses_form.cleaned_data["address"] != AddressChoiceForm.NEW_ADDRESS- )-- if use_existing_address:- address_id = addresses_form.cleaned_data["address"]- address = Address.objects.get(id=address_id)- change_shipping_address_in_checkout(checkout, address)- updated = True-- elif address_form.is_valid():- address = address_form.save()- change_shipping_address_in_checkout(checkout, address)- updated = True-- return addresses_form, address_form, updated---def update_shipping_address_in_anonymous_checkout(checkout, data, country):- """Return shipping address choice forms and if an address was updated."""- address_form, preview = get_address_form(- data,- country_code=country.code,- autocomplete_type="shipping",- instance=checkout.shipping_address,- initial={"country": country},- )- user_form = AnonymousUserShippingForm(- data if not preview else None, instance=checkout- )-- updated = False-- if user_form.is_valid() and address_form.is_valid():- user_form.save()- address = address_form.save()- change_shipping_address_in_checkout(checkout, address)- updated = True-- return user_form, address_form, updated---def get_billing_forms_with_shipping(checkout, data, user_addresses, country):- """Get billing form based on a the current billing and shipping data."""- shipping_address = checkout.shipping_address- billing_address = checkout.billing_address or Address(country=country)-- if not billing_address.id or billing_address == shipping_address:- address_form, preview = get_address_form(- data,- country_code=shipping_address.country.code,- autocomplete_type="billing",- initial={"country": shipping_address.country},- )- addresses_form = BillingAddressChoiceForm(- data,- addresses=user_addresses,- initial={"address": BillingAddressChoiceForm.SHIPPING_ADDRESS},- )- elif billing_address in user_addresses:- address_form, preview = get_address_form(- data,- country_code=billing_address.country.code,- autocomplete_type="billing",- initial={"country": billing_address.country},- )- addresses_form = BillingAddressChoiceForm(- data, addresses=user_addresses, initial={"address": billing_address.id}- )- else:- address_form, preview = get_address_form(- data,- country_code=billing_address.country.code,- autocomplete_type="billing",- initial={"country": billing_address.country},- instance=billing_address,- )- addresses_form = BillingAddressChoiceForm(- data,- addresses=user_addresses,- initial={"address": BillingAddressChoiceForm.NEW_ADDRESS},- )-- return address_form, addresses_form, preview---def update_billing_address_in_checkout_with_shipping(- checkout, user_addresses, data, country-):- """Return shipping address choice forms and if an address was updated."""- address_form, addresses_form, preview = get_billing_forms_with_shipping(- checkout, data, user_addresses, country- )-- updated = False-- if addresses_form.is_valid() and not preview:- address = None- address_id = addresses_form.cleaned_data["address"]-- if address_id == BillingAddressChoiceForm.SHIPPING_ADDRESS:- if checkout.user and checkout.shipping_address in user_addresses:- address = checkout.shipping_address- else:- address = checkout.shipping_address.get_copy()- elif address_id != BillingAddressChoiceForm.NEW_ADDRESS:- address = user_addresses.get(id=address_id)- elif address_form.is_valid():- address = address_form.save()-- if address:- change_billing_address_in_checkout(checkout, address)- updated = True-- return addresses_form, address_form, updated---def get_anonymous_summary_without_shipping_forms(checkout, data, country):- """Build a form initialized with data depending on addresses in checkout."""- billing_address = checkout.billing_address-- if billing_address:- address_form, preview = get_address_form(- data,- country_code=billing_address.country.code,- autocomplete_type="billing",- instance=billing_address,- )- else:- address_form, preview = get_address_form(- data,- country_code=country.code,- autocomplete_type="billing",- initial={"country": country},- )-- return address_form, preview---def update_billing_address_in_anonymous_checkout(checkout, data, country):- """Return shipping address choice forms and if an address was updated."""- address_form, preview = get_anonymous_summary_without_shipping_forms(- checkout, data, country- )- user_form = AnonymousUserBillingForm(data, instance=checkout)-- updated = False-- if user_form.is_valid() and address_form.is_valid() and not preview:- user_form.save()- address = address_form.save()- change_billing_address_in_checkout(checkout, address)- updated = True-- return user_form, address_form, updated---def get_summary_without_shipping_forms(checkout, user_addresses, data, country):- """Build a forms initialized with data depending on addresses in checkout."""- billing_address = checkout.billing_address-- if billing_address and billing_address in user_addresses:- address_form, preview = get_address_form(- data,- autocomplete_type="billing",- country_code=billing_address.country.code,- initial={"country": billing_address.country},- )- initial_address = billing_address.id- elif billing_address:- address_form, preview = get_address_form(- data,- autocomplete_type="billing",- country_code=billing_address.country.code,- initial={"country": billing_address.country},- instance=billing_address,- )- initial_address = AddressChoiceForm.NEW_ADDRESS- else:- address_form, preview = get_address_form(- data,- autocomplete_type="billing",- country_code=country.code,- initial={"country": country},- )- if checkout.user and checkout.user.default_billing_address:- initial_address = checkout.user.default_billing_address.id- else:- initial_address = AddressChoiceForm.NEW_ADDRESS-- addresses_form = AddressChoiceForm(- data, addresses=user_addresses, initial={"address": initial_address}- )- return address_form, addresses_form, preview---def update_billing_address_in_checkout(checkout, user_addresses, data, country):- """Return shipping address choice forms and if an address was updated."""- address_form, addresses_form, preview = get_summary_without_shipping_forms(- checkout, user_addresses, data, country- )-- updated = False-- if addresses_form.is_valid():- use_existing_address = (- addresses_form.cleaned_data["address"] != AddressChoiceForm.NEW_ADDRESS- )-- if use_existing_address:- address_id = addresses_form.cleaned_data["address"]- address = Address.objects.get(id=address_id)- change_billing_address_in_checkout(checkout, address)- updated = True-- elif address_form.is_valid():- address = address_form.save()- change_billing_address_in_checkout(checkout, address)- updated = True-- return addresses_form, address_form, updated--def _check_new_checkout_address(checkout, address, address_type):"""Check if and address in checkout has changed and if to remove old one."""if address_type == AddressType.BILLING:@@ -661,55 +205,6 @@ def change_shipping_address_in_checkout(checkout, address):checkout.save(update_fields=["shipping_address"])-def get_checkout_context(- checkout: Checkout,- discounts: "DiscountsListType",- currency: Optional[str] = None,- shipping_range=None,-) -> dict:- """Retrieve the data shared between views in checkout process."""- cards_balance = checkout.get_total_gift_cards_balance()-- # FIXME: We are having here parts of checkout total calculation logic- checkout_total = calculations.checkout_total(checkout=checkout, discounts=discounts)- checkout_total.gross -= cards_balance- checkout_total.net -= cards_balance- checkout_total = max(checkout_total, zero_taxed_money(checkout_total.currency))- checkout_subtotal = calculations.checkout_subtotal(checkout, discounts)- shipping_price = calculations.checkout_shipping_price(checkout, discounts)-- shipping_required = checkout.is_shipping_required()- total_with_shipping = TaxedMoneyRange(- start=checkout_subtotal, stop=checkout_subtotal- )- if shipping_required and shipping_range:- total_with_shipping = shipping_range + checkout_subtotal-- manager = get_extensions_manager()- context = {- "checkout": checkout,- "checkout_are_taxes_handled": manager.taxes_are_enabled(),- "checkout_lines": [- (line, calculations.checkout_line_total(line, discounts))- for line in checkout- ],- "checkout_shipping_price": shipping_price,- "checkout_subtotal": checkout_subtotal,- "checkout_total": checkout_total,- "shipping_required": checkout.is_shipping_required(),- "total_with_shipping": total_with_shipping,- }-- if currency:- context.update(- local_checkout_total=to_local_currency(checkout_total, currency),- local_checkout_subtotal=to_local_currency(checkout_subtotal, currency),- local_total_with_shipping=to_local_currency(total_with_shipping, currency),- )-- return context--def _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts: "DiscountsListType" = None):@@ -753,6 +248,47 @@ def _get_products_voucher_discount(return get_products_voucher_discount(voucher, prices)+def get_prices_of_discounted_specific_product(+ lines: List[CheckoutLine], voucher: Voucher, discounts: "DiscountsListType" = None+) -> List[Money]:+ """Get prices of variants belonging to the discounted specific products.++ Specific products are products, collections and categories.+ Product must be assigned directly to the discounted category, assigning+ product to child category won't work.+ """+ discounted_products = voucher.products.all()+ discounted_categories = set(voucher.categories.all())+ discounted_collections = set(voucher.collections.all())++ line_prices = []+ discounted_lines = []+ if discounted_products or discounted_collections or discounted_categories:+ for line in lines:+ line_product = line.variant.product+ line_category = line.variant.product.category+ line_collections = set(line.variant.product.collections.all())+ if line.variant and (+ line_product in discounted_products+ or line_category in discounted_categories+ or line_collections.intersection(discounted_collections)+ ):+ discounted_lines.append(line)+ else:+ # If there's no discounted products, collections or categories,+ # it means that all products are discounted+ discounted_lines.extend(list(lines))++ for line in discounted_lines:+ line_total = calculations.checkout_line_total(line, discounts or []).gross+ line_unit_price = quantize_price(+ (line_total / line.quantity), line_total.currency+ )+ line_prices.extend([line_unit_price] * line.quantity)++ return line_prices++def get_voucher_discount_for_checkout(voucher: Voucher, checkout: Checkout, discounts: "DiscountsListType" = None) -> Money:diff --git a/tests/test_cart.py b/tests/test_cart.pyindex 41bbf7d1b4..f2ae0d52fa 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -1,20 +1,14 @@-from unittest.mock import MagicMock, Mock+from unittest.mock import Mockfrom uuid import uuid4import pytestfrom measurement.measures import Weightfrom prices import Money, TaxedMoney-from saleor.checkout import calculations, forms, utils+from saleor.checkout import calculations, utilsfrom saleor.checkout.context_processors import checkout_counterfrom saleor.checkout.models import Checkout-from saleor.checkout.utils import (- add_variant_to_checkout,- change_checkout_user,- find_open_checkout_for_user,- get_shipping_price_estimate,-)-from saleor.core.exceptions import InsufficientStock+from saleor.checkout.utils import add_variant_to_checkoutfrom saleor.product.models import Category@@ -23,29 +17,6 @@ def anonymous_checkout(db):return Checkout.objects.get_or_create(user=None)[0]-def test_get_or_create_anonymous_checkout_from_token(anonymous_checkout, user_checkout):- queryset = Checkout.objects.all()- checkouts = list(queryset)- checkout = utils.get_or_create_anonymous_checkout_from_token(- anonymous_checkout.token- )- assert Checkout.objects.all().count() == 2- assert checkout == anonymous_checkout-- # test against new token- checkout = utils.get_or_create_anonymous_checkout_from_token(uuid4())- assert Checkout.objects.all().count() == 3- assert checkout not in checkouts- assert checkout.user is None- checkout.delete()-- # test against getting checkout assigned to user- checkout = utils.get_or_create_anonymous_checkout_from_token(user_checkout.token)- assert Checkout.objects.all().count() == 3- assert checkout not in checkouts- assert checkout.user is None--def test_get_or_create_user_checkout(customer_user, anonymous_checkout, user_checkout, admin_user):@@ -244,138 +215,6 @@ def test_get_prices_of_discounted_specific_product_all_products(assert prices == excepted_value-def test_contains_unavailable_variants():- missing_variant = Mock(check_quantity=Mock(side_effect=InsufficientStock("")))- checkout = MagicMock()- checkout.__iter__ = Mock(return_value=iter([Mock(variant=missing_variant)]))- assert utils.contains_unavailable_variants(checkout)-- variant = Mock(check_quantity=Mock())- checkout.__iter__ = Mock(return_value=iter([Mock(variant=variant)]))- assert not utils.contains_unavailable_variants(checkout)---def test_remove_unavailable_variants(checkout, product):- variant = product.variants.get()- add_variant_to_checkout(checkout, variant)- variant.quantity = 0- variant.save()- utils.remove_unavailable_variants(checkout)- assert len(checkout) == 0---def test_check_product_availability_and_warn(monkeypatch, checkout, product):- variant = product.variants.get()- add_variant_to_checkout(checkout, variant)- monkeypatch.setattr("django.contrib.messages.warning", Mock(warning=Mock()))- monkeypatch.setattr(- "saleor.checkout.utils.contains_unavailable_variants", Mock(return_value=False)- )-- utils.check_product_availability_and_warn(MagicMock(), checkout)- assert len(checkout) == 1-- monkeypatch.setattr(- "saleor.checkout.utils.contains_unavailable_variants", Mock(return_value=True)- )- monkeypatch.setattr(- "saleor.checkout.utils.remove_unavailable_variants",- lambda c: add_variant_to_checkout(checkout, variant, 0, replace=True),- )-- utils.check_product_availability_and_warn(MagicMock(), checkout)- assert len(checkout) == 0---def test_add_to_checkout_form(checkout, product):- variant = product.variants.get()- add_variant_to_checkout(checkout, variant, 3)- data = {"quantity": 1}- form = forms.AddToCheckoutForm(data=data, checkout=checkout, product=product)-- form.get_variant = Mock(return_value=variant)-- assert form.is_valid()- form.save()- assert checkout.lines.count() == 1- assert checkout.lines.filter(variant=variant).exists()-- with pytest.raises(NotImplementedError):- data = {"quantity": 1}- form = forms.AddToCheckoutForm(data=data, checkout=checkout, product=product)- form.is_valid()- data = {}-- form = forms.AddToCheckoutForm(data=data, checkout=checkout, product=product)- assert not form.is_valid()--[email protected]("track_inventory", (True, False))-def test_add_to_checkout_form_when_insufficient_stock(product, track_inventory):- variant = product.variants.first()- variant.track_inventory = track_inventory- variant.save()-- checkout_lines = []- checkout = Mock(- add=lambda variant, quantity: checkout_lines.append(variant),- get_line=Mock(return_value=Mock(quantity=49)),- )-- form = forms.AddToCheckoutForm(- data={"quantity": 1}, checkout=checkout, product=Mock()- )- form.get_variant = Mock(return_value=variant)-- if track_inventory:- assert not form.is_valid()- else:- assert form.is_valid()---def test_replace_checkout_line_form(checkout, product):- variant = product.variants.get()- initial_quantity = 1- replaced_quantity = 4-- add_variant_to_checkout(checkout, variant, initial_quantity)- data = {"quantity": replaced_quantity}- form = forms.ReplaceCheckoutLineForm(data=data, checkout=checkout, variant=variant)- assert form.is_valid()- form.save()- assert checkout.quantity == replaced_quantity---def test_replace_checkout_line_form_when_insufficient_stock(- monkeypatch, checkout, product-):- variant = product.variants.get()- initial_quantity = 1- replaced_quantity = 4-- add_variant_to_checkout(checkout, variant, initial_quantity)- exception_mock = InsufficientStock(Mock(quantity_available=2))- monkeypatch.setattr(- "saleor.product.models.ProductVariant.check_quantity",- Mock(side_effect=exception_mock),- )- data = {"quantity": replaced_quantity}- form = forms.ReplaceCheckoutLineForm(data=data, checkout=checkout, variant=variant)- assert not form.is_valid()- with pytest.raises(KeyError):- form.save()- assert checkout.quantity == initial_quantity---def test_find_open_checkout_for_user(customer_user, user_checkout):- assert find_open_checkout_for_user(customer_user) == user_checkout-- checkout = Checkout.objects.create(user=customer_user)-- assert find_open_checkout_for_user(customer_user) == checkout- assert not Checkout.objects.filter(pk=user_checkout.pk).exists()--def test_checkout_repr():checkout = Checkout()assert repr(checkout) == "Checkout(quantity=0)"@@ -384,16 +223,6 @@ def test_checkout_repr():assert repr(checkout) == "Checkout(quantity=1)"-def test_checkout_change_user(customer_user):- checkout1 = Checkout.objects.create()- change_checkout_user(checkout1, customer_user)-- checkout2 = Checkout.objects.create()- change_checkout_user(checkout2, customer_user)-- assert not Checkout.objects.filter(pk=checkout1.pk).exists()--def test_checkout_line_repr(product, checkout_with_single_item):variant = product.variants.get()line = checkout_with_single_item.lines.first()@@ -414,43 +243,6 @@ def test_checkout_line_state(product, checkout_with_single_item):assert line.quantity == 2-def test_get_checkout_context(checkout_with_single_item, shipping_zone, address):- checkout = checkout_with_single_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])-- shipment_option = get_shipping_price_estimate(- checkout, discounts=None, country_code="PL"- )- checkout_data = utils.get_checkout_context(- checkout, None, currency="USD", shipping_range=shipment_option- )- assert checkout_data["checkout_total"] == TaxedMoney(- net=Money("10.00", "USD"), gross=Money("10.00", "USD")- )- assert checkout_data["total_with_shipping"].start == TaxedMoney(- net=Money("20.00", "USD"), gross=Money("20.00", "USD")- )---def test_get_checkout_context_no_shipping(checkout_with_single_item, address):- checkout = checkout_with_single_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])-- shipment_option = get_shipping_price_estimate(- checkout, discounts=None, country_code="PL"- )- checkout_data = utils.get_checkout_context(- checkout, None, currency="USD", shipping_range=shipment_option- )- checkout_total = checkout_data["checkout_total"]- assert checkout_total == TaxedMoney(- net=Money("10.00", "USD"), gross=Money("10.00", "USD")- )- assert checkout_data["total_with_shipping"].start == checkout_total--def test_get_total_weight(checkout_with_item):line = checkout_with_item.lines.first()variant = line.variantdiff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 0d58e219e0..643095cabb 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -5,14 +5,12 @@ import pytestfrom django.contrib.auth.models import AnonymousUserfrom django.utils import timezonefrom django_countries.fields import Country-from freezegun import freeze_time-from prices import Money, TaxedMoney, TaxedMoneyRange+from prices import Money, TaxedMoneyfrom saleor.account import CustomerEventsfrom saleor.account.models import Address, CustomerEvent, Userfrom saleor.account.utils import store_user_addressfrom saleor.checkout import AddressType, calculations-from saleor.checkout.forms import CheckoutVoucherForm, CountryFormfrom saleor.checkout.models import Checkoutfrom saleor.checkout.utils import (add_variant_to_checkout,@@ -21,8 +19,6 @@ from saleor.checkout.utils import (change_shipping_address_in_checkout,clear_shipping_method,create_order,- get_checkout_context,- get_shipping_price_estimate,get_voucher_discount_for_checkout,get_voucher_for_checkout,is_valid_shipping_method,@@ -34,24 +30,12 @@ from saleor.core.exceptions import InsufficientStockfrom saleor.core.taxes import zero_money, zero_taxed_moneyfrom saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Voucher-from saleor.extensions.manager import ExtensionsManager, get_extensions_manager+from saleor.extensions.manager import get_extensions_managerfrom saleor.order import OrderEvents, OrderEventsEmailsfrom saleor.order.models import OrderEventfrom saleor.shipping.models import ShippingZone-def test_country_form_country_choices():- form = CountryForm(data={"csrf": "", "country": "PL"})- assert form.fields["country"].choices == []-- zone = ShippingZone.objects.create(countries=["PL", "DE"], name="Europe")- form = CountryForm(data={"csrf": "", "country": "PL"})-- expected_choices = [(country.code, country.name) for country in zone.countries]- expected_choices = sorted(expected_choices, key=lambda choice: choice[1])- assert form.fields["country"].choices == expected_choices--def test_is_valid_shipping_method(checkout_with_item, address, shipping_zone):checkout = checkout_with_itemcheckout.shipping_address = address@@ -734,81 +718,6 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(assert str(e.value) == error_msg-def test_checkout_voucher_form_invalid_voucher_code(- monkeypatch, request_checkout_with_item-):- form = CheckoutVoucherForm(- {"voucher": "invalid"}, instance=request_checkout_with_item- )- assert not form.is_valid()- assert "voucher" in form.errors---def test_checkout_voucher_form_voucher_not_applicable(- voucher, request_checkout_with_item-):- voucher.min_spent = Money(200, "USD")- voucher.save()- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- assert not form.is_valid()- assert "voucher" in form.errors---def test_checkout_voucher_form_active_queryset_voucher_not_active(- voucher, request_checkout_with_item-):- assert Voucher.objects.count() == 1- voucher.start_date = timezone.now() + datetime.timedelta(days=1)- voucher.save()- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- qs = form.fields["voucher"].queryset- assert qs.count() == 0---def test_checkout_voucher_form_active_queryset_voucher_active(- voucher, request_checkout_with_item-):- assert Voucher.objects.count() == 1- voucher.start_date = timezone.now()- voucher.save()- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- qs = form.fields["voucher"].queryset- assert qs.count() == 1---def test_checkout_voucher_form_active_queryset_after_some_time(- voucher, request_checkout_with_item-):- assert Voucher.objects.count() == 1- voucher.start_date = timezone.now().replace(year=2016, month=6, day=1, hour=0)- voucher.end_date = timezone.now().replace(year=2016, month=6, day=2, hour=0)- voucher.save()-- with freeze_time("2016-05-31"):- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- assert form.fields["voucher"].queryset.count() == 0-- with freeze_time("2016-06-01T05:00:00+00:00"):- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- assert form.fields["voucher"].queryset.count() == 1-- with freeze_time("2016-06-03"):- form = CheckoutVoucherForm(- {"voucher": voucher.code}, instance=request_checkout_with_item- )- assert form.fields["voucher"].queryset.count() == 0--def test_get_voucher_for_checkout(checkout_with_voucher, voucher):checkout_voucher = get_voucher_for_checkout(checkout_with_voucher)assert checkout_voucher == voucher@@ -943,49 +852,6 @@ def test_recalculate_checkout_discount_free_shipping_for_checkout_without_shippiassert checkout.discount == zero_money()-def test_get_checkout_context(checkout_with_voucher):- line_price = TaxedMoney(net=Money("30.00", "USD"), gross=Money("30.00", "USD"))- manager = get_extensions_manager()- expected_data = {- "checkout": checkout_with_voucher,- "checkout_are_taxes_handled": manager.taxes_are_enabled(),- "checkout_lines": [(checkout_with_voucher.lines.first(), line_price)],- "checkout_shipping_price": zero_taxed_money(),- "checkout_subtotal": line_price,- "checkout_total": line_price - checkout_with_voucher.discount,- "shipping_required": checkout_with_voucher.is_shipping_required(),- "total_with_shipping": TaxedMoneyRange(start=line_price, stop=line_price),- }-- data = get_checkout_context(checkout_with_voucher, discounts=None)-- assert data == expected_data---def test_get_checkout_context_with_shipping_range(- checkout_with_voucher, shipping_method, address, monkeypatch-):- checkout_with_voucher.shipping_method = shipping_method- checkout_with_voucher.shipping_address = address- line_price = TaxedMoney(net=Money("30.00", "USD"), gross=Money("45.00", "USD"))-- monkeypatch.setattr(- ExtensionsManager, "calculate_checkout_subtotal", Mock(return_value=line_price)- )-- shipping_range = get_shipping_price_estimate(- checkout_with_voucher, discounts=None, country_code="US"- )- expected_total_with_shipping = TaxedMoneyRange(start=line_price, stop=line_price)- expected_total_with_shipping += shipping_range-- data = get_checkout_context(- checkout_with_voucher, discounts=None, shipping_range=shipping_range- )-- assert data["total_with_shipping"] == expected_total_with_shipping--def test_change_address_in_checkout(checkout, address):change_shipping_address_in_checkout(checkout, address)change_billing_address_in_checkout(checkout, address)