Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
WIP Refactor add_error to raising ValidationError
Marcin Gębala31dc1eac3232
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 06840d5c94..ad77235d53 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -5,6 +5,7 @@ from uuid import UUIDfrom django.conf import settingsfrom django.contrib import messages+from django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.db.models import Sumfrom django.utils.encoding import smart_text@@ -890,25 +891,26 @@ def is_fully_paid(cart: Cart, taxes, discounts):return total_paid >= cart_total-def ready_to_place_order(cart: Cart, taxes, discounts):+def clean_checkout(cart: Cart, taxes, discounts):"""Check if checkout can be completed."""+ errors = {}+if cart.is_shipping_required():if not cart.shipping_method:- return False, pgettext_lazy(- 'order placement_error', 'Shipping method is not set')+ errors.append('Shipping method is not set')if not cart.shipping_address:- return False, pgettext_lazy(- 'order placement error', 'Shipping address is not set')+ errors.append('Shipping address is not set')if not is_valid_shipping_method(cart, taxes, discounts):- return False, pgettext_lazy(- 'order placement error',+ errors.append('Shipping method is not valid for your shipping address')+if not cart.billing_address:- return False, pgettext_lazy(- 'order placement_error', 'Billing address is not set')+ errors.append('Billing address is not set')+if not is_fully_paid(cart, taxes, discounts):- return False, pgettext_lazy(- 'order placement error', (- 'Provided payment methods can not '- 'cover the checkout\'s total amount'))- return True, None+ errors.append(+ 'Provided payment methods can not cover the checkout\'s total '+ 'amount')++ if errors:+ raise ValidationError(errors)diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.pyindex dbcee47ea8..420c95d02d 100644--- a/saleor/graphql/account/i18n.py+++ b/saleor/graphql/account/i18n.py@@ -1,43 +1,30 @@from django_countries import countries+from django.core.exceptions import ValidationErrorfrom ...account.forms import get_address_formfrom ...account.models import Address-def get_field_name(field_name, parent_field_name):- if not field_name:- return None- if not parent_field_name:- return field_name- return '%s:%s' % (parent_field_name, field_name)--class I18nMixin:"""Mixin to be used with BaseMutation or ModelMutation, providing methodsnecessary to fulfill the internationalization process."""@classmethod- def validate_address(- cls, address_data, errors, parent_field_name=None,- instance=None):+ def validate_address(cls, address_data, instance=None):country_code = address_data.get('country')if country_code in countries.countries.keys():address_form, _ = get_address_form(address_data, address_data['country'])else:- error_msg = 'Invalid country code.'- cls.add_error(errors, 'country', error_msg)- return None, errors+ raise ValidationError({'country': 'Invalid country code.'})+if not address_form.is_valid():- for field_name, field_errors in address_form.errors.items():- error_field = get_field_name(field_name, parent_field_name)- # sometimes same error is duplicated within the field errors- for error_msg in set(field_errors):- cls.add_error(errors, error_field, error_msg)- return None, errors+ raise ValidationError(address_form.errors)+if not instance:instance = Address()+cls.construct_instance(instance, address_form.cleaned_data)- cls.clean_instance(instance, errors)- return instance, errors+ cls.clean_instance(instance)+ return instancediff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.pyindex 44c8dfc826..d7e2eb729c 100644--- a/saleor/graphql/account/mutations.py+++ b/saleor/graphql/account/mutations.py@@ -3,18 +3,17 @@ from textwrap import dedentimport graphenefrom django.conf import settingsfrom django.contrib.auth.tokens import default_token_generator-from django.core.exceptions import ObjectDoesNotExist+from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.utils.encoding import force_bytesfrom django.utils.http import urlsafe_base64_encode-from graphql_jwt.decorators import (- login_required, permission_required, staff_member_required)+from graphql_jwt.decorators import staff_member_requiredfrom graphql_jwt.exceptions import PermissionDeniedfrom ...account import emails, models, utilsfrom ...account.thumbnails import create_user_avatar_thumbnailsfrom ...account.utils import get_random_avatarfrom ...checkout import AddressType-from ...core.permissions import MODELS_PERMISSIONS, get_permissions+from ...core.permissions import get_permissionsfrom ...dashboard.emails import (send_set_password_customer_email, send_set_password_staff_email)from ...dashboard.staff.utils import remove_staff_member@@ -23,7 +22,7 @@ from ..account.i18n import I18nMixinfrom ..account.types import Address, AddressInput, Userfrom ..core.enums import PermissionEnumfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation-from ..core.types import Error, Upload+from ..core.types import Uploadfrom ..core.utils import validate_image_filefrom .utils import CustomerDeleteMixin, StaffDeleteMixin, UserDeleteMixin@@ -135,20 +134,21 @@ class CustomerCreate(ModelMutation, I18nMixin):cleaned_input = super().clean_input(info, instance, input, errors)if shipping_address_data:- shipping_address, errors = cls.validate_address(- shipping_address_data, errors, SHIPPING_ADDRESS_FIELD,+ shipping_address = cls.validate_address(+ shipping_address_data,instance=getattr(instance, SHIPPING_ADDRESS_FIELD))cleaned_input[SHIPPING_ADDRESS_FIELD] = shipping_addressif billing_address_data:- billing_address, errors = cls.validate_address(- billing_address_data, errors, BILLING_ADDRESS_FIELD,+ billing_address = cls.validate_address(+ billing_address_data,instance=getattr(instance, BILLING_ADDRESS_FIELD))cleaned_input[BILLING_ADDRESS_FIELD] = billing_addressreturn cleaned_input@classmethoddef save(cls, info, instance, cleaned_input):+ # FIXME: save address in user.addresses as welldefault_shipping_address = cleaned_input.get(SHIPPING_ADDRESS_FIELD)if default_shipping_address:default_shipping_address.save()@@ -193,10 +193,10 @@ class LoggedUserUpdate(CustomerCreate):return user.is_authenticated@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):user = info.context.userdata['id'] = graphene.Node.to_global_id('User', user.id)- return super().mutate(root, info, **data)+ return super().perform_mutation(root, info, **data)class UserDelete(UserDeleteMixin, ModelDeleteMutation):@@ -242,17 +242,8 @@ class StaffCreate(ModelMutation):# clean and prepare permissionsif 'permissions' in cleaned_input:- permissions = cleaned_input['permissions']- cleaned_permissions = []- for code in permissions:- if code not in MODELS_PERMISSIONS:- error_msg = 'Unknown permission: %s' % code- cls.add_error(errors, 'permissions', error_msg)- else:- cleaned_permissions.append(code)- if not errors:- permission_objs = get_permissions(cleaned_permissions)- cleaned_input['user_permissions'] = permission_objs+ permissions = cleaned_input.pop('permissions')+ cleaned_input['user_permissions'] = get_permissions(permissions)return cleaned_input@classmethod@@ -284,12 +275,11 @@ class StaffUpdate(StaffCreate):if not is_active:if user == instance:- cls.add_error(- errors, 'is_active', 'Cannot deactivate your own account.')+ raise ValidationError({+ 'is_active': 'Cannot deactivate your own account.'})elif instance.is_superuser:- cls.add_error(- errors, 'is_active',- 'Cannot deactivate superuser\'s account.')+ raise ValidationError({+ 'is_active': 'Cannot deactivate superuser\'s account.'})return errors@classmethod@@ -315,17 +305,14 @@ class StaffDelete(StaffDeleteMixin, UserDelete):return user.has_perm('account.manage_staff')@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):if not cls.user_is_allowed(info.context.user, data):raise PermissionDenied()errors = []user_id = data.get('id')instance = cls.get_node_or_error(info, user_id, errors, 'id', User)- if instance:- cls.clean_instance(info, instance, errors)- if errors:- return cls(errors=errors)+ cls.clean_instance(info, instance, errors)db_id = instance.idremove_staff_member(instance)@@ -360,7 +347,7 @@ class SetPassword(ModelMutation):cleaned_input = super().clean_input(info, instance, input, errors)token = cleaned_input.pop('token')if not default_token_generator.check_token(instance, token):- cls.add_error(errors, 'token', SetPassword.INVALID_TOKEN)+ raise ValidationError({'token': SetPassword.INVALID_TOKEN})return cleaned_input@classmethod@@ -377,16 +364,16 @@ class PasswordReset(BaseMutation):description = 'Sends password reset email'@classmethod- @permission_required('account.manage_users')- def mutate(cls, root, info, email):+ def user_is_allowed(cls, user, input):+ return user.has_perm('account.manage_users')++ @classmethod+ def perform_mutation(cls, root, info, email):try:user = models.User.objects.get(email=email)except ObjectDoesNotExist:- return cls(- errors=[- Error(- field='email',- message='User with this email doesn\'t exist')])+ raise ValidationError({+ 'email': 'User with this email doesn\'t exist'})site = info.context.sitesend_user_password_reset_email(user, site)@@ -407,14 +394,16 @@ class CustomerPasswordReset(BaseMutation):description = 'Resets the customer\'s password.'@classmethod- def mutate(cls, root, info, input):+ def perform_mutation(cls, root, info, input):email = input['email']try:user = models.User.objects.get(email=email)except ObjectDoesNotExist:- return+ raise ValidationError({+ 'email': 'User with this email doesn\'t exist'})site = info.context.sitesend_user_password_reset_email(user, site)+ return CustomerPasswordReset()class AddressCreate(ModelMutation):@@ -432,13 +421,11 @@ class AddressCreate(ModelMutation):model = models.Address@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):errors = []user_id = data['user_id']user = cls.get_node_or_error(info, user_id, errors, 'userId', User)- if not user:- return cls(errors=errors)- response = super().mutate(root, info, **data)+ response = super().perform_mutation(root, info, **data)if not response.errors:user.addresses.add(response.address)response.user = user@@ -473,8 +460,8 @@ class AddressUpdate(ModelMutation):return super().clean_input(info, instance, input, errors)@classmethod- def mutate(cls, root, info, **data):- response = super().mutate(root, info, **data)+ def perform_mutation(cls, root, info, **data):+ response = super().perform_mutation(root, info, **data)user = response.address.user_addresses.first()response.user = userreturn response@@ -501,7 +488,7 @@ class AddressDelete(ModelDeleteMutation):return super().clean_instance(info, instance, errors)@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):if not cls.user_is_allowed(info.context.user, data):raise PermissionDenied()@@ -549,23 +536,19 @@ class AddressSetDefault(BaseMutation):class Meta:description = 'Sets a default address for the given user.'+ def user_is_allowed(cls, user, input):+ return user.has_perm('account.manage_users')+@classmethod- @permission_required('account.manage_users')- def mutate(cls, root, info, address_id, user_id, type):+ def perform_mutation(cls, root, info, address_id, user_id, type):errors = []- address = cls.get_node_or_error(info, address_id, errors, 'addressId', Address)- if not address:- return cls(errors=errors)-+ address = cls.get_node_or_error(+ info, address_id, errors, 'addressId', Address)user = cls.get_node_or_error(info, user_id, errors, 'userId', User)- if not user:- return cls(errors=errors)if address not in user.addresses.all():- cls.add_error(- errors, 'address_id',- 'The address doesn\'t belong to that user.')- return cls(errors=errors)+ raise ValidationError({+ 'address_id': 'The address doesn\'t belong to that user.'})if type == AddressTypeEnum.BILLING.value:address_type = AddressType.BILLING@@ -598,8 +581,8 @@ class CustomerAddressCreate(ModelMutation):return user.is_authenticated@classmethod- def mutate(cls, root, info, **data):- success_response = super().mutate(root, info, **data)+ def perform_mutation(cls, root, info, **data):+ success_response = super().perform_mutation(root, info, **data)address_type = data.get('type', None)if address_type:user = info.context.user@@ -628,18 +611,18 @@ class CustomerSetDefaultAddress(BaseMutation):description = 'Sets a default address for the authenticated user.'@classmethod- @login_required- def mutate(cls, root, info, id, type):+ def user_is_allowed(cls, user, input):+ return user.is_authenticated++ @classmethod+ def perform_mutation(cls, root, info, id, type):errors = []address = cls.get_node_or_error(info, id, errors, 'id', Address)- if not address:- return cls(errors=errors)user = info.context.userif address not in user.addresses.all():- cls.add_error(- errors, 'id', 'The address doesn\'t belong to that user.')- return cls(errors=errors)+ raise ValidationError({+ 'id': 'The address doesn\'t belong to that user.'})if type == AddressTypeEnum.BILLING.value:address_type = AddressType.BILLING@@ -673,19 +656,17 @@ class UserAvatarUpdate(BaseMutation):@classmethod@staff_member_required- def mutate(cls, root, info, image):+ def perform_mutation(cls, root, info, image):user = info.context.user- errors = []image_data = info.context.FILES.get(image)- validate_image_file(cls, image_data, 'image', errors)+ validate_image_file(image_data, 'image')- if not errors:- if user.avatar:- user.avatar.delete_sized_images()- user.avatar.delete()- user.avatar = image_data- user.save()- create_user_avatar_thumbnails.delay(user_id=user.pk)+ if user.avatar:+ user.avatar.delete_sized_images()+ user.avatar.delete()+ user.avatar = image_data+ user.save()+ create_user_avatar_thumbnails.delay(user_id=user.pk)return UserAvatarUpdate(user=user, errors=errors)@@ -698,10 +679,9 @@ class UserAvatarDelete(BaseMutation):@classmethod@staff_member_required- def mutate(cls, root, info):+ def perform_mutation(cls, root, info):user = info.context.usererrors = []user.avatar.delete_sized_images()user.avatar.delete()-- return UserAvatarDelete(user=user, errors=errors)+ return UserAvatarDelete(user=user)diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex 7723d37b8c..077f4556b4 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -23,7 +23,7 @@ class AddressInput(graphene.InputObjectType):city = graphene.String(description='City.')city_area = graphene.String(description='District.')postal_code = graphene.String(description='Postal code.')- country = graphene.String(required=True, description='Country.')+ country = graphene.String(description='Country.')country_area = graphene.String(description='State or province.')phone = graphene.String(description='Phone number.')diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.pyindex 5ab42126a0..beea316641 100644--- a/saleor/graphql/account/utils.py+++ b/saleor/graphql/account/utils.py@@ -1,3 +1,5 @@+from django.core.exceptions import ValidationError+class UserDeleteMixin:class Meta:@@ -7,9 +9,10 @@ class UserDeleteMixin:def clean_instance(cls, info, instance, errors):user = info.context.userif instance == user:- cls.add_error(errors, 'id', 'You cannot delete your own account.')+ raise ValidationError({+ 'id': 'You cannot delete your own account.'})elif instance.is_superuser:- cls.add_error(errors, 'id', 'Cannot delete this account.')+ raise ValidationError({'id': 'Cannot delete this account.'})class CustomerDeleteMixin(UserDeleteMixin):@@ -20,7 +23,7 @@ class CustomerDeleteMixin(UserDeleteMixin):def clean_instance(cls, info, instance, errors):super().clean_instance(info, instance, errors)if instance.is_staff:- cls.add_error(errors, 'id', 'Cannot delete a staff account.')+ raise ValidationError({'id': 'Cannot delete a staff account.'})class StaffDeleteMixin(UserDeleteMixin):@@ -31,4 +34,4 @@ class StaffDeleteMixin(UserDeleteMixin):def clean_instance(cls, info, instance, errors):super().clean_instance(info, instance, errors)if not instance.is_staff:- cls.add_error(errors, 'id', 'Cannot delete a non-staff user.')+ raise ValidationError({'id': 'Cannot delete a non-staff user.'})diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex fc0162fec5..1faf2d23e7 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -1,13 +1,14 @@from datetime import dateimport graphene+from django.core.exceptions import ValidationErrorfrom django.db import transactionfrom ...checkout import modelsfrom ...checkout.utils import (add_variant_to_cart, add_voucher_to_cart, change_billing_address_in_cart,change_shipping_address_in_cart, create_order, get_or_create_user_cart,- get_taxes_for_cart, get_voucher_for_cart, ready_to_place_order,+ get_taxes_for_cart, get_voucher_for_cart, clean_checkout,recalculate_cart_discount, remove_voucher_from_cart)from ...core import analyticsfrom ...core.exceptions import InsufficientStock@@ -21,32 +22,24 @@ from ...shipping.models import ShippingMethod as ShippingMethodModelfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInput, Userfrom ..core.mutations import BaseMutation, ModelMutation-from ..core.types.common import Errorfrom ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethodfrom .types import Checkout, CheckoutLine+# FIXME Add tests for this functiondef clean_shipping_method(checkout, method, errors, discounts, taxes, country_code=None,remove=True):- # FIXME Add tests for this function- if not method:- return errorsif not checkout.is_shipping_required():- errors.append(- Error(- field='checkout',- message='This checkout does not requires shipping.'))+ raise ValidationError('This checkout does not requires shipping.')+if not checkout.shipping_address:- errors.append(- Error(- field='checkout',- message=(- 'Cannot choose a shipping method for a '- 'checkout without the shipping address.')))- return errors+ raise ValidationError(+ 'Cannot choose a shipping method for a checkout without the '+ 'shipping address.')+valid_methods = (ShippingMethodModel.objects.applicable_shipping_methods(price=checkout.get_subtotal(discounts, taxes).gross.amount,@@ -54,14 +47,15 @@ def clean_shipping_method(country_code=country_code or checkout.shipping_address.country.code))valid_methods = valid_methods.values_list('id', flat=True)+if method.pk not in valid_methods and not remove:- errors.append(- Error(- field='shippingMethod',- message='Shipping method cannot be used with this checkout.'))+ raise ValidationError(+ 'Shipping method cannot be used with this checkout.')+if remove:checkout.shipping_method = Nonecheckout.save(update_fields=['shipping_method'])+return errors@@ -69,7 +63,7 @@ def check_lines_quantity(variants, quantities):"""Check if stock is sufficient for each line in the list of dicts.Return list of errors."""- errors = []+ errors = {}for variant, quantity in zip(variants, quantities):try:variant.check_quantity(quantity)@@ -79,8 +73,10 @@ def check_lines_quantity(variants, quantities):+ '%(item_name)s. Only %(remaining)d remaining in stock.' % {'remaining': e.item.quantity_available,'item_name': e.item.display_product()})- errors.append(('quantity', message))- return errors+ ValidationError({'quantity': message}).update_error_dict(errors)++ if errors:+ raise ValidationError(errors)class CheckoutLineInput(graphene.InputObjectType):@@ -126,14 +122,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):ids=variant_ids, errors=errors, field='variant_id',only_type=ProductVariant)quantities = [line.get('quantity') for line in lines]- if not errors:- line_errors = check_lines_quantity(variants, quantities)- if line_errors:- for err in line_errors:- cls.add_error(errors, field=err[0], message=err[1])- else:- cleaned_input['variants'] = variants- cleaned_input['quantities'] = quantities++ check_lines_quantity(variants, quantities)++ cleaned_input['variants'] = variants+ cleaned_input['quantities'] = quantitiesdefault_shipping_address = Nonedefault_billing_address = None@@ -142,15 +135,13 @@ class CheckoutCreate(ModelMutation, I18nMixin):default_shipping_address = user.default_shipping_addressif 'shipping_address' in input:- shipping_address, errors = cls.validate_address(- input['shipping_address'], errors)+ shipping_address = cls.validate_address(input['shipping_address'])cleaned_input['shipping_address'] = shipping_addresselse:cleaned_input['shipping_address'] = default_shipping_addressif 'billing_address' in input:- billing_address, errors = cls.validate_address(- input['billing_address'], errors)+ billing_address = cls.validate_address(input['billing_address'])cleaned_input['billing_address'] = billing_addresselse:cleaned_input['billing_address'] = default_billing_address@@ -182,12 +173,12 @@ class CheckoutCreate(ModelMutation, I18nMixin):add_variant_to_cart(instance, variant, quantity)@classmethod- def mutate(cls, root, info, input):+ def perform_mutation(cls, root, info, **data):errors = []user = info.context.user- # `mutate` method is overriden to properly get or create a checkout- # instance here:+ # `perform_mutation` is overriden to properly get or create a checkout+ # instance here and abort mutation if needed.if user.is_authenticated:checkout, created = get_or_create_user_cart(user)# If user has an active checkout, return it without any@@ -200,8 +191,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):cleaned_input = cls.clean_input(info, checkout, input, errors)checkout = cls.construct_instance(checkout, cleaned_input)cls.clean_instance(checkout, errors)- if errors:- return CheckoutCreate(errors=errors)cls.save(info, checkout, cleaned_input)cls._save_m2m(info, checkout, cleaned_input)return CheckoutCreate(checkout=checkout, errors=errors)@@ -224,25 +213,20 @@ class CheckoutLinesAdd(BaseMutation):description = 'Adds a checkout line to the existing checkout.'@classmethod- def mutate(cls, root, info, checkout_id, lines, replace=False):+ def perform_mutation(cls, root, info, checkout_id, lines, replace=False):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is None:- return CheckoutLinesAdd(errors=errors)variants, quantities = None, None- if lines:- variant_ids = [line.get('variant_id') for line in lines]- variants = cls.get_nodes_or_error(- ids=variant_ids, errors=errors, field='variant_id',- only_type=ProductVariant)- quantities = [line.get('quantity') for line in lines]- if not errors:- line_errors = check_lines_quantity(variants, quantities)- if line_errors:- for err in line_errors:- cls.add_error(errors, field=err[0], message=err[1])++ variant_ids = [line.get('variant_id') for line in lines]+ variants = cls.get_nodes_or_error(+ ids=variant_ids, errors=errors, field='variant_id',+ only_type=ProductVariant)+ quantities = [line.get('quantity') for line in lines]++ check_lines_quantity(variants, quantities)# FIXME test if below function is calledclean_shipping_method(@@ -250,9 +234,6 @@ class CheckoutLinesAdd(BaseMutation):errors=errors, discounts=info.context.discounts,taxes=get_taxes_for_address(checkout.shipping_address))- if errors:- return CheckoutLinesAdd(errors=errors)-if variants and quantities:for variant, quantity in zip(variants, quantities):add_variant_to_cart(@@ -271,8 +252,8 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):description = 'Updates CheckoutLine in the existing Checkout.'@classmethod- def mutate(cls, root, info, checkout_id, lines):- return super().mutate(root, info, checkout_id, lines, replace=True)+ def perform_mutation(cls, root, info, checkout_id, lines):+ return super().perform_mutation(root, info, checkout_id, lines, replace=True)class CheckoutLineDelete(BaseMutation):@@ -288,16 +269,13 @@ class CheckoutLineDelete(BaseMutation):description = 'Deletes a CheckoutLine.'@classmethod- def mutate(cls, root, info, checkout_id, line_id):+ def perform_mutation(cls, root, info, checkout_id, line_id):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)line = cls.get_node_or_error(info, line_id, errors, 'line_id', only_type=CheckoutLine)- if checkout is None or line is None:- return CheckoutLineDelete(errors=errors)-if line and line in checkout.lines.all():line.delete()@@ -306,8 +284,6 @@ class CheckoutLineDelete(BaseMutation):checkout=checkout, method=checkout.shipping_method, errors=errors,discounts=info.context.discounts,taxes=get_taxes_for_address(checkout.shipping_address))- if errors:- return CheckoutLineDelete(errors=errors)recalculate_cart_discount(checkout, info.context.discounts, info.context.taxes)@@ -328,15 +304,14 @@ class CheckoutCustomerAttach(BaseMutation):description = 'Sets the customer as the owner of the Checkout.'@classmethod- def mutate(cls, root, info, checkout_id, customer_id):+ def perform_mutation(cls, root, info, checkout_id, customer_id):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)customer = cls.get_node_or_error(info, customer_id, errors, 'customer_id', only_type=User)- if checkout is not None and customer:- checkout.user = customer- checkout.save(update_fields=['user'])+ checkout.user = customer+ checkout.save(update_fields=['user'])return CheckoutCustomerAttach(checkout=checkout, errors=errors)@@ -350,16 +325,15 @@ class CheckoutCustomerDetach(BaseMutation):description = 'Removes the user assigned as the owner of the checkout.'@classmethod- def mutate(cls, root, info, checkout_id):+ def perform_mutation(cls, root, info, checkout_id):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is not None and not checkout.user:- cls.add_error(- errors, field=None,- message='There\'s no customer assigned to this Checkout.')- if errors:- return CheckoutCustomerDetach(errors=errors)++ # FIXME: is this error actually useful? IN this case mutation could just do nothing+ if not checkout.user:+ raise ValidationError(+ 'There\'s no customer assigned to this Checkout.')checkout.user = Nonecheckout.save(update_fields=['user'])@@ -372,6 +346,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):class Arguments:checkout_id = graphene.ID(description='ID of the Checkout.')shipping_address = AddressInput(+ required=True,description=('The mailling address to where the checkout will be shipped.'))@@ -379,25 +354,24 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):description = 'Update shipping address in the existing Checkout.'@classmethod- def mutate(cls, root, info, checkout_id, shipping_address):+ def perform_mutation(cls, root, info, checkout_id, shipping_address):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)+ shipping_address = cls.validate_address(+ shipping_address, instance=checkout.shipping_address)++ # FIXME test if below function is called+ clean_shipping_method(+ checkout, checkout.shipping_method, errors,+ info.context.discounts,+ get_taxes_for_address(shipping_address))- if checkout is not None and shipping_address:- shipping_address, errors = cls.validate_address(- shipping_address, errors, instance=checkout.shipping_address)- # FIXME test if below function is called- clean_shipping_method(- checkout, checkout.shipping_method, errors,- info.context.discounts,- get_taxes_for_address(shipping_address))- if not errors:- with transaction.atomic():- shipping_address.save()- change_shipping_address_in_cart(checkout, shipping_address)- recalculate_cart_discount(- checkout, info.context.discounts, info.context.taxes)+ with transaction.atomic():+ shipping_address.save()+ change_shipping_address_in_cart(checkout, shipping_address)+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)return CheckoutShippingAddressUpdate(checkout=checkout, errors=errors)@@ -408,25 +382,23 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):class Arguments:checkout_id = graphene.ID(description='ID of the Checkout.')billing_address = AddressInput(- description=(- 'The billing address of the checkout.'))+ required=True,+ description=('The billing address of the checkout.'))class Meta:description = 'Update billing address in the existing Checkout.'@classmethod- def mutate(cls, root, info, checkout_id, billing_address):+ def perform_mutation(cls, root, info, checkout_id, billing_address):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is not None and billing_address:- billing_address, errors = cls.validate_address(- billing_address, errors, instance=checkout.billing_address)- if not errors:- with transaction.atomic():- billing_address.save()- change_billing_address_in_cart(checkout, billing_address)+ billing_address = cls.validate_address(+ billing_address, instance=checkout.billing_address)+ with transaction.atomic():+ billing_address.save()+ change_billing_address_in_cart(checkout, billing_address)return CheckoutShippingAddressUpdate(checkout=checkout, errors=errors)@@ -441,17 +413,14 @@ class CheckoutEmailUpdate(BaseMutation):description = 'Updates email address in the existing Checkout object.'@classmethod- def mutate(cls, root, info, checkout_id, email):+ def perform_mutation(cls, root, info, checkout_id, email):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is not None:- checkout.email = email- cls.clean_instance(checkout, errors)- if errors:- return CheckoutEmailUpdate(errors=errors)- checkout.save(update_fields=['email'])+ checkout.email = email+ cls.clean_instance(checkout, errors)+ checkout.save(update_fields=['email'])return CheckoutEmailUpdate(checkout=checkout, errors=errors)@@ -467,7 +436,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):description = 'Updates the shipping address of the checkout.'@classmethod- def mutate(cls, root, info, checkout_id, shipping_method_id):+ def perform_mutation(cls, root, info, checkout_id, shipping_method_id):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)@@ -475,16 +444,14 @@ class CheckoutShippingMethodUpdate(BaseMutation):info, shipping_method_id, errors, 'shipping_method_id',only_type=ShippingMethod)- if checkout is not None and shipping_method:- clean_shipping_method(- checkout, shipping_method, errors, info.context.discounts,- info.context.taxes, remove=False)+ clean_shipping_method(+ checkout, shipping_method, errors, info.context.discounts,+ info.context.taxes, remove=False)- if not errors:- checkout.shipping_method = shipping_method- checkout.save(update_fields=['shipping_method'])- recalculate_cart_discount(- checkout, info.context.discounts, info.context.taxes)+ checkout.shipping_method = shipping_method+ checkout.save(update_fields=['shipping_method'])+ recalculate_cart_discount(+ checkout, info.context.discounts, info.context.taxes)return CheckoutShippingMethodUpdate(checkout=checkout, errors=errors)@@ -502,20 +469,13 @@ class CheckoutComplete(BaseMutation):'payment before it can be performed.')@classmethod- def mutate(cls, root, info, checkout_id):+ def perform_mutation(cls, root, info, checkout_id):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is None:- return CheckoutComplete(errors=errors)taxes = get_taxes_for_cart(checkout, info.context.taxes)- ready, checkout_error = ready_to_place_order(- checkout, taxes, info.context.discounts)- if not ready:- cls.add_error(- field=None, message=checkout_error, errors=errors)- return CheckoutComplete(errors=errors)+ clean_checkout(checkout, taxes, info.context.discounts)try:order = create_order(@@ -523,14 +483,9 @@ class CheckoutComplete(BaseMutation):tracking_code=analytics.get_client_id(info.context),discounts=info.context.discounts, taxes=taxes)except InsufficientStock:- cls.add_error(- field=None, message='Insufficient product stock.',- errors=errors)- return CheckoutComplete(errors=errors)+ raise ValidationError('Insufficient product stock.')except voucher_model.NotApplicable:- cls.add_error(- field=None, message='Voucher not applicable', errors=errors)- return CheckoutComplete(errors=errors)+ raise ValidationError('Voucher not applicable')payment = checkout.get_last_active_payment()@@ -548,7 +503,7 @@ class CheckoutComplete(BaseMutation):gateway_process_payment(payment=payment, payment_token=payment.token)except PaymentError as e:- cls.add_error(errors=errors, field=None, message=str(e))+ raise ValidationError(str(e))return CheckoutComplete(order=order, errors=errors)@@ -562,12 +517,11 @@ class CheckoutUpdateVoucher(BaseMutation):class Meta:description = (- 'Adds voucher to the checkout. '- 'Query it without voucher_code field to '- 'remove voucher from checkout.')+ 'Adds voucher to the checkout. Query it without voucher_code '+ 'field to remove voucher from checkout.')@classmethod- def mutate(cls, root, info, checkout_id, voucher_code=None):+ def perform_mutation(cls, root, info, checkout_id, voucher_code=None):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)@@ -579,21 +533,15 @@ class CheckoutUpdateVoucher(BaseMutation):voucher = voucher_model.Voucher.objects.active(date=date.today()).get(code=voucher_code)except voucher_model.Voucher.DoesNotExist:- cls.add_error(- errors=errors,- field='voucher_code',- message='Voucher with given code does not exist.')- return CheckoutUpdateVoucher(errors=errors)+ raise ValidationError({+ 'voucher_code': 'Voucher with given code does not exist.'})try:add_voucher_to_cart(voucher, checkout)except voucher_model.NotApplicable:- cls.add_error(- errors=errors,- field='voucher_code',- message='Voucher is not applicable to that checkout.')- return CheckoutUpdateVoucher(errors=errors)-+ raise ValidationError({+ 'voucher_code':+ 'Voucher is not applicable to that checkout.'})else:existing_voucher = get_voucher_for_cart(checkout)if existing_voucher:diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 40d7443f71..90e12019c4 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -3,7 +3,8 @@ from textwrap import dedentimport graphenefrom django.contrib.auth import get_user_model-from django.core.exceptions import ImproperlyConfigured, ValidationError+from django.core.exceptions import (+ ImproperlyConfigured, NON_FIELD_ERRORS, ValidationError)from django.db.models.fields.files import FileFieldfrom graphene.types.mutation import MutationOptionsfrom graphene_django.registry import get_global_registry@@ -37,6 +38,22 @@ def get_output_fields(model, return_field_name):return fields+def validation_error_to_error_type(validation_error: ValidationError) -> list:+ """Convert a ValidationError into a list of Error types."""+ err_list = []+ if hasattr(validation_error, 'error_dict'):+ # convert field errors+ for field, field_errors in validation_error.error_dict.items():+ for err in field_errors:+ field = None if field == NON_FIELD_ERRORS else snake_to_camel_case(field)+ err_list.append(Error(field=field, message=err.message))+ else:+ # convert non-field errors+ for err in validation_error.error_list:+ err_list.append(Error(message=err.message))+ return err_list++class ModelMutationOptions(MutationOptions):exclude = Nonemodel = None@@ -63,22 +80,6 @@ class BaseMutation(graphene.Mutation):cls._meta.arguments.update(arguments)cls._meta.fields.update(fields)- @classmethod- def add_error(cls, errors, field, message):- """Add a mutation user error.-- `errors` is the list of errors that happened during the execution of- the mutation. `field` is the name of an input field the error is- related to. `None` value is allowed and it indicates that the error- is general and is not related to any of the input fields. `message`- is the actual error message to be returned in the response.-- As a result of this method, the `errors` list is updated with an Error- object to be returned as mutation result.- """- field = snake_to_camel_case(field)- errors.append(Error(field=field, message=message))-@classmethoddef get_node_or_error(cls, info, global_id, errors, field, only_type=None):if not global_id:@@ -89,11 +90,11 @@ class BaseMutation(graphene.Mutation):node = graphene.Node.get_node_from_global_id(info, global_id, only_type)except (AssertionError, GraphQLError) as e:- cls.add_error(errors, field, str(e))+ raise ValidationError({field: str(e)})else:if node is None:- message = "Couldn't resolve to a node: %s" % global_id- cls.add_error(errors, field, message)+ raise ValidationError({+ field: "Couldn't resolve to a node: %s" % global_id})return node@classmethod@@ -102,7 +103,9 @@ class BaseMutation(graphene.Mutation):try:instances = get_nodes(ids, only_type)except GraphQLError as e:- cls.add_error(field=field, message=str(e), errors=errors)+ # FIXME: czy zawsze tutaj powinien lecieć ValidationError? moze+ # tylko jak nie znaleziono danego IDka?+ raise ValidationError({field: str(e)})return instances@classmethod@@ -115,15 +118,18 @@ class BaseMutation(graphene.Mutation):"""try:instance.full_clean()- except ValidationError as validation_errors:- message_dict = validation_errors.message_dict- for field in message_dict:- if hasattr(cls._meta,- 'exclude') and field in cls._meta.exclude:- continue- for message in message_dict[field]:- field = snake_to_camel_case(field)- cls.add_error(errors, field, message)+ except ValidationError as error:+ if hasattr(cls._meta, 'exclude'):+ # Ignore validation errors for fields that are specified as+ # excluded.+ new_error_dict = {}+ for field, errors in error.error_dict.items():+ if field not in cls._meta.exclude:+ new_error_dict[field] = errors+ error.error_dict = new_error_dict++ if error.error_dict:+ raise error@classmethoddef construct_instance(cls, instance, cleaned_data):@@ -154,6 +160,35 @@ class BaseMutation(graphene.Mutation):f.save_form_data(instance, data)return instance+ @classmethod+ def user_is_allowed(cls, user, input):+ """Determine whether user has rights to perform this mutation.++ Default implementation assumes that user is allowed to perform any+ mutation. By overriding this method, you can restrict access to it.+ `user` is the User instance associated with the request and `input` is+ the input data provided as mutation arguments.+ """+ return True++ @classmethod+ def mutate(cls, root, info, **data):+ if not cls.user_is_allowed(info.context.user, data):+ raise PermissionDenied()++ try:+ response = cls.perform_mutation(root, info, **data)+ if response.errors is None:+ response.errors = []+ return response+ except ValidationError as e:+ errors = validation_error_to_error_type(e)+ return cls(errors=errors)++ @classmethod+ def perform_mutation(cls, root, info, **data):+ pass+class ModelMutation(BaseMutation):class Meta:@@ -258,17 +293,6 @@ class ModelMutation(BaseMutation):if f.name in cleaned_data and cleaned_data[f.name] is not None:f.save_form_data(instance, cleaned_data[f.name])- @classmethod- def user_is_allowed(cls, user, input):- """Determine whether user has rights to perform this mutation.-- Default implementation assumes that user is allowed to perform any- mutation. By overriding this method, you can restrict access to it.- `user` is the User instance associated with the request and `input` is- the input data provided as mutation arguments.- """- return True-@classmethoddef success_response(cls, instance):"""Return a success response."""@@ -279,7 +303,18 @@ class ModelMutation(BaseMutation):instance.save()@classmethod- def mutate(cls, root, info, **data):+ def get_instance(cls, info, errors, **data):+ object_id = data.get('id')+ if object_id:+ model_type = registry.get_type_for_model(cls._meta.model)+ instance = cls.get_node_or_error(+ info, object_id, errors, 'id', model_type)+ else:+ instance = cls._meta.model()+ return instance++ @classmethod+ def perform_mutation(cls, root, info, **data):"""Perform model mutation.Depending on the input data, `mutate` either creates a new instance or@@ -287,30 +322,14 @@ class ModelMutation(BaseMutation):that this is an "update" mutation. Otherwise, a new instance iscreated based on the model associated with this mutation."""- if not cls.user_is_allowed(info.context.user, data):- raise PermissionDenied()-- id = data.get('id')- input = data.get('input')+ errors = [] # Initialize the errors list.+ instance = cls.get_instance(info, errors, **data)- # Initialize the errors list.- errors = []+ input_data = data.get('input') # FIXME: pass data to clean_input- # Initialize model instance based on presence of `id` attribute.- if id:- model_type = registry.get_type_for_model(cls._meta.model)- instance = cls.get_node_or_error(- info, id, errors, 'id', model_type)- else:- instance = cls._meta.model()- if errors:- return cls(errors=errors)-- cleaned_input = cls.clean_input(info, instance, input, errors)- instance = cls.construct_instance(instance, cleaned_input)- cls.clean_instance(instance, errors)- if errors:- return cls(errors=errors)+ cleaned_input = cls.clean_input(info, instance, input_data, errors)+ instance = cls.construct_instance(instance, cleaned_input) # FIXME: maybe rename to `populate_instance`+ cls.clean_instance(instance, errors) # FIXME: maybe rename to `pre_save_instance` ?cls.save(info, instance, cleaned_input)cls._save_m2m(info, instance, cleaned_input)return cls.success_response(instance)@@ -329,7 +348,7 @@ class ModelDeleteMutation(ModelMutation):"""@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):"""Perform a mutation that deletes a model instance."""if not cls.user_is_allowed(info.context.user, data):raise PermissionDenied()diff --git a/saleor/graphql/core/utils.py b/saleor/graphql/core/utils.pyindex a2f1fe26d1..e607025aa2 100644--- a/saleor/graphql/core/utils.py+++ b/saleor/graphql/core/utils.py@@ -1,3 +1,6 @@+from django.core.exceptions import ValidationError++def clean_seo_fields(data):"""Extract and assign seo fields to given dictionary."""seo_fields = data.pop('seo', None)@@ -19,7 +22,7 @@ def str_to_enum(name):return name.replace(' ', '_').replace('-', '_').upper()-def validate_image_file(mutation_cls, file, field_name, errors):+def validate_image_file(file, field_name):"""Validate if the file is an image."""if not file.content_type.startswith('image/'):- mutation_cls.add_error(errors, field_name, 'Invalid file type')+ raise ValidationError({field_name: 'Invalid file type.'})diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.pyindex 789de59ba7..dde06022ae 100644--- a/saleor/graphql/discount/mutations.py+++ b/saleor/graphql/discount/mutations.py@@ -1,5 +1,4 @@import graphene-from graphql_jwt.decorators import permission_requiredfrom ...discount import modelsfrom ...discount.utils import generate_voucher_code@@ -166,8 +165,11 @@ class VoucherAddCatalogues(VoucherBaseCatalogueMutation):description = 'Adds products, categories, collections to a voucher.'@classmethod- @permission_required('discount.manage_discounts')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('discount.manage_discounts')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []voucher = cls.get_node_or_error(info, id, errors, 'voucherId', only_type=Voucher)@@ -182,8 +184,11 @@ class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):'Removes products, categories, collections from a voucher.')@classmethod- @permission_required('discount.manage_discounts')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('discount.manage_discounts')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []voucher = cls.get_node_or_error(info, id, errors, 'voucherId', only_type=Voucher)@@ -275,8 +280,11 @@ class SaleAddCatalogues(SaleBaseCatalogueMutation):description = 'Adds products, categories, collections to a voucher.'@classmethod- @permission_required('discount.manage_discounts')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('discount.manage_discounts')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []sale = cls.get_node_or_error(info, id, errors, 'saleId', only_type=Sale)@@ -290,8 +298,11 @@ class SaleRemoveCatalogues(SaleBaseCatalogueMutation):description = 'Removes products, categories, collections from a sale.'@classmethod- @permission_required('discount.manage_discounts')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('discount.manage_discounts')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []sale = cls.get_node_or_error(info, id, errors, 'saleId', only_type=Sale)diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.pyindex 88d8f3d1d9..0ccb1ecfcd 100644--- a/saleor/graphql/menu/mutations.py+++ b/saleor/graphql/menu/mutations.py@@ -1,7 +1,7 @@from textwrap import dedentimport graphene-from graphql_jwt.decorators import permission_required+from django.core.exceptions import ValidationErrorfrom ...menu import modelsfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation@@ -60,14 +60,15 @@ class MenuCreate(ModelMutation):def clean_input(cls, info, instance, input, errors):cleaned_input = super().clean_input(info, instance, input, errors)items = []+ errors = {}for item in cleaned_input.get('items', []):category = item.get('category')collection = item.get('collection')page = item.get('page')url = item.get('url')if len([i for i in [category, collection, page, url] if i]) > 1:- cls.add_error(- errors, 'items', 'More than one item provided.')+ ValidationError({+ 'items': 'More than one item provided.'}).update_error_dict(errors)else:if category:category = cls.get_node_or_error(@@ -83,8 +84,13 @@ class MenuCreate(ModelMutation):info, page, errors, 'items', only_type=Page)item['page'] = pageelif not url:- cls.add_error(errors, 'items', 'No menu item provided.')+ ValidationError({+ 'items': 'No menu item provided.'}).update_error_dict(errors)items.append(item)++ if errors:+ raise ValidationError(errors)+cleaned_input['items'] = itemsreturn cleaned_input@@ -151,9 +157,7 @@ class MenuItemCreate(ModelMutation):cleaned_input.get('url'), cleaned_input.get('category')]items = [item for item in items if item is not None]if len(items) > 1:- cls.add_error(- errors=errors,- field='items', message='More than one item provided.')+ raise ValidationError({'items': 'More than one item provided.'})return cleaned_input@@ -203,8 +207,7 @@ class AssignNavigation(BaseMutation):menu = graphene.Field(Menu, description='Assigned navigation menu.')class Arguments:- menu = graphene.ID(- description='ID of the menu.')+ menu = graphene.ID(description='ID of the menu.') # FIXME: required=True?navigation_type = NavigationType(description='Type of the navigation bar to assign the menu to.',required=True)@@ -212,22 +215,26 @@ class AssignNavigation(BaseMutation):class Meta:description = 'Assigns storefront\'s navigation menus.'+ def user_is_allowed(cls, instance, input):+ return instance.has_perms([+ 'menu.manage_menus', 'site.manage_settings'])+@classmethod- @permission_required(['menu.manage_menus', 'site.manage_settings'])- def mutate(cls, root, info, navigation_type, menu=None):+ def perform_mutation(cls, root, info, navigation_type, menu=None):errors = []site_settings = info.context.site.settingsif menu is not None:menu = cls.get_node_or_error(info, menu, errors=errors, field='menu')- if not errors:- if navigation_type == NavigationType.MAIN:- site_settings.top_menu = menu- site_settings.save(update_fields=['top_menu'])- elif navigation_type == NavigationType.SECONDARY:- site_settings.bottom_menu = menu- site_settings.save(update_fields=['bottom_menu'])- else:- raise AssertionError(- 'Unknown navigation type: %s' % navigation_type)++ if navigation_type == NavigationType.MAIN:+ site_settings.top_menu = menu+ site_settings.save(update_fields=['top_menu'])+ elif navigation_type == NavigationType.SECONDARY:+ site_settings.bottom_menu = menu+ site_settings.save(update_fields=['bottom_menu'])+ else:+ raise AssertionError(+ 'Unknown navigation type: %s' % navigation_type)+return AssignNavigation(menu=menu, errors=errors)diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.pyindex 6285f9b80f..e2880fbc7a 100644--- a/saleor/graphql/order/bulk_mutations/draft_orders.py+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py@@ -1,4 +1,5 @@import graphene+from django.core.exceptions import ValidationErrorfrom ....order import OrderStatus, modelsfrom ...core.mutations import ModelBulkDeleteMutation@@ -18,7 +19,7 @@ class DraftOrderBulkDelete(ModelBulkDeleteMutation):@classmethoddef clean_instance(cls, info, instance, errors):if instance.status != OrderStatus.DRAFT:- cls.add_error(errors, 'id', 'Cannot delete non-draft orders.')+ raise ValidationError({'id': 'Cannot delete non-draft orders.'})@classmethoddef user_is_allowed(cls, user, input):diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 98c8886002..f668abc973 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -1,8 +1,8 @@from textwrap import dedentimport graphene+from django.core.exceptions import ValidationErrorfrom graphene.types import InputObjectType-from graphql_jwt.decorators import permission_requiredfrom ....account.models import Userfrom ....core.exceptions import InsufficientStock@@ -91,14 +91,12 @@ class DraftOrderCreate(ModelMutation, I18nMixin):'billing_address'] = user.default_billing_addressif shipping_address:- shipping_address, errors = cls.validate_address(- shipping_address, errors, 'shipping_address',- instance=instance.shipping_address)+ shipping_address = cls.validate_address(+ shipping_address, instance=instance.shipping_address)cleaned_input['shipping_address'] = shipping_addressif billing_address:- billing_address, errors = cls.validate_address(- billing_address, errors, 'billing_address',- instance=instance.billing_address)+ billing_address = cls.validate_address(+ billing_address, instance=instance.billing_address)cleaned_input['billing_address'] = billing_addressreturn cleaned_input@@ -177,8 +175,11 @@ class DraftOrderComplete(BaseMutation):order.user = None@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)if order:@@ -232,15 +233,15 @@ class DraftOrderLinesCreate(BaseMutation):description = 'Create order lines for a draft order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, input):- errors = []+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, input):+ errors = {}order = cls.get_node_or_error(info, id, errors, 'id', Order)- if not order:- return DraftOrderLinesCreate(errors=errors)if order.status != OrderStatus.DRAFT:- cls.add_error(- errors, 'order_id', 'Only draft orders can be edited.')+ raise ValidationError({'id': 'Only draft orders can be edited.'})lines = []for input_line in input:@@ -254,9 +255,8 @@ class DraftOrderLinesCreate(BaseMutation):order, variant, quantity, allow_overselling=True)lines.append(line)else:- cls.add_error(- errors, 'quantity',- 'Ensure this value is greater than or equal to 1.')+ ValidationError({+ 'quantity': 'Ensure this value is greater than or equal to 1.'}).update_error_dict(errors)recalculate_order(order)return DraftOrderLinesCreate(@@ -276,24 +276,21 @@ class DraftOrderLineDelete(BaseMutation):description = 'Deletes an order line from a draft order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id):- errors = []- line = cls.get_node_or_error(info, id, errors, 'id', OrderLine)- if not line:- return DraftOrderLineDelete(errors=errors)+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')+ @classmethod+ def perform_mutation(cls, root, info, id):+ line = cls.get_node_or_error(info, id, [], 'id', OrderLine)order = line.orderif order.status != OrderStatus.DRAFT:- cls.add_error(- errors, 'id', 'Only draft orders can be edited.')- if not errors:- db_id = line.id- delete_order_line(line)- line.id = db_id- recalculate_order(order)- return DraftOrderLineDelete(- errors=errors, order=order, order_line=line)+ raise ValidationError({'id': 'Only draft orders can be edited.'})++ db_id = line.id+ delete_order_line(line)+ line.id = db_id+ recalculate_order(order)+ return DraftOrderLineDelete(order=order, order_line=line)class DraftOrderLineUpdate(ModelMutation):@@ -318,15 +315,13 @@ class DraftOrderLineUpdate(ModelMutation):def clean_input(cls, info, instance, input, errors):cleaned_input = super().clean_input(info, instance, input, errors)if instance.order.status != OrderStatus.DRAFT:- cls.add_error(- errors, 'id', 'Only draft orders can be edited.')+ raise ValidationError({'id': 'Only draft orders can be edited.'})quantity = input['quantity']if quantity <= 0:- cls.add_error(- errors, 'quantity',- 'Ensure this value is greater than or equal to 1.')-+ raise ValidationError({+ 'quantity':+ 'Ensure this value is greater than or equal to 1.'})return cleaned_input@classmethoddiff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex d6e5dbd408..2883a6ddac 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -1,8 +1,8 @@from textwrap import dedentimport graphene+from django.core.exceptions import ValidationErrorfrom django.utils.translation import npgettext_lazy, pgettext_lazy-from graphql_jwt.decorators import permission_requiredfrom ....order import OrderEvents, OrderEventsEmails, modelsfrom ....order.emails import send_fulfillment_confirmation@@ -68,19 +68,21 @@ class FulfillmentCreate(BaseMutation):@classmethoddef clean_lines(cls, order_lines, quantities, errors):- if errors:- return errors-+ errors = {}for order_line, quantity in zip(order_lines, quantities):if quantity > order_line.quantity_unfulfilled:msg = npgettext_lazy('Fulfill order line mutation error',- 'Only %(quantity)d item remaining to fulfill.',- 'Only %(quantity)d items remaining to fulfill.',+ 'Only %(quantity)d item remaining to fulfill: %(order_line)s.',+ 'Only %(quantity)d items remaining to fulfill: %(order_line)s.',number='quantity') % {'quantity': order_line.quantity_unfulfilled,'order_line': order_line}- cls.add_error(errors, order_line, msg)+ ValidationError({+ 'order_line_id': msg}).update_error_dict(errors)+ ValidationError(msg).update_error_dict(errors)+ if errors:+ raise ValidationError(errors)return errors@classmethod@@ -94,11 +96,9 @@ class FulfillmentCreate(BaseMutation):cls.clean_lines(order_lines, quantities, errors)if sum(quantities) <= 0:- cls.add_error(- errors, 'lines', 'Total quantity must be larger than 0.')+ raise ValidationError({+ 'lines': 'Total quantity must be larger than 0.'})- if errors:- return cls(errors=errors)input['order_lines'] = order_linesinput['quantities'] = quantitiesreturn input@@ -130,19 +130,17 @@ class FulfillmentCreate(BaseMutation):return fulfillment@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, order, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, order, input):errors = []- order = cls.get_node_or_error(- info, order, errors, 'order', Order)- if errors:- return cls(errors=errors)+ order = cls.get_node_or_error(info, order, errors, 'order', Order)fulfillment = models.Fulfillment(tracking_number=input.pop('tracking_number', None) or '',order=order)cleaned_input = cls.clean_input(input, errors)- if errors:- return cls(errors=errors)fulfillment = cls.save(info.context.user, fulfillment, order, cleaned_input)return FulfillmentCreate(@@ -166,13 +164,14 @@ class FulfillmentUpdateTracking(BaseMutation):description = 'Updates a fulfillment for an order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []fulfillment = cls.get_node_or_error(info, id, errors, 'id', Fulfillment)- if errors:- return cls(errors=errors)tracking_number = input.get('tracking_number') or ''fulfillment.tracking_number = tracking_numberfulfillment.save()@@ -204,24 +203,24 @@ class FulfillmentCancel(BaseMutation):and optionally restocks items.""")@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, input):- errors = []+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutatation(cls, root, info, id, input):restock = input.get('restock')- fulfillment = cls.get_node_or_error(- info, id, errors, 'id', Fulfillment)- if fulfillment:- order = fulfillment.order- if not fulfillment.can_edit():- err_msg = pgettext_lazy(- 'Cancel fulfillment mutation error',- 'This fulfillment can\'t be canceled')- cls.add_error(errors, 'fulfillment', err_msg)+ fulfillment = cls.get_node_or_error(info, id, [], 'id', Fulfillment)- if errors:- return cls(errors=errors)+ if not fulfillment.can_edit():+ err_msg = pgettext_lazy(+ 'Cancel fulfillment mutation error',+ 'This fulfillment can\'t be canceled')+ raise ValidationError({'fulfillment': err_msg})+ order = fulfillment.ordercancel_fulfillment(fulfillment, restock)++ # FIXME: move event creation to `cancel_fulfillment`if restock:order.events.create(parameters={'quantity': fulfillment.get_total_quantity()},diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 4072942679..27b5fdf3b3 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -1,5 +1,5 @@import graphene-from graphql_jwt.decorators import permission_required+from django.core.exceptions import ValidationErrorfrom ....account.models import Userfrom ....core.utils.taxes import ZERO_TAXED_MONEY@@ -13,23 +13,17 @@ from ....shipping.models import ShippingMethod as ShippingMethodModelfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutationfrom ...core.scalars import Decimal-from ...core.types.common import Errorfrom ...order.mutations.draft_orders import DraftOrderUpdatefrom ...order.types import Order, OrderEventfrom ...shipping.types import ShippingMethod-def clean_order_update_shipping(order, method, errors):- if not method:- return errors+def clean_order_update_shipping(order, method):if not order.shipping_address:- errors.append(- Error(- field='order',- message=(- 'Cannot choose a shipping method for an '- 'order without the shipping address.')))- return errors+ raise ValidationError({+ 'order': 'Cannot choose a shipping method for an order without '+ 'the shipping address.'})+valid_methods = (ShippingMethodModel.objects.applicable_shipping_methods(price=order.get_subtotal().gross.amount,@@ -37,56 +31,36 @@ def clean_order_update_shipping(order, method, errors):country_code=order.shipping_address.country.code))valid_methods = valid_methods.values_list('id', flat=True)if method.pk not in valid_methods:- errors.append(- Error(- field='shippingMethod',- message='Shipping method cannot be used with this order.'))- return errors+ raise ValidationError({+ 'shipping_method':+ 'Shipping method cannot be used with this order.'})-def clean_order_cancel(order, errors):+def clean_order_cancel(order):if order and not order.can_cancel():- errors.append(- Error(- field='order',- message='This order can\'t be canceled.'))- return errors+ raise ValidationError({'order': 'This order can\'t be canceled.'})-def clean_order_capture(payment, amount, errors):+def clean_order_capture(payment, amount):if not payment:- errors.append(- Error(- field='payment',- message='There\'s no payment associated with the order.'))- return errors+ raise ValidationError({+ 'payment': 'There\'s no payment associated with the order.'})if not payment.is_active:- errors.append(- Error(- field='payment',- message='Only pre-authorized payments can be captured'))- return errors+ raise ValidationError({+ 'payment': 'Only pre-authorized payments can be captured'})-def clean_void_payment(payment, errors):+def clean_void_payment(payment):"""Check for payment errors."""if not payment.is_active:- errors.append(- Error(field='payment',- message='Only pre-authorized payments can be voided'))- try:- gateway_void(payment)- except (PaymentError, ValueError) as e:- errors.append(Error(field='payment', message=str(e)))- return errors+ raise ValidationError({+ 'payment': 'Only pre-authorized payments can be voided'})-def clean_refund_payment(payment, amount, errors):+def clean_refund_payment(payment, amount):if payment.gateway == CustomPaymentChoices.MANUAL:- errors.append(- Error(field='payment',- message='Manual payments can not be refunded.'))- return errors+ raise ValidationError({+ 'payment': 'Manual payments can not be refunded.'})class OrderUpdateInput(graphene.InputObjectType):@@ -140,17 +114,20 @@ class OrderUpdateShipping(BaseMutation):description = 'Updates a shipping method of the order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)if not input['shipping_method']:if not order.is_draft() and order.is_shipping_required():- cls.add_error(- errors, 'shippingMethod',- 'Shipping method is required for this order.')- return OrderUpdateShipping(errors=errors)+ raise ValidationError({+ 'shipping_method':+ 'Shipping method is required for this order.'})+order.shipping_method = Noneorder.shipping_price = ZERO_TAXED_MONEYorder.shipping_method_name = None@@ -163,9 +140,8 @@ class OrderUpdateShipping(BaseMutation):method = cls.get_node_or_error(info, input['shipping_method'], errors,'shipping_method', ShippingMethod)- clean_order_update_shipping(order, method, errors)- if errors:- return OrderUpdateShipping(errors=errors)++ clean_order_update_shipping(order, method)order.shipping_method = methodorder.shipping_price = method.get_total(info.context.taxes)@@ -197,13 +173,13 @@ class OrderAddNote(BaseMutation):description = 'Adds note to the order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)- if errors:- return OrderAddNote(errors=errors)-event = order.events.create(type=OrderEvents.NOTE_ADDED.value,user=info.context.user,@@ -226,14 +202,14 @@ class OrderCancel(BaseMutation):description = 'Cancel an order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, restock):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, restock):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)- clean_order_cancel(order, errors)- if errors:- return OrderCancel(errors=errors)-+ clean_order_cancel(order)cancel_order(order=order, restock=restock)if restock:order.events.create(@@ -257,17 +233,17 @@ class OrderMarkAsPaid(BaseMutation):description = 'Mark order as manually paid.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)- if order is not None:- try:- clean_mark_order_as_paid(order)- except PaymentError as e:- errors.append(Error(field='payment', message=str(e)))- if errors:- return OrderMarkAsPaid(errors=errors)+ try:+ clean_mark_order_as_paid(order)+ except PaymentError as e:+ raise ValidationError({'payment': str(e)})mark_order_as_paid(order, info.context.user)return OrderMarkAsPaid(order=order)@@ -285,25 +261,24 @@ class OrderCapture(BaseMutation):description = 'Capture an order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, amount):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, amount):errors = []if amount <= 0:- cls.add_error(- errors, 'amount', 'Amount should be a positive number.')- return OrderCapture(errors=errors)+ raise ValidationError({+ 'amount': 'Amount should be a positive number.'})order = cls.get_node_or_error(info, id, errors, 'id', Order)payment = order.get_last_payment()- clean_order_capture(payment, amount, errors)+ clean_order_capture(payment, amount)try:gateway_capture(payment, amount)except PaymentError as e:- errors.append(Error(field='payment', message=str(e)))-- if errors:- return OrderCapture(errors=errors)+ raise ValidationError({'payment': str(e)})order.events.create(parameters={'amount': amount},@@ -323,16 +298,19 @@ class OrderVoid(BaseMutation):description = 'Void an order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id):errors = []order = cls.get_node_or_error(info, id, errors, 'id', Order)- if order:- payment = order.get_last_payment()- clean_void_payment(payment, errors)-- if errors:- return OrderVoid(errors=errors)+ payment = order.get_last_payment()+ clean_void_payment(payment)+ try:+ gateway_void(payment)+ except (PaymentError, ValueError) as e:+ raise ValidationError({'payment': str(e)})order.events.create(type=OrderEvents.PAYMENT_VOIDED.value,user=info.context.user)@@ -352,25 +330,24 @@ class OrderRefund(BaseMutation):description = 'Refund an order.'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, id, amount):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, id, amount):errors = []if amount <= 0:- cls.add_error(- errors, 'amount', 'Amount should be a positive number.')- return OrderRefund(errors=errors)+ raise ValidationError({+ 'amount': 'Amount should be a positive number.'})order = cls.get_node_or_error(info, id, errors, 'id', Order)- if order:- payment = order.get_last_payment()- clean_refund_payment(payment, amount, errors)- try:- gateway_refund(payment, amount)- except PaymentError as e:- errors.append(Error(field='payment', message=str(e)))-- if errors:- return OrderRefund(errors=errors)+ payment = order.get_last_payment()+ clean_refund_payment(payment, amount)++ try:+ gateway_refund(payment, amount)+ except PaymentError as e:+ raise ValidationError({'payment': str(e)})order.events.create(type=OrderEvents.PAYMENT_REFUNDED.value,diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex a3752464e8..d406156b5e 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -2,6 +2,7 @@ from textwrap import dedentimport graphenefrom django.conf import settings+from django.core.exceptions import ValidationErrorfrom graphql_jwt.decorators import permission_requiredfrom ...core.utils import get_client_ip@@ -53,33 +54,28 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):description = 'Create a new payment for given checkout.'@classmethod- def mutate(cls, root, info, checkout_id, input):+ def perform_mutation(cls, root, info, checkout_id, input):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)- if checkout is None:- return CheckoutPaymentCreate(errors=errors)billing_address = checkout.billing_addressif 'billing_address' in input:- billing_address, errors = cls.validate_address(- input['billing_address'], errors, 'billing_address')+ billing_address = cls.validate_address(input['billing_address'])if billing_address is None:- cls.add_error(- errors, 'billingAddress',- 'No billing address associated with this checkout.')- return CheckoutPaymentCreate(errors=errors)+ raise ValidationError({+ 'billing_address':+ 'No billing address associated with this checkout.'})checkout_total = checkout.get_total(discounts=info.context.discounts,taxes=get_taxes_for_address(checkout.billing_address))amount = input.get('amount', checkout_total)if amount < checkout_total.gross.amount:- cls.add_error(- errors, 'amount',- 'Partial payments are not allowed, '- 'amount should be equal checkout\'s total.')- return CheckoutPaymentCreate(errors=errors)+ raise ValidationError({+ 'amount':+ 'Partial payments are not allowed, amount should be '+ 'equal checkout\'s total.'})extra_data = {'customer_user_agent': info.context.META.get('HTTP_USER_AGENT')}@@ -94,7 +90,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):extra_data=extra_data,customer_ip_address=get_client_ip(info.context),checkout=checkout)- return CheckoutPaymentCreate(payment=payment, errors=errors)+ return CheckoutPaymentCreate(payment=payment)class PaymentCapture(BaseMutation):@@ -108,43 +104,42 @@ class PaymentCapture(BaseMutation):description = 'Captures the authorized payment amount'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, payment_id, amount=None):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, payment_id, amount=None):errors = []payment = cls.get_node_or_error(info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment:- return PaymentCapture(errors=errors)-try:gateway_capture(payment, amount)- except PaymentError as exc:- msg = str(exc)- cls.add_error(field=None, message=msg, errors=errors)- return PaymentCapture(payment=payment, errors=errors)+ except PaymentError as e:+ raise ValidationError(str(e))+ return PaymentCapture(payment=payment)class PaymentRefund(PaymentCapture):++ class Meta:+ description = 'Refunds the captured payment amount'++ @classmethod+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')+@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, payment_id, amount=None):+ def perform_mutation(cls, root, info, payment_id, amount=None):errors = []payment = cls.get_node_or_error(info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment:- return PaymentRefund(errors=errors)-try:gateway_refund(payment, amount=amount)- except PaymentError as exc:- msg = str(exc)- cls.add_error(field=None, message=msg, errors=errors)- return PaymentRefund(payment=payment, errors=errors)-- class Meta:- description = 'Refunds the captured payment amount'+ except PaymentError as e:+ raise ValidationError(str(e))+ return PaymentRefund(payment=payment)class PaymentVoid(BaseMutation):@@ -157,18 +152,17 @@ class PaymentVoid(BaseMutation):description = 'Voids the authorized payment'@classmethod- @permission_required('order.manage_orders')- def mutate(cls, root, info, payment_id, amount=None):+ def user_is_allowed(cls, user, input):+ return user.has_perm('order.manage_orders')++ @classmethod+ def perform_mutation(cls, root, info, payment_id, amount=None):errors = []payment = cls.get_node_or_error(info, payment_id, errors, 'payment_id', only_type=Payment)- if not payment:- return PaymentVoid(errors=errors)-try:gateway_void(payment)- except PaymentError as exc:- msg = str(exc)- cls.add_error(field=None, message=msg, errors=errors)- return PaymentVoid(payment=payment, errors=errors)+ except PaymentError as e:+ raise ValidationError(str(e))+ return PaymentVoid(payment=payment)diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 7a6b72c3df..66405991ee 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -2,7 +2,6 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.template.defaultfilters import slugify-from graphql_jwt.decorators import permission_requiredfrom ....product import modelsfrom ...core.mutations import ModelDeleteMutation, ModelMutation@@ -46,14 +45,14 @@ class AttributeMixin:msg = ('Value %s already exists within this attribute.' %value_data['name'])- cls.add_error(errors, cls.ATTRIBUTE_VALUES_FIELD, msg)+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})new_slugs = [slugify(value_data['name']) for value_data in values_input]if len(set(new_slugs)) != len(new_slugs):- cls.add_error(- errors, cls.ATTRIBUTE_VALUES_FIELD,- 'Provided values are not unique.')+ raise ValidationError({+ cls.ATTRIBUTE_VALUES_FIELD:+ 'Provided values are not unique.'})@classmethoddef clean_values(cls, cleaned_input, attribute, errors):@@ -74,9 +73,9 @@ class AttributeMixin:for field in validation_errors.message_dict:if field == 'attribute':continue- for message in validation_errors.message_dict[field]:- cls.add_error(- errors, cls.ATTRIBUTE_VALUES_FIELD, message)+ for msg in validation_errors.message_dict[field]:+ # FIXME :HANDLE this+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})cls.check_unique_values(values_input, attribute, errors)return errors@@ -88,8 +87,7 @@ class AttributeMixin:elif instance.pk:slug = instance.slugelse:- cls.add_error(errors, 'name', 'This field cannot be blank.')- return cleaned_input+ raise ValidationError({'name': 'This field cannot be blank.'})cleaned_input['slug'] = slugif not product_type:@@ -100,9 +98,8 @@ class AttributeMixin:| Q(product_variant_type=product_type))query = query.exclude(pk=getattr(instance, 'pk', None))if query.exists():- cls.add_error(- errors, 'name',- 'Attribute already exists within this product type.')+ raise ValidationError({+ 'name': 'Attribute already exists within this product type.'})return cleaned_input@classmethod@@ -139,24 +136,22 @@ class AttributeCreate(AttributeMixin, ModelMutation):model = models.Attribute@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, id, type, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, id, type, input):errors = []product_type = cls.get_node_or_error(info, id, errors, 'id', ProductType)- if not product_type:- return AttributeCreate(errors=errors)instance = models.Attribute()cleaned_input = cls.clean_input(info, instance, input, errors)cls.clean_attribute(instance, cleaned_input, errors, product_type=product_type)cls.clean_values(cleaned_input, instance, errors)-instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(instance, errors)- if errors:- return AttributeCreate(errors=errors)instance.save()if type == AttributeTypeEnum.VARIANT.name:@@ -164,8 +159,7 @@ class AttributeCreate(AttributeMixin, ModelMutation):else:product_type.product_attributes.add(instance)cls._save_m2m(info, instance, cleaned_input)- return AttributeCreate(- attribute=instance, product_type=product_type, errors=errors)+ return AttributeCreate(attribute=instance, product_type=product_type)class AttributeUpdate(AttributeMixin, ModelMutation):@@ -194,7 +188,8 @@ class AttributeUpdate(AttributeMixin, ModelMutation):for value in remove_values:if value.attribute != instance:msg = 'Value %s does not belong to this attribute.' % value- cls.add_error(errors, 'remove_values', msg)+ # FIXME: HANDLE THIS+ raise ValidationError({'remove_values': msg})return remove_values@classmethod@@ -204,8 +199,11 @@ class AttributeUpdate(AttributeMixin, ModelMutation):attribute_value.delete()@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []instance = cls.get_node_or_error(info, id, errors, 'id', Attribute)@@ -215,16 +213,13 @@ class AttributeUpdate(AttributeMixin, ModelMutation):instance, cleaned_input, errors, product_type=product_type)cls.clean_values(cleaned_input, instance, errors)cls.clean_remove_values(cleaned_input, instance, errors)-instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(instance, errors)- if errors:- return AttributeUpdate(errors=errors)instance.save()cls._save_m2m(info, instance, cleaned_input)return AttributeUpdate(- attribute=instance, product_type=product_type, errors=errors)+ attribute=instance, product_type=product_type)class AttributeDelete(ModelDeleteMutation):@@ -273,8 +268,11 @@ class AttributeValueCreate(ModelMutation):return cleaned_input@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, attribute_id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, attribute_id, input):errors = []attribute = cls.get_node_or_error(info, attribute_id, errors, 'id', Attribute)@@ -283,13 +281,11 @@ class AttributeValueCreate(ModelMutation):cleaned_input = cls.clean_input(info, instance, input, errors)instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(instance, errors)- if errors:- return cls(errors=errors)instance.save()cls._save_m2m(info, instance, cleaned_input)return AttributeValueCreate(- attribute=attribute, attributeValue=instance, errors=errors)+ attribute=attribute, attributeValue=instance)class AttributeValueUpdate(ModelMutation):diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex a9989b19ce..af2f1146b5 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1,10 +1,10 @@from textwrap import dedentimport graphene+from django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.template.defaultfilters import slugifyfrom graphene.types import InputObjectType-from graphql_jwt.decorators import permission_requiredfrom ....product import modelsfrom ....product.tasks import update_variants_names@@ -68,10 +68,10 @@ class CategoryCreate(ModelMutation):return user.has_perm('product.manage_products')@classmethod- def mutate(cls, root, info, **data):+ def perform_mutation(cls, root, info, **data):parent_id = data.pop('parent_id', None)data['input']['parent_id'] = parent_id- return super().mutate(root, info, **data)+ return super().perform_mutation(root, info, **data)@classmethoddef save(cls, info, instance, cleaned_input):@@ -218,15 +218,18 @@ class CollectionAddProducts(BaseMutation):description = 'Adds products to a collection.'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, collection_id, products):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, collection_id, products):errors = []collection = cls.get_node_or_error(info, collection_id, errors, 'collectionId', only_type=Collection)products = cls.get_nodes_or_error(products, errors, 'products', only_type=Product)collection.products.add(*products)- return CollectionAddProducts(collection=collection, errors=errors)+ return CollectionAddProducts(collection=collection, errors=[])class CollectionRemoveProducts(BaseMutation):@@ -244,15 +247,18 @@ class CollectionRemoveProducts(BaseMutation):description = 'Remove products from a collection.'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, collection_id, products):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, collection_id, products):errors = []collection = cls.get_node_or_error(info, collection_id, errors, 'collectionId', only_type=Collection)products = cls.get_nodes_or_error(products, errors, 'products', only_type=Product)collection.products.remove(*products)- return CollectionRemoveProducts(collection=collection, errors=errors)+ return CollectionRemoveProducts(collection=collection)class AttributeValueInput(InputObjectType):@@ -335,7 +341,7 @@ class ProductCreate(ModelMutation):try:attributes = attributes_to_hstore(attributes, qs)except ValueError as e:- cls.add_error(errors, 'attributes', str(e))+ raise ValidationError({'attributes': str(e)})else:cleaned_input['attributes'] = attributesclean_seo_fields(cleaned_input)@@ -354,10 +360,10 @@ class ProductCreate(ModelMutation):if product_type and not product_type.has_variants:input_sku = cleaned_input.get('sku')if not input_sku:- cls.add_error(errors, 'sku', 'This field cannot be blank.')+ raise ValidationError({'sku': 'This field cannot be blank.'})elif models.ProductVariant.objects.filter(sku=input_sku).exists():- cls.add_error(- errors, 'sku', 'Product with this SKU already exists.')+ raise ValidationError({+ 'sku': 'Product with this SKU already exists.'})@classmethod@transaction.atomic@@ -401,8 +407,8 @@ class ProductUpdate(ProductCreate):if (not product_type.has_variants andinput_sku andmodels.ProductVariant.objects.filter(sku=input_sku).exists()):- cls.add_error(- errors, 'sku', 'Product with this SKU already exists.')+ raise ValidationError({+ 'sku': 'Product with this SKU already exists.'})@classmethod@transaction.atomic@@ -486,7 +492,8 @@ class ProductVariantCreate(ModelMutation):value = attributes_input.get(attr.slug, None)if not value:fieldname = 'attributes:%s' % attr.slug- cls.add_error(errors, fieldname, 'This field cannot be blank.')+ raise ValidationError({+ fieldname: 'This field cannot be blank.'})@classmethoddef clean_input(cls, info, instance, input, errors):@@ -510,7 +517,7 @@ class ProductVariantCreate(ModelMutation):attributes = attributes_to_hstore(attributes_input, variant_attrs)except ValueError as e:- cls.add_error(errors, 'attributes', str(e))+ raise ValidationError({'attributes': str(e)})else:cleaned_input['attributes'] = attributesreturn cleaned_input@@ -663,19 +670,21 @@ class ProductImageCreate(BaseMutation):https://github.com/jaydenseric/graphql-multipart-request-spec''')@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, input):errors = []product = cls.get_node_or_error(info, input['product'], errors, 'product', only_type=Product)image_data = info.context.FILES.get(input['image'])validate_image_file(cls, image_data, 'image', errors)- image = None- if not errors:- image = product.images.create(- image=image_data, alt=input.get('alt', ''))- create_product_thumbnails.delay(image.pk)- return ProductImageCreate(product=product, image=image, errors=errors)++ image = product.images.create(+ image=image_data, alt=input.get('alt', ''))+ create_product_thumbnails.delay(image.pk)+ return ProductImageCreate(product=product, image=image)class ProductImageUpdateInput(graphene.InputObjectType):@@ -697,8 +706,11 @@ class ProductImageUpdate(BaseMutation):description = 'Updates a product image.'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, id, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, id, input):errors = []image = cls.get_node_or_error(info, id, errors, 'id', only_type=ProductImage)@@ -708,7 +720,7 @@ class ProductImageUpdate(BaseMutation):if alt is not None:image.alt = altimage.save(update_fields=['alt'])- return ProductImageUpdate(product=product, image=image, errors=errors)+ return ProductImageUpdate(product=product, image=image)class ProductImageReorder(BaseMutation):@@ -727,30 +739,33 @@ class ProductImageReorder(BaseMutation):description = 'Changes ordering of the product image.'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, product_id, images_ids):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, product_id, images_ids):errors = []product = cls.get_node_or_error(info, product_id, errors, 'productId', Product)if len(images_ids) != product.images.count():- cls.add_error(- errors, 'order', 'Incorrect number of image IDs provided.')+ raise ValidationError({+ 'order': 'Incorrect number of image IDs provided.'})images = []for image_id in images_ids:image = cls.get_node_or_error(info, image_id, errors, 'order', only_type=ProductImage)if image and image.product != product:- cls.add_error(- errors, 'order',- "Image with id %r does not belong to product %r" % (- image_id, product_id))+ raise ValidationError({+ 'order':+ 'Image %(image_id)s does not belong to this product.'},+ params={'image_id': image_id})images.append(image)if not errors:for order, image in enumerate(images):image.sort_order = orderimage.save(update_fields=['sort_order'])return ProductImageReorder(- product=product, images=images, errors=errors)+ product=product, images=images)class ProductImageDelete(BaseMutation):@@ -765,8 +780,11 @@ class ProductImageDelete(BaseMutation):description = 'Deletes a product image.'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, id):errors = []image = cls.get_node_or_error(info, id, errors, 'id', only_type=ProductImage)@@ -775,7 +793,7 @@ class ProductImageDelete(BaseMutation):image.delete()image.id = image_idreturn ProductImageDelete(- product=image.product, image=image, errors=errors)+ product=image.product, image=image)class VariantImageAssign(BaseMutation):@@ -794,8 +812,11 @@ class VariantImageAssign(BaseMutation):description = 'Assign an image to a product variant'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, image_id, variant_id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, image_id, variant_id):errors = []image = cls.get_node_or_error(info, image_id, errors, 'imageId', ProductImage)@@ -808,10 +829,10 @@ class VariantImageAssign(BaseMutation):if image_belongs_to_product:image.variant_images.create(variant=variant)else:- cls.add_error(- errors, 'imageId', 'Image must be for this product')+ raise ValidationError({+ 'image_id': 'This image doesn\'t belong to that product.'})return VariantImageAssign(- product_variant=variant, image=image, errors=errors)+ product_variant=variant, image=image)class VariantImageUnassign(BaseMutation):@@ -829,8 +850,11 @@ class VariantImageUnassign(BaseMutation):description = 'Unassign an image from a product variant'@classmethod- @permission_required('product.manage_products')- def mutate(cls, root, info, image_id, variant_id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('product.manage_products')++ @classmethod+ def perform_mutation(cls, root, info, image_id, variant_id):errors = []image = cls.get_node_or_error(info, image_id, errors, 'imageId', ProductImage)@@ -842,10 +866,9 @@ class VariantImageUnassign(BaseMutation):variant_image = models.VariantImage.objects.get(image=image, variant=variant)except models.VariantImage.DoesNotExist:- cls.add_error(- errors, 'imageId',- 'Image is not assigned to this variant.')+ raise ValidationError({+ 'image_id': 'Image is not assigned to this variant.'})else:variant_image.delete()return VariantImageUnassign(- product_variant=variant, image=image, errors=errors)+ product_variant=variant, image=image)diff --git a/saleor/graphql/shipping/mutations.py b/saleor/graphql/shipping/mutations.pyindex b705398e59..110158e0ff 100644--- a/saleor/graphql/shipping/mutations.py+++ b/saleor/graphql/shipping/mutations.py@@ -1,7 +1,7 @@from textwrap import dedentimport graphene-from graphql_jwt.decorators import permission_required+from django.core.exceptions import ValidationErrorfrom ...dashboard.shipping.forms import default_shipping_zone_existsfrom ...shipping import models@@ -49,8 +49,8 @@ class ShippingZoneMixin:default = cleaned_input.get('default')if default:if default_shipping_zone_exists(instance.pk):- cls.add_error(- errors, 'default', 'Default shipping zone already exists.')+ raise ValidationError({+ 'default': 'Default shipping zone already exists.'})elif cleaned_input.get('countries'):cleaned_input['countries'] = []else:@@ -121,19 +121,19 @@ class ShippingPriceMixin:max_price = cleaned_input.get('maximum_order_price')if (min_price is not None and max_price is not Noneand max_price <= min_price):- cls.add_error(- errors, 'maximum_order_price',+ raise ValidationError({+ 'maximum_order_price':'Maximum order price should be larger than the '- 'minimum order price.')+ 'minimum order price.'})else:min_weight = cleaned_input.get('minimum_order_weight')max_weight = cleaned_input.get('maximum_order_weight')if (min_weight is not None and max_weight is not Noneand max_weight <= min_weight):- cls.add_error(- errors, 'maximum_order_weight',+ raise ValidationError({+ 'maximum_order_weight':'Maximum order weight should be larger than the '- 'minimum order weight.')+ 'minimum order weight.'})return cleaned_input@@ -204,20 +204,18 @@ class ShippingPriceDelete(BaseMutation):description = 'Deletes a shipping price.'@classmethod- @permission_required('shipping.manage_shipping')- def mutate(cls, root, info, id):+ def user_is_allowed(cls, user, input):+ return user.has_perm('shipping.manage_shipping')++ @classmethod+ def perform_mutation(cls, root, info, id):errors = []shipping_method = cls.get_node_or_error(info, id, errors, 'id', only_type=ShippingMethod)- if not shipping_method:- return ShippingPriceDelete(errors=errors)shipping_method_id = shipping_method.idshipping_zone = shipping_method.shipping_zone-shipping_method.delete()shipping_method.id = shipping_method_idreturn ShippingPriceDelete(- shipping_method=shipping_method,- shipping_zone=shipping_zone,- errors=errors)+ shipping_method=shipping_method, shipping_zone=shipping_zone)diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.pyindex 497218ec02..29c775c840 100644--- a/saleor/graphql/shop/mutations.py+++ b/saleor/graphql/shop/mutations.py@@ -1,7 +1,7 @@import graphenefrom django.conf import settings+from django.core.exceptions import ValidationErrorfrom django.core.management import call_command-from graphql_jwt.decorators import permission_requiredfrom ...site import models as site_modelsfrom ..core.enums import WeightUnitsEnum@@ -48,8 +48,11 @@ class ShopSettingsUpdate(BaseMutation):description = 'Updates shop settings'@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info, input):errors = []instance = info.context.site.settingsfor field_name, desired_value in input.items():@@ -58,10 +61,8 @@ class ShopSettingsUpdate(BaseMutation):setattr(instance, field_name, desired_value)cls.clean_instance(instance, errors)- if errors:- return ShopSettingsUpdate(errors=errors)instance.save()- return ShopSettingsUpdate(shop=Shop(), errors=errors)+ return ShopSettingsUpdate(shop=Shop())class ShopDomainUpdate(BaseMutation):@@ -74,8 +75,11 @@ class ShopDomainUpdate(BaseMutation):description = 'Updates site domain of the shop'@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info, input):errors = []site = info.context.sitedomain = input.get('domain')@@ -85,10 +89,8 @@ class ShopDomainUpdate(BaseMutation):if name is not None:site.name = namecls.clean_instance(site, errors)- if errors:- return ShopDomainUpdate(errors=errors)site.save()- return ShopDomainUpdate(shop=Shop(), errors=errors)+ return ShopDomainUpdate(shop=Shop())class ShopFetchTaxRates(BaseMutation):@@ -98,16 +100,19 @@ class ShopFetchTaxRates(BaseMutation):description = 'Fetch tax rates'@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info):errors = []if settings.VATLAYER_ACCESS_KEY:call_command('get_vat_rates')else:- cls.add_error(- errors, None, 'Could not fetch tax rates. '- 'Make sure you have supplied a valid API Access Key.')- return ShopFetchTaxRates(shop=Shop(), errors=errors)+ raise ValidationError(+ 'Could not fetch tax rates. Make sure you have supplied a '+ 'valid API Access Key.')+ return ShopFetchTaxRates(shop=Shop())class HomepageCollectionUpdate(BaseMutation):@@ -121,22 +126,19 @@ class HomepageCollectionUpdate(BaseMutation):description = 'Updates homepage collection of the shop'@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info, collection=None):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info, collection=None):errors = []- new_collection = None- if collection:- new_collection = cls.get_node_or_error(- info, collection, errors, 'collection', Collection)- if errors:- return HomepageCollectionUpdate(errors=errors)+ new_collection = cls.get_node_or_error(+ info, collection, errors, 'collection', Collection)site_settings = info.context.site.settingssite_settings.homepage_collection = new_collectioncls.clean_instance(site_settings, errors)- if errors:- return HomepageCollectionUpdate(errors=errors)site_settings.save(update_fields=['homepage_collection'])- return HomepageCollectionUpdate(shop=Shop(), errors=errors)+ return HomepageCollectionUpdate(shop=Shop())class AuthorizationKeyInput(graphene.InputObjectType):@@ -162,21 +164,20 @@ class AuthorizationKeyAdd(BaseMutation):description='Fields required to create an authorization key.')@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info, key_type, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info, key_type, input):errors = []if site_models.AuthorizationKey.objects.filter(name=key_type).exists():- cls.add_error(- errors, 'key_type', 'Authorization key already exists.')- return AuthorizationKeyAdd(errors=errors)+ raise ValidationError({+ 'key_type': 'Authorization key already exists.'})site_settings = info.context.site.settingsinstance = site_models.AuthorizationKey(name=key_type, site_settings=site_settings, **input)cls.clean_instance(instance, errors)- if errors:- return AuthorizationKeyAdd(errors=errors)-instance.save()return AuthorizationKeyAdd(authorization_key=instance, shop=Shop())@@ -194,17 +195,18 @@ class AuthorizationKeyDelete(BaseMutation):description = 'Deletes an authorization key.'@classmethod- @permission_required('site.manage_settings')- def mutate(cls, root, info, key_type):- errors = []+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_settings')++ @classmethod+ def perform_mutation(cls, root, info, key_type):try:site_settings = info.context.site.settingsinstance = site_models.AuthorizationKey.objects.get(name=key_type, site_settings=site_settings)except site_models.AuthorizationKey.DoesNotExist:- cls.add_error(- errors, 'key_type', 'Couldn\'t resolve authorization key')- return AuthorizationKeyDelete(errors=errors)+ raise ValidationError({+ 'key_type': 'Couldn\'t resolve authorization key'})instance.delete()return AuthorizationKeyDelete(authorization_key=instance, shop=Shop())diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.pyindex 295946d95e..e2ba9fd070 100644--- a/saleor/graphql/translations/mutations.py+++ b/saleor/graphql/translations/mutations.py@@ -1,5 +1,4 @@import graphene-from graphql_jwt.decorators import permission_requiredfrom ...discount import models as discount_modelsfrom ...menu import models as menu_models@@ -14,24 +13,21 @@ from .enums import LanguageCodeEnumclass BaseTranslateMutation(ModelMutation):-class Meta:abstract = True@classmethod- @permission_required('site.manage_translations')- def mutate(cls, root, info, **data):- errors = []+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_translations')++ @classmethod+ def perform_mutation(cls, root, info, **data):model_type = registry.get_type_for_model(cls._meta.model)instance = cls.get_node_or_error(- info, data['id'], errors, 'id', model_type)-- if errors or not instance:- return cls(errors=errors)-+ info, data['id'], only_type=model_type)instance.translations.update_or_create(language_code=data['language_code'], defaults=data['input'])- return cls(**{cls._meta.return_field_name: instance, 'errors': errors})+ return cls(**{cls._meta.return_field_name: instance})class NameTranslationInput(graphene.InputObjectType):@@ -218,9 +214,12 @@ class ShopSettingsTranslate(BaseMutation):description = 'Creates/Updates translations for Shop Settings.'@classmethod- @permission_required('site.manage_translations')- def mutate(cls, root, info, language_code, input):+ def user_is_allowed(cls, user, input):+ return user.has_perm('site.manage_translations')++ @classmethod+ def perform_mutation(cls, root, info, language_code, input):instance = info.context.site.settingsinstance.translations.update_or_create(language_code=language_code, defaults=input)- return ShopSettingsTranslate(shop=Shop(), errors=[])+ return ShopSettingsTranslate(shop=Shop())diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 6c3ad0c5b8..35bd16df8f 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -6,7 +6,7 @@ import pytestfrom saleor.checkout.models import Cartfrom saleor.checkout.utils import (- add_voucher_to_cart, is_fully_paid, ready_to_place_order)+ add_voucher_to_cart, is_fully_paid, clean_checkout)from saleor.graphql.core.utils import str_to_enumfrom saleor.order.models import Orderfrom tests.api.utils import get_graphql_content@@ -1155,7 +1155,7 @@ def test_ready_to_place_order(payment.currency = total.gross.currencypayment.checkout = checkoutpayment.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert readyassert not error@@ -1164,7 +1164,7 @@ def test_ready_to_place_order_no_shipping_method(cart_with_item, address):checkout = cart_with_itemcheckout.shipping_address = addresscheckout.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert not readyassert error == 'Shipping method is not set'@@ -1174,7 +1174,7 @@ def test_ready_to_place_order_no_shipping_address(checkout = cart_with_itemcheckout.shipping_method = shipping_methodcheckout.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert not readyassert error == 'Shipping address is not set'@@ -1186,7 +1186,7 @@ def test_ready_to_place_order_invalid_shipping_method(shipping_method = shipping_zone_without_countries.shipping_methods.first()checkout.shipping_method = shipping_methodcheckout.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert not readyassert error == 'Shipping method is not valid for your shipping address'@@ -1197,7 +1197,7 @@ def test_ready_to_place_order_no_billing_address(checkout.shipping_address = addresscheckout.shipping_method = shipping_methodcheckout.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert not readyassert error == 'Billing address is not set'@@ -1209,7 +1209,7 @@ def test_ready_to_place_order_no_payment(checkout.shipping_method = shipping_methodcheckout.billing_address = addresscheckout.save()- ready, error = ready_to_place_order(checkout, None, None)+ ready, error = clean_checkout(checkout, None, None)assert not readyassert error == ('Provided payment methods can not '