Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add validation for unique code for Voucher and Gift Card
fowczareke938c65a89e0
diff --git a/saleor/core/utils/promotional_code.py b/saleor/core/utils/promotional_code.pynew file mode 100644index 0000000000..5dd69edfa1--- /dev/null+++ b/saleor/core/utils/promotional_code.py@@ -0,0 +1,19 @@+import uuid++from ...discount.models import Voucher+from ...giftcard.models import GiftCard+++def generate_promotional_code(length=12):+ """Generate new unique gift card code."""+ code = str(uuid.uuid4()).replace("-", "").upper()[:length]+ while not is_avaible_promotional_code(code):+ code = str(uuid.uuid4()).replace("-", "").upper()[:length]+ return code+++def is_avaible_promotional_code(code):+ return not (+ GiftCard.objects.filter(code=code).exists()+ or Voucher.objects.filter(code=code).exists()+ )diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.pyindex 59c5b08528..4d3321b204 100644--- a/saleor/dashboard/discount/forms.py+++ b/saleor/dashboard/discount/forms.py@@ -9,7 +9,7 @@ from mptt.forms import TreeNodeMultipleChoiceFieldfrom ...core.utils.taxes import ZERO_MONEYfrom ...discount import DiscountValueTypefrom ...discount.models import Sale, Voucher-from ...discount.utils import generate_voucher_code+from ...core.utils.promotional_code import generate_promotional_codefrom ...product.models import Category, Productfrom ..forms import AjaxSelect2MultipleChoiceField@@ -107,7 +107,7 @@ class VoucherForm(forms.ModelForm):initial = kwargs.get("initial", {})instance = kwargs.get("instance")if instance and instance.id is None and not initial.get("code"):- initial["code"] = generate_voucher_code()+ initial["code"] = generate_promotional_code()kwargs["initial"] = initialsuper().__init__(*args, **kwargs)diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 74088eeecb..1a0ce61abf 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -1,5 +1,3 @@-import uuid-from django.db.models import Ffrom django.utils.translation import pgettext@@ -87,8 +85,3 @@ def get_products_voucher_discount(voucher, prices):discounts = (voucher.get_discount_amount_for(price) for price in prices)total_amount = sum(discounts, ZERO_MONEY)return total_amount---def generate_voucher_code():- """Generate new unique voucher code."""- return str(uuid.uuid4()).replace("-", "").upper()[:12]diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pydeleted file mode 100644index 5656c5645f..0000000000--- a/saleor/giftcard/utils.py+++ /dev/null@@ -1,6 +0,0 @@-import uuid---def generate_gift_card_code():- """Generate new unique gift card code."""- return str(uuid.uuid4()).replace("-", "").upper()[:16]diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.pyindex af52d04e46..0317b92a4b 100644--- a/saleor/graphql/discount/mutations.py+++ b/saleor/graphql/discount/mutations.py@@ -1,7 +1,11 @@import graphene+from django.core.exceptions import ObjectDoesNotExist, ValidationError+from ...core.utils.promotional_code import (+ generate_promotional_code,+ is_avaible_promotional_code,+)from ...discount import models-from ...discount.utils import generate_voucher_codefrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.scalars import Decimalfrom ..product.types import Category, Collection, Product@@ -113,7 +117,9 @@ class VoucherCreate(ModelMutation):def clean_input(cls, info, instance, data):code = data.get("code", None)if code == "":- data["code"] = generate_voucher_code()+ data["code"] = generate_promotional_code()+ elif not is_avaible_promotional_code(code):+ raise ValidationError({"code": "Voucher with this code is not avaible."})cleaned_input = super().clean_input(info, instance, data)return cleaned_inputdiff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.pyindex e389a08d49..ed1e03f541 100644--- a/saleor/graphql/giftcard/mutations.py+++ b/saleor/graphql/giftcard/mutations.py@@ -4,8 +4,11 @@ import graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom ...account.models import User+from ...core.utils.promotional_code import (+ generate_promotional_code,+ is_avaible_promotional_code,+)from ...giftcard import models-from ...giftcard.utils import generate_gift_card_codefrom ..core.mutations import BaseMutation, ModelMutationfrom ..core.scalars import Decimalfrom .types import GiftCard@@ -39,8 +42,10 @@ class GiftCardCreate(ModelMutation):@classmethoddef clean_input(cls, info, instance, data):code = data.get("code", None)- if code == "":- data["code"] = generate_gift_card_code()+ if not code and not instance.pk:+ data["code"] = generate_promotional_code(16)+ elif not is_avaible_promotional_code(code):+ raise ValidationError({"code": "Gift card with this code is not avaible."})cleaned_input = super().clean_input(info, instance, data)balance = cleaned_input.get("balance", None)if balance:diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex a49c49dba6..a1f4298773 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -12,7 +12,7 @@ from ...product import models as product_modelsfrom ...site import models as site_modelsfrom ..core.enums import WeightUnitsEnumfrom ..core.types.common import CountryDisplay, LanguageDisplay, PermissionDisplay-from ..core.utils import str_to_enum, get_node_optimized+from ..core.utils import get_node_optimized, str_to_enumfrom ..menu.types import Menufrom ..product.types import Collectionfrom ..translations.enums import LanguageCodeEnum@@ -278,4 +278,3 @@ class Shop(graphene.ObjectType):@permission_required("site.manage_settings")def resolve_default_digital_url_valid_days(_, info):return info.context.site.settings.default_digital_url_valid_days-