Skip to content

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

Reorganise discount mutations (#10037)

Jakub2a5e6795271f
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
deleted file mode 100644
index 4a2a1c3896..0000000000
--- a/saleor/graphql/discount/mutations.py
+++ /dev/null
@@ -1,894 +0,0 @@
-from collections import defaultdict
-from typing import TYPE_CHECKING, DefaultDict, Dict, List, Set
-
-import graphene
-from django.core.exceptions import ValidationError
-from django.db import transaction
-
-from ...core.permissions import DiscountPermissions
-from ...core.tracing import traced_atomic_transaction
-from ...core.utils.promo_code import generate_promo_code, is_available_promo_code
-from ...discount import DiscountValueType, models
-from ...discount.error_codes import DiscountErrorCode
-from ...discount.models import SaleChannelListing
-from ...discount.utils import CatalogueInfo, fetch_catalogue_info
-from ...product.tasks import (
- update_products_discounted_prices_of_catalogues_task,
- update_products_discounted_prices_of_discount_task,
-)
-from ...product.utils import get_products_ids_without_variants
-from ..channel import ChannelContext
-from ..channel.mutations import BaseChannelListingMutation
-from ..core.descriptions import ADDED_IN_31
-from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ..core.scalars import PositiveDecimal
-from ..core.types import DiscountError, NonNullList
-from ..core.validators import validate_end_is_after_start, validate_price_precision
-from ..discount.dataloaders import SaleChannelListingBySaleIdLoader
-from ..product.types import Category, Collection, Product, ProductVariant
-from .enums import DiscountValueTypeEnum, VoucherTypeEnum
-from .types import Sale, Voucher
-
-if TYPE_CHECKING:
- from ...discount.models import Sale as SaleModel
-
-ErrorType = DefaultDict[str, List[ValidationError]]
-NodeCatalogueInfo = DefaultDict[str, Set[str]]
-
-
-def convert_catalogue_info_to_global_ids(
- catalogue_info: CatalogueInfo,
-) -> NodeCatalogueInfo:
- catalogue_fields = ["categories", "collections", "products", "variants"]
- type_names = ["Category", "Collection", "Product", "ProductVariant"]
- converted_catalogue_info: NodeCatalogueInfo = defaultdict(set)
-
- for type_name, catalogue_field in zip(type_names, catalogue_fields):
- converted_catalogue_info[catalogue_field].update(
- graphene.Node.to_global_id(type_name, id_)
- for id_ in catalogue_info[catalogue_field]
- )
- return converted_catalogue_info
-
-
-class CatalogueInput(graphene.InputObjectType):
- products = NonNullList(
- graphene.ID, description="Products related to the discount.", name="products"
- )
- categories = NonNullList(
- graphene.ID,
- description="Categories related to the discount.",
- name="categories",
- )
- collections = NonNullList(
- graphene.ID,
- description="Collections related to the discount.",
- name="collections",
- )
- variants = NonNullList(
- graphene.ID,
- description="Product variant related to the discount." + ADDED_IN_31,
- name="variants",
- )
-
-
-class BaseDiscountCatalogueMutation(BaseMutation):
- class Meta:
- abstract = True
-
- @classmethod
- def recalculate_discounted_prices(cls, products, categories, collections, variants):
- update_products_discounted_prices_of_catalogues_task.delay(
- product_ids=[p.pk for p in products],
- category_ids=[c.pk for c in categories],
- collection_ids=[c.pk for c in collections],
- variant_ids=[v.pk for v in variants],
- )
-
- @classmethod
- def add_catalogues_to_node(cls, node, input):
- products = input.get("products", [])
- if products:
- products = cls.get_nodes_or_error(products, "products", Product)
- cls.clean_product(products)
- node.products.add(*products)
- categories = input.get("categories", [])
- if categories:
- categories = cls.get_nodes_or_error(categories, "categories", Category)
- node.categories.add(*categories)
- collections = input.get("collections", [])
- if collections:
- collections = cls.get_nodes_or_error(collections, "collections", Collection)
- node.collections.add(*collections)
- variants = input.get("variants", [])
- if variants:
- variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)
- node.variants.add(*variants)
- # Updated the db entries, recalculating discounts of affected products
- cls.recalculate_discounted_prices(products, categories, collections, variants)
-
- @classmethod
- def clean_product(cls, products):
- products_ids_without_variants = get_products_ids_without_variants(products)
- if products_ids_without_variants:
- raise ValidationError(
- {
- "products": ValidationError(
- "Cannot manage products without variants.",
- code=DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT,
- params={"products": products_ids_without_variants},
- )
- }
- )
-
- @classmethod
- def remove_catalogues_from_node(cls, node, input):
- products = input.get("products", [])
- if products:
- products = cls.get_nodes_or_error(products, "products", Product)
- node.products.remove(*products)
- categories = input.get("categories", [])
- if categories:
- categories = cls.get_nodes_or_error(categories, "categories", Category)
- node.categories.remove(*categories)
- collections = input.get("collections", [])
- if collections:
- collections = cls.get_nodes_or_error(collections, "collections", Collection)
- node.collections.remove(*collections)
- variants = input.get("variants", [])
- if variants:
- variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)
- node.variants.remove(*variants)
- # Updated the db entries, recalculating discounts of affected products
- cls.recalculate_discounted_prices(products, categories, collections, variants)
-
-
-class VoucherInput(graphene.InputObjectType):
- type = VoucherTypeEnum(
- description="Voucher type: PRODUCT, CATEGORY SHIPPING or ENTIRE_ORDER."
- )
- name = graphene.String(description="Voucher name.")
- code = graphene.String(description="Code to use the voucher.")
- start_date = graphene.types.datetime.DateTime(
- description="Start date of the voucher in ISO 8601 format."
- )
- end_date = graphene.types.datetime.DateTime(
- description="End date of the voucher in ISO 8601 format."
- )
- discount_value_type = DiscountValueTypeEnum(
- description="Choices: fixed or percentage."
- )
- products = NonNullList(
- graphene.ID, description="Products discounted by the voucher.", name="products"
- )
- variants = NonNullList(
- graphene.ID,
- description="Variants discounted by the voucher." + ADDED_IN_31,
- name="variants",
- )
- collections = NonNullList(
- graphene.ID,
- description="Collections discounted by the voucher.",
- name="collections",
- )
- categories = NonNullList(
- graphene.ID,
- description="Categories discounted by the voucher.",
- name="categories",
- )
- min_checkout_items_quantity = graphene.Int(
- description="Minimal quantity of checkout items required to apply the voucher."
- )
- countries = NonNullList(
- graphene.String,
- description="Country codes that can be used with the shipping voucher.",
- )
- apply_once_per_order = graphene.Boolean(
- description="Voucher should be applied to the cheapest item or entire order."
- )
- apply_once_per_customer = graphene.Boolean(
- description="Voucher should be applied once per customer."
- )
- only_for_staff = graphene.Boolean(
- description="Voucher can be used only by staff user."
- )
- usage_limit = graphene.Int(
- description="Limit number of times this voucher can be used in total."
- )
-
-
-class VoucherCreate(ModelMutation):
- class Arguments:
- input = VoucherInput(
- required=True, description="Fields required to create a voucher."
- )
-
- class Meta:
- description = "Creates a new voucher."
- model = models.Voucher
- object_type = Voucher
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- code = data.get("code", None)
- if code == "":
- data["code"] = generate_promo_code()
- elif not is_available_promo_code(code):
- raise ValidationError(
- {
- "code": ValidationError(
- "Promo code already exists.",
- code=DiscountErrorCode.ALREADY_EXISTS,
- )
- }
- )
- cleaned_input = super().clean_input(info, instance, data)
-
- return cleaned_input
-
- @classmethod
- def success_response(cls, instance):
- instance = ChannelContext(node=instance, channel_slug=None)
- return super().success_response(instance)
-
- @classmethod
- def clean_instance(cls, info, instance):
- super().clean_instance(info, instance)
- start_date = instance.start_date
- end_date = instance.end_date
- try:
- validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"end_date": error})
-
- @classmethod
- def post_save_action(cls, info, instance, cleaned_input):
- info.context.plugins.voucher_created(instance)
-
-
-class VoucherUpdate(VoucherCreate):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher to update.")
- input = VoucherInput(
- required=True, description="Fields required to update a voucher."
- )
-
- class Meta:
- description = "Updates a voucher."
- model = models.Voucher
- object_type = Voucher
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def post_save_action(cls, info, instance, cleaned_input):
- info.context.plugins.voucher_updated(instance)
-
-
-class VoucherDelete(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher to delete.")
-
- class Meta:
- description = "Deletes a voucher."
- model = models.Voucher
- object_type = Voucher
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def success_response(cls, instance):
- instance = ChannelContext(node=instance, channel_slug=None)
- response = super().success_response(instance)
- return response
-
- @classmethod
- def post_save_action(cls, info, instance, cleaned_input):
- info.context.plugins.voucher_deleted(instance)
-
-
-class VoucherBaseCatalogueMutation(BaseDiscountCatalogueMutation):
- voucher = graphene.Field(
- Voucher, description="Voucher of which catalogue IDs will be modified."
- )
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher.")
- input = CatalogueInput(
- required=True,
- description="Fields required to modify catalogue IDs of voucher.",
- )
-
- class Meta:
- abstract = True
-
- @classmethod
- def mutate(cls, root, info, **data):
- response = super().mutate(root, info, **data)
- if response.voucher:
- response.voucher = ChannelContext(node=response.voucher, channel_slug=None)
- return response
-
-
-class VoucherAddCatalogues(VoucherBaseCatalogueMutation):
- class Meta:
- description = "Adds products, categories, collections to a voucher."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- voucher = cls.get_node_or_error(
- info, data.get("id"), only_type=Voucher, field="voucher_id"
- )
- input_data = data.get("input", {})
- cls.add_catalogues_to_node(voucher, input_data)
-
- if input_data:
- info.context.plugins.voucher_updated(voucher)
-
- return VoucherAddCatalogues(voucher=voucher)
-
-
-class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):
- class Meta:
- description = "Removes products, categories, collections from a voucher."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- voucher = cls.get_node_or_error(
- info, data.get("id"), only_type=Voucher, field="voucher_id"
- )
- input_data = data.get("input", {})
- cls.remove_catalogues_from_node(voucher, input_data)
-
- if input_data:
- info.context.plugins.voucher_updated(voucher)
-
- return VoucherRemoveCatalogues(voucher=voucher)
-
-
-class VoucherChannelListingAddInput(graphene.InputObjectType):
- channel_id = graphene.ID(required=True, description="ID of a channel.")
- discount_value = PositiveDecimal(description="Value of the voucher.")
- min_amount_spent = PositiveDecimal(
- description="Min purchase amount required to apply the voucher."
- )
-
-
-class VoucherChannelListingInput(graphene.InputObjectType):
- add_channels = NonNullList(
- VoucherChannelListingAddInput,
- description="List of channels to which the voucher should be assigned.",
- required=False,
- )
- remove_channels = NonNullList(
- graphene.ID,
- description="List of channels from which the voucher should be unassigned.",
- required=False,
- )
-
-
-class VoucherChannelListingUpdate(BaseChannelListingMutation):
- voucher = graphene.Field(Voucher, description="An updated voucher instance.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a voucher to update.")
- input = VoucherChannelListingInput(
- required=True,
- description="Fields required to update voucher channel listings.",
- )
-
- class Meta:
- description = "Manage voucher's availability in channels."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def clean_discount_values_per_channel(cls, cleaned_input, voucher, error_dict):
- channel_slugs_assigned_to_voucher = voucher.channel_listings.values_list(
- "channel__slug", flat=True
- )
-
- for cleaned_channel in cleaned_input.get("add_channels", []):
- channel = cleaned_channel.get("channel", None)
- if not channel:
- continue
- discount_value = cleaned_channel.get("discount_value", "")
- # New channel listing requires discout value. It raises validation error for
- # `discout_value` == `None`.
- # Updating channel listing doesn't require to pass `discout_value`.
- should_create = channel.slug not in channel_slugs_assigned_to_voucher
- missing_required_value = not discount_value and should_create
- if missing_required_value or discount_value is None:
- error_dict["channels_without_value"].append(
- cleaned_channel["channel_id"]
- )
- # Validate value precision if it is fixed amount voucher
- if voucher.discount_value_type == DiscountValueType.FIXED:
- try:
- validate_price_precision(discount_value, channel.currency_code)
- except ValidationError:
- error_dict["channels_with_invalid_value_precision"].append(
- cleaned_channel["channel_id"]
- )
- elif voucher.discount_value_type == DiscountValueType.PERCENTAGE:
- if discount_value > 100:
- error_dict["channels_with_invalid_percentage_value"].append(
- cleaned_channel["channel_id"]
- )
-
- min_amount_spent = cleaned_channel.get("min_amount_spent", None)
- if min_amount_spent:
- try:
- validate_price_precision(min_amount_spent, channel.currency_code)
- except ValidationError:
- error_dict[
- "channels_with_invalid_min_amount_spent_precision"
- ].append(cleaned_channel["channel_id"])
-
- @classmethod
- def clean_discount_values(cls, cleaned_input, voucher, errors):
- error_dict = {
- "channels_without_value": [],
- "channels_with_invalid_value_precision": [],
- "channels_with_invalid_percentage_value": [],
- "channels_with_invalid_min_amount_spent_precision": [],
- }
- cls.clean_discount_values_per_channel(
- cleaned_input,
- voucher,
- error_dict,
- )
- channels_without_value = error_dict["channels_without_value"]
- if channels_without_value:
- errors["discount_value"].append(
- ValidationError(
- "Value is required for voucher.",
- code=DiscountErrorCode.REQUIRED.value,
- params={"channels": channels_without_value},
- )
- )
-
- channels_with_invalid_value_precision = error_dict[
- "channels_with_invalid_value_precision"
- ]
- if channels_with_invalid_value_precision:
- errors["discount_value"].append(
- ValidationError(
- "Invalid amount precision.",
- code=DiscountErrorCode.INVALID.value,
- params={"channels": channels_with_invalid_value_precision},
- )
- )
-
- channels_with_invalid_percentage_value = error_dict[
- "channels_with_invalid_percentage_value"
- ]
- if channels_with_invalid_percentage_value:
- errors["discount_value"].append(
- ValidationError(
- "Invalid percentage value.",
- code=DiscountErrorCode.INVALID.value,
- params={"channels": channels_with_invalid_percentage_value},
- )
- )
-
- channels_with_invalid_min_amount_spent_precision = error_dict[
- "channels_with_invalid_min_amount_spent_precision"
- ]
- if channels_with_invalid_min_amount_spent_precision:
- errors["min_amount_spent"].append(
- ValidationError(
- "Invalid amount precision.",
- code=DiscountErrorCode.INVALID.value,
- params={
- "channels": channels_with_invalid_min_amount_spent_precision
- },
- )
- )
- return cleaned_input
-
- @classmethod
- def add_channels(cls, voucher, add_channels):
- for add_channel in add_channels:
- channel = add_channel["channel"]
- defaults = {"currency": channel.currency_code}
- if "discount_value" in add_channel.keys():
- defaults["discount_value"] = add_channel.get("discount_value")
- if "min_amount_spent" in add_channel.keys():
- defaults["min_spent_amount"] = add_channel.get("min_amount_spent", None)
- models.VoucherChannelListing.objects.update_or_create(
- voucher=voucher,
- channel=channel,
- defaults=defaults,
- )
-
- @classmethod
- def remove_channels(cls, voucher, remove_channels):
- voucher.channel_listings.filter(channel_id__in=remove_channels).delete()
-
- @classmethod
- @traced_atomic_transaction()
- def save(cls, voucher, cleaned_input):
- cls.add_channels(voucher, cleaned_input.get("add_channels", []))
- cls.remove_channels(voucher, cleaned_input.get("remove_channels", []))
-
- @classmethod
- def perform_mutation(cls, _root, info, id, input):
- voucher = cls.get_node_or_error(info, id, only_type=Voucher, field="id")
- errors = defaultdict(list)
- cleaned_input = cls.clean_channels(
- info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
- )
- cleaned_input = cls.clean_discount_values(cleaned_input, voucher, errors)
-
- if errors:
- raise ValidationError(errors)
-
- cls.save(voucher, cleaned_input)
- info.context.plugins.voucher_updated(voucher)
-
- return VoucherChannelListingUpdate(
- voucher=ChannelContext(node=voucher, channel_slug=None)
- )
-
-
-class SaleInput(graphene.InputObjectType):
- name = graphene.String(description="Voucher name.")
- type = DiscountValueTypeEnum(description="Fixed or percentage.")
- value = PositiveDecimal(description="Value of the voucher.")
- products = NonNullList(
- graphene.ID, description="Products related to the discount.", name="products"
- )
- variants = NonNullList(
- graphene.ID,
- descriptions="Product variant related to the discount." + ADDED_IN_31,
- name="variants",
- )
- categories = NonNullList(
- graphene.ID,
- description="Categories related to the discount.",
- name="categories",
- )
- collections = NonNullList(
- graphene.ID,
- description="Collections related to the discount.",
- name="collections",
- )
- start_date = graphene.types.datetime.DateTime(
- description="Start date of the voucher in ISO 8601 format."
- )
- end_date = graphene.types.datetime.DateTime(
- description="End date of the voucher in ISO 8601 format."
- )
-
-
-class SaleUpdateDiscountedPriceMixin:
- @classmethod
- def success_response(cls, instance):
- # Update the "discounted_prices" of the associated, discounted
- # products (including collections and categories).
- update_products_discounted_prices_of_discount_task.delay(instance.pk)
- return super().success_response(
- ChannelContext(node=instance, channel_slug=None)
- )
-
-
-class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):
- class Arguments:
- input = SaleInput(
- required=True, description="Fields required to create a sale."
- )
-
- class Meta:
- description = "Creates a new sale."
- model = models.Sale
- object_type = Sale
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def clean_instance(cls, info, instance):
- super().clean_instance(info, instance)
- start_date = instance.start_date
- end_date = instance.end_date
- try:
- validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"end_date": error})
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- response = super().perform_mutation(_root, info, **data)
- instance = getattr(response, cls._meta.return_field_name).node
- current_catalogue = fetch_catalogue_info(instance)
-
- transaction.on_commit(
- lambda: info.context.plugins.sale_created(
- instance,
- convert_catalogue_info_to_global_ids(current_catalogue),
- )
- )
- return response
-
-
-class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a sale to update.")
- input = SaleInput(
- required=True, description="Fields required to update a sale."
- )
-
- class Meta:
- description = "Updates a sale."
- model = models.Sale
- object_type = Sale
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- node_id = data.get("id")
- instance = cls.get_node_or_error(info, node_id, only_type=Sale)
- previous_catalogue = fetch_catalogue_info(instance)
- response = super().perform_mutation(_root, info, **data)
- current_catalogue = fetch_catalogue_info(instance)
- transaction.on_commit(
- lambda: info.context.plugins.sale_updated(
- instance,
- convert_catalogue_info_to_global_ids(previous_catalogue),
- convert_catalogue_info_to_global_ids(current_catalogue),
- )
- )
- return response
-
-
-class SaleDelete(SaleUpdateDiscountedPriceMixin, ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a sale to delete.")
-
- class Meta:
- description = "Deletes a sale."
- model = models.Sale
- object_type = Sale
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- node_id = data.get("id")
- instance = cls.get_node_or_error(info, node_id, only_type=Sale)
- previous_catalogue = fetch_catalogue_info(instance)
- response = super().perform_mutation(_root, info, **data)
-
- transaction.on_commit(
- lambda: info.context.plugins.sale_deleted(
- instance, convert_catalogue_info_to_global_ids(previous_catalogue)
- )
- )
- return response
-
-
-class SaleBaseCatalogueMutation(BaseDiscountCatalogueMutation):
- sale = graphene.Field(
- Sale, description="Sale of which catalogue IDs will be modified."
- )
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a sale.")
- input = CatalogueInput(
- required=True,
- description="Fields required to modify catalogue IDs of sale.",
- )
-
- class Meta:
- abstract = True
-
-
-class SaleAddCatalogues(SaleBaseCatalogueMutation):
- class Meta:
- description = "Adds products, categories, collections to a voucher."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- sale = cls.get_node_or_error(
- info, data.get("id"), only_type=Sale, field="sale_id"
- )
- previous_catalogue = fetch_catalogue_info(sale)
- cls.add_catalogues_to_node(sale, data.get("input"))
- current_catalogue = fetch_catalogue_info(sale)
-
- transaction.on_commit(
- lambda: info.context.plugins.sale_updated(
- sale,
- previous_catalogue=convert_catalogue_info_to_global_ids(
- previous_catalogue
- ),
- current_catalogue=convert_catalogue_info_to_global_ids(
- current_catalogue
- ),
- )
- )
-
- return SaleAddCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
-
-
-class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
- class Meta:
- description = "Removes products, categories, collections from a sale."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- sale = cls.get_node_or_error(
- info, data.get("id"), only_type=Sale, field="sale_id"
- )
- previous_catalogue = fetch_catalogue_info(sale)
- cls.remove_catalogues_from_node(sale, data.get("input"))
- current_catalogue = fetch_catalogue_info(sale)
-
- transaction.on_commit(
- lambda: info.context.plugins.sale_updated(
- sale,
- previous_catalogue=convert_catalogue_info_to_global_ids(
- previous_catalogue
- ),
- current_catalogue=convert_catalogue_info_to_global_ids(
- current_catalogue
- ),
- )
- )
-
- return SaleRemoveCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
-
-
-class SaleChannelListingAddInput(graphene.InputObjectType):
- channel_id = graphene.ID(required=True, description="ID of a channel.")
- discount_value = PositiveDecimal(
- required=True, description="The value of the discount."
- )
-
-
-class SaleChannelListingInput(graphene.InputObjectType):
- add_channels = NonNullList(
- SaleChannelListingAddInput,
- description="List of channels to which the sale should be assigned.",
- required=False,
- )
- remove_channels = NonNullList(
- graphene.ID,
- description=("List of channels from which the sale should be unassigned."),
- required=False,
- )
-
-
-class SaleChannelListingUpdate(BaseChannelListingMutation):
- sale = graphene.Field(Sale, description="An updated sale instance.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a sale to update.")
- input = SaleChannelListingInput(
- required=True,
- description="Fields required to update sale channel listings.",
- )
-
- class Meta:
- description = "Manage sale's availability in channels."
- permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
- error_type_class = DiscountError
- error_type_field = "discount_errors"
-
- @classmethod
- def add_channels(cls, sale: "SaleModel", add_channels: List[Dict]):
- for add_channel in add_channels:
- channel = add_channel["channel"]
- defaults = {"currency": channel.currency_code}
- channel = add_channel["channel"]
- if "discount_value" in add_channel.keys():
- defaults["discount_value"] = add_channel.get("discount_value")
- SaleChannelListing.objects.update_or_create(
- sale=sale,
- channel=channel,
- defaults=defaults,
- )
-
- @classmethod
- def clean_discount_values(cls, cleaned_channels, sale_type, errors, error_code):
- channels_with_invalid_value_precision = []
- channels_with_invalid_percentage_value = []
- for cleaned_channel in cleaned_channels.get("add_channels", []):
- channel = cleaned_channel["channel"]
- currency_code = channel.currency_code
- discount_value = cleaned_channel.get("discount_value")
- if not discount_value:
- continue
- if sale_type == DiscountValueType.FIXED:
- try:
- validate_price_precision(discount_value, currency_code)
- except ValidationError:
- channels_with_invalid_value_precision.append(
- cleaned_channel["channel_id"]
- )
- elif sale_type == DiscountValueType.PERCENTAGE:
- if discount_value > 100:
- channels_with_invalid_percentage_value.append(
- cleaned_channel["channel_id"]
- )
-
- if channels_with_invalid_value_precision:
- errors["input"].append(
- ValidationError(
- "Invalid amount precision.",
- code=error_code,
- params={"channels": channels_with_invalid_value_precision},
- )
- )
- if channels_with_invalid_percentage_value:
- errors["input"].append(
- ValidationError(
- "Invalid percentage value.",
- code=error_code,
- params={"channels": channels_with_invalid_percentage_value},
- )
- )
- return cleaned_channels
-
- @classmethod
- def remove_channels(cls, sale: "SaleModel", remove_channels: List[int]):
- sale.channel_listings.filter(channel_id__in=remove_channels).delete()
-
- @classmethod
- @traced_atomic_transaction()
- def save(cls, info, sale: "SaleModel", cleaned_input: Dict):
- cls.add_channels(sale, cleaned_input.get("add_channels", []))
- cls.remove_channels(sale, cleaned_input.get("remove_channels", []))
- update_products_discounted_prices_of_discount_task.delay(sale.pk)
-
- @classmethod
- def perform_mutation(cls, _root, info, id, input):
- sale = cls.get_node_or_error(info, id, only_type=Sale, field="id")
- errors = defaultdict(list)
- cleaned_channels = cls.clean_channels(
- info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
- )
- cleaned_input = cls.clean_discount_values(
- cleaned_channels, sale.type, errors, DiscountErrorCode.INVALID.value
- )
-
- if errors:
- raise ValidationError(errors)
-
- cls.save(info, sale, cleaned_input)
-
- # Invalidate dataloader for channel listings
- SaleChannelListingBySaleIdLoader(info.context).clear(sale.id)
-
- return SaleChannelListingUpdate(
- sale=ChannelContext(node=sale, channel_slug=None)
- )
diff --git a/saleor/graphql/discount/mutations/__init__.py b/saleor/graphql/discount/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/discount/mutations/sale_add_catalogues.py b/saleor/graphql/discount/mutations/sale_add_catalogues.py
new file mode 100644
index 0000000000..05915db073
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_add_catalogues.py
@@ -0,0 +1,42 @@
+from django.db import transaction
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount.utils import fetch_catalogue_info
+from ...channel import ChannelContext
+from ...core.types import DiscountError
+from ..types import Sale
+from .sale_base_catalogue import SaleBaseCatalogueMutation
+from .utils import convert_catalogue_info_to_global_ids
+
+
+class SaleAddCatalogues(SaleBaseCatalogueMutation):
+ class Meta:
+ description = "Adds products, categories, collections to a voucher."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ sale = cls.get_node_or_error(
+ info, data.get("id"), only_type=Sale, field="sale_id"
+ )
+ previous_catalogue = fetch_catalogue_info(sale)
+ cls.add_catalogues_to_node(sale, data.get("input"))
+ current_catalogue = fetch_catalogue_info(sale)
+
+ transaction.on_commit(
+ lambda: info.context.plugins.sale_updated(
+ sale,
+ previous_catalogue=convert_catalogue_info_to_global_ids(
+ previous_catalogue
+ ),
+ current_catalogue=convert_catalogue_info_to_global_ids(
+ current_catalogue
+ ),
+ )
+ )
+
+ return SaleAddCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
diff --git a/saleor/graphql/discount/mutations/sale_base_catalogue.py b/saleor/graphql/discount/mutations/sale_base_catalogue.py
new file mode 100644
index 0000000000..eabc64a3c0
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_base_catalogue.py
@@ -0,0 +1,21 @@
+import graphene
+
+from ..types import Sale
+from .sale_base_discount_catalogue import BaseDiscountCatalogueMutation
+from .voucher_add_catalogues import CatalogueInput
+
+
+class SaleBaseCatalogueMutation(BaseDiscountCatalogueMutation):
+ sale = graphene.Field(
+ Sale, description="Sale of which catalogue IDs will be modified."
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a sale.")
+ input = CatalogueInput(
+ required=True,
+ description="Fields required to modify catalogue IDs of sale.",
+ )
+
+ class Meta:
+ abstract = True
diff --git a/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py b/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py
new file mode 100644
index 0000000000..746e13a2af
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_base_discount_catalogue.py
@@ -0,0 +1,78 @@
+from django.core.exceptions import ValidationError
+
+from ....discount.error_codes import DiscountErrorCode
+from ....product.tasks import update_products_discounted_prices_of_catalogues_task
+from ....product.utils import get_products_ids_without_variants
+from ...core.mutations import BaseMutation
+from ...product.types import Category, Collection, Product, ProductVariant
+
+
+class BaseDiscountCatalogueMutation(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def recalculate_discounted_prices(cls, products, categories, collections, variants):
+ update_products_discounted_prices_of_catalogues_task.delay(
+ product_ids=[p.pk for p in products],
+ category_ids=[c.pk for c in categories],
+ collection_ids=[c.pk for c in collections],
+ variant_ids=[v.pk for v in variants],
+ )
+
+ @classmethod
+ def add_catalogues_to_node(cls, node, input):
+ products = input.get("products", [])
+ if products:
+ products = cls.get_nodes_or_error(products, "products", Product)
+ cls.clean_product(products)
+ node.products.add(*products)
+ categories = input.get("categories", [])
+ if categories:
+ categories = cls.get_nodes_or_error(categories, "categories", Category)
+ node.categories.add(*categories)
+ collections = input.get("collections", [])
+ if collections:
+ collections = cls.get_nodes_or_error(collections, "collections", Collection)
+ node.collections.add(*collections)
+ variants = input.get("variants", [])
+ if variants:
+ variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)
+ node.variants.add(*variants)
+ # Updated the db entries, recalculating discounts of affected products
+ cls.recalculate_discounted_prices(products, categories, collections, variants)
+
+ @classmethod
+ def clean_product(cls, products):
+ products_ids_without_variants = get_products_ids_without_variants(products)
+ if products_ids_without_variants:
+ raise ValidationError(
+ {
+ "products": ValidationError(
+ "Cannot manage products without variants.",
+ code=DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT,
+ params={"products": products_ids_without_variants},
+ )
+ }
+ )
+
+ @classmethod
+ def remove_catalogues_from_node(cls, node, input):
+ products = input.get("products", [])
+ if products:
+ products = cls.get_nodes_or_error(products, "products", Product)
+ node.products.remove(*products)
+ categories = input.get("categories", [])
+ if categories:
+ categories = cls.get_nodes_or_error(categories, "categories", Category)
+ node.categories.remove(*categories)
+ collections = input.get("collections", [])
+ if collections:
+ collections = cls.get_nodes_or_error(collections, "collections", Collection)
+ node.collections.remove(*collections)
+ variants = input.get("variants", [])
+ if variants:
+ variants = cls.get_nodes_or_error(variants, "variants", ProductVariant)
+ node.variants.remove(*variants)
+ # Updated the db entries, recalculating discounts of affected products
+ cls.recalculate_discounted_prices(products, categories, collections, variants)
diff --git a/saleor/graphql/discount/mutations/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale_channel_listing_update.py
new file mode 100644
index 0000000000..41a14abec7
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_channel_listing_update.py
@@ -0,0 +1,148 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, Dict, List
+
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount import DiscountValueType
+from ....discount.error_codes import DiscountErrorCode
+from ....discount.models import SaleChannelListing
+from ....product.tasks import update_products_discounted_prices_of_discount_task
+from ...channel import ChannelContext
+from ...channel.mutations import BaseChannelListingMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types import DiscountError, NonNullList
+from ...core.validators import validate_price_precision
+from ...discount.types import Sale
+from ..dataloaders import SaleChannelListingBySaleIdLoader
+
+if TYPE_CHECKING:
+ from ....discount.models import Sale as SaleModel
+
+
+class SaleChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ discount_value = PositiveDecimal(
+ required=True, description="The value of the discount."
+ )
+
+
+class SaleChannelListingInput(graphene.InputObjectType):
+ add_channels = NonNullList(
+ SaleChannelListingAddInput,
+ description="List of channels to which the sale should be assigned.",
+ required=False,
+ )
+ remove_channels = NonNullList(
+ graphene.ID,
+ description="List of channels from which the sale should be unassigned.",
+ required=False,
+ )
+
+
+class SaleChannelListingUpdate(BaseChannelListingMutation):
+ sale = graphene.Field(Sale, description="An updated sale instance.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a sale to update.")
+ input = SaleChannelListingInput(
+ required=True,
+ description="Fields required to update sale channel listings.",
+ )
+
+ class Meta:
+ description = "Manage sale's availability in channels."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def add_channels(cls, sale: "SaleModel", add_channels: List[Dict]):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ channel = add_channel["channel"]
+ if "discount_value" in add_channel.keys():
+ defaults["discount_value"] = add_channel.get("discount_value")
+ SaleChannelListing.objects.update_or_create(
+ sale=sale,
+ channel=channel,
+ defaults=defaults,
+ )
+
+ @classmethod
+ def clean_discount_values(cls, cleaned_channels, sale_type, errors, error_code):
+ channels_with_invalid_value_precision = []
+ channels_with_invalid_percentage_value = []
+ for cleaned_channel in cleaned_channels.get("add_channels", []):
+ channel = cleaned_channel["channel"]
+ currency_code = channel.currency_code
+ discount_value = cleaned_channel.get("discount_value")
+ if not discount_value:
+ continue
+ if sale_type == DiscountValueType.FIXED:
+ try:
+ validate_price_precision(discount_value, currency_code)
+ except ValidationError:
+ channels_with_invalid_value_precision.append(
+ cleaned_channel["channel_id"]
+ )
+ elif sale_type == DiscountValueType.PERCENTAGE:
+ if discount_value > 100:
+ channels_with_invalid_percentage_value.append(
+ cleaned_channel["channel_id"]
+ )
+
+ if channels_with_invalid_value_precision:
+ errors["input"].append(
+ ValidationError(
+ "Invalid amount precision.",
+ code=error_code,
+ params={"channels": channels_with_invalid_value_precision},
+ )
+ )
+ if channels_with_invalid_percentage_value:
+ errors["input"].append(
+ ValidationError(
+ "Invalid percentage value.",
+ code=error_code,
+ params={"channels": channels_with_invalid_percentage_value},
+ )
+ )
+ return cleaned_channels
+
+ @classmethod
+ def remove_channels(cls, sale: "SaleModel", remove_channels: List[int]):
+ sale.channel_listings.filter(channel_id__in=remove_channels).delete()
+
+ @classmethod
+ @traced_atomic_transaction()
+ def save(cls, info, sale: "SaleModel", cleaned_input: Dict):
+ cls.add_channels(sale, cleaned_input.get("add_channels", []))
+ cls.remove_channels(sale, cleaned_input.get("remove_channels", []))
+ update_products_discounted_prices_of_discount_task.delay(sale.pk)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ sale = cls.get_node_or_error(info, id, only_type=Sale, field="id")
+ errors = defaultdict(list)
+ cleaned_channels = cls.clean_channels(
+ info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
+ )
+ cleaned_input = cls.clean_discount_values(
+ cleaned_channels, sale.type, errors, DiscountErrorCode.INVALID.value
+ )
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, sale, cleaned_input)
+
+ # Invalidate dataloader for channel listings
+ SaleChannelListingBySaleIdLoader(info.context).clear(sale.id)
+
+ return SaleChannelListingUpdate(
+ sale=ChannelContext(node=sale, channel_slug=None)
+ )
diff --git a/saleor/graphql/discount/mutations/sale_create.py b/saleor/graphql/discount/mutations/sale_create.py
new file mode 100644
index 0000000000..e6124ea3ae
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_create.py
@@ -0,0 +1,101 @@
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount import models
+from ....discount.error_codes import DiscountErrorCode
+from ....discount.utils import fetch_catalogue_info
+from ....product.tasks import update_products_discounted_prices_of_discount_task
+from ...channel import ChannelContext
+from ...core.descriptions import ADDED_IN_31
+from ...core.mutations import ModelMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types import DiscountError, NonNullList
+from ...core.validators import validate_end_is_after_start
+from ..enums import DiscountValueTypeEnum
+from ..types import Sale
+from .utils import convert_catalogue_info_to_global_ids
+
+
+class SaleUpdateDiscountedPriceMixin:
+ @classmethod
+ def success_response(cls, instance):
+ # Update the "discounted_prices" of the associated, discounted
+ # products (including collections and categories).
+ update_products_discounted_prices_of_discount_task.delay(instance.pk)
+ return super().success_response(
+ ChannelContext(node=instance, channel_slug=None)
+ )
+
+
+class SaleInput(graphene.InputObjectType):
+ name = graphene.String(description="Voucher name.")
+ type = DiscountValueTypeEnum(description="Fixed or percentage.")
+ value = PositiveDecimal(description="Value of the voucher.")
+ products = NonNullList(
+ graphene.ID, description="Products related to the discount.", name="products"
+ )
+ variants = NonNullList(
+ graphene.ID,
+ descriptions="Product variant related to the discount." + ADDED_IN_31,
+ name="variants",
+ )
+ categories = NonNullList(
+ graphene.ID,
+ description="Categories related to the discount.",
+ name="categories",
+ )
+ collections = NonNullList(
+ graphene.ID,
+ description="Collections related to the discount.",
+ name="collections",
+ )
+ start_date = graphene.types.datetime.DateTime(
+ description="Start date of the voucher in ISO 8601 format."
+ )
+ end_date = graphene.types.datetime.DateTime(
+ description="End date of the voucher in ISO 8601 format."
+ )
+
+
+class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):
+ class Arguments:
+ input = SaleInput(
+ required=True, description="Fields required to create a sale."
+ )
+
+ class Meta:
+ description = "Creates a new sale."
+ model = models.Sale
+ object_type = Sale
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ super().clean_instance(info, instance)
+ start_date = instance.start_date
+ end_date = instance.end_date
+ try:
+ validate_end_is_after_start(start_date, end_date)
+ except ValidationError as error:
+ error.code = DiscountErrorCode.INVALID.value
+ raise ValidationError({"end_date": error})
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = getattr(response, cls._meta.return_field_name).node
+ current_catalogue = fetch_catalogue_info(instance)
+
+ transaction.on_commit(
+ lambda: info.context.plugins.sale_created(
+ instance,
+ convert_catalogue_info_to_global_ids(current_catalogue),
+ )
+ )
+ return response
diff --git a/saleor/graphql/discount/mutations/sale_delete.py b/saleor/graphql/discount/mutations/sale_delete.py
new file mode 100644
index 0000000000..c0fb5b0e5c
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_delete.py
@@ -0,0 +1,40 @@
+import graphene
+from django.db import transaction
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount import models
+from ....discount.utils import fetch_catalogue_info
+from ....graphql.core.mutations import ModelDeleteMutation
+from ...core.types import DiscountError
+from ..types import Sale
+from .sale_create import SaleUpdateDiscountedPriceMixin
+from .utils import convert_catalogue_info_to_global_ids
+
+
+class SaleDelete(SaleUpdateDiscountedPriceMixin, ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a sale to delete.")
+
+ class Meta:
+ description = "Deletes a sale."
+ model = models.Sale
+ object_type = Sale
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ node_id = data.get("id")
+ instance = cls.get_node_or_error(info, node_id, only_type=Sale)
+ previous_catalogue = fetch_catalogue_info(instance)
+ response = super().perform_mutation(_root, info, **data)
+
+ transaction.on_commit(
+ lambda: info.context.plugins.sale_deleted(
+ instance, convert_catalogue_info_to_global_ids(previous_catalogue)
+ )
+ )
+ return response
diff --git a/saleor/graphql/discount/mutations/sale_remove_catalogues.py b/saleor/graphql/discount/mutations/sale_remove_catalogues.py
new file mode 100644
index 0000000000..2ac964872c
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_remove_catalogues.py
@@ -0,0 +1,42 @@
+from django.db import transaction
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount.utils import fetch_catalogue_info
+from ....graphql.channel import ChannelContext
+from ...core.types import DiscountError
+from ..types import Sale
+from .sale_base_catalogue import SaleBaseCatalogueMutation
+from .utils import convert_catalogue_info_to_global_ids
+
+
+class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
+ class Meta:
+ description = "Removes products, categories, collections from a sale."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ sale = cls.get_node_or_error(
+ info, data.get("id"), only_type=Sale, field="sale_id"
+ )
+ previous_catalogue = fetch_catalogue_info(sale)
+ cls.remove_catalogues_from_node(sale, data.get("input"))
+ current_catalogue = fetch_catalogue_info(sale)
+
+ transaction.on_commit(
+ lambda: info.context.plugins.sale_updated(
+ sale,
+ previous_catalogue=convert_catalogue_info_to_global_ids(
+ previous_catalogue
+ ),
+ current_catalogue=convert_catalogue_info_to_global_ids(
+ current_catalogue
+ ),
+ )
+ )
+
+ return SaleRemoveCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
diff --git a/saleor/graphql/discount/mutations/sale_update.py b/saleor/graphql/discount/mutations/sale_update.py
new file mode 100644
index 0000000000..4d481d3085
--- /dev/null
+++ b/saleor/graphql/discount/mutations/sale_update.py
@@ -0,0 +1,45 @@
+import graphene
+from django.db import transaction
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount import models
+from ....discount.utils import fetch_catalogue_info
+from ...core.mutations import ModelMutation
+from ...core.types import DiscountError
+from ..types import Sale
+from .sale_create import SaleInput, SaleUpdateDiscountedPriceMixin
+from .utils import convert_catalogue_info_to_global_ids
+
+
+class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a sale to update.")
+ input = SaleInput(
+ required=True, description="Fields required to update a sale."
+ )
+
+ class Meta:
+ description = "Updates a sale."
+ model = models.Sale
+ object_type = Sale
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ node_id = data.get("id")
+ instance = cls.get_node_or_error(info, node_id, only_type=Sale)
+ previous_catalogue = fetch_catalogue_info(instance)
+ response = super().perform_mutation(_root, info, **data)
+ current_catalogue = fetch_catalogue_info(instance)
+ transaction.on_commit(
+ lambda: info.context.plugins.sale_updated(
+ instance,
+ convert_catalogue_info_to_global_ids(previous_catalogue),
+ convert_catalogue_info_to_global_ids(current_catalogue),
+ )
+ )
+ return response
diff --git a/saleor/graphql/discount/mutations/utils.py b/saleor/graphql/discount/mutations/utils.py
new file mode 100644
index 0000000000..8a308eb88e
--- /dev/null
+++ b/saleor/graphql/discount/mutations/utils.py
@@ -0,0 +1,21 @@
+from collections import defaultdict
+from typing import DefaultDict, Set
+
+import graphene
+
+from ....discount.utils import CatalogueInfo
+
+
+def convert_catalogue_info_to_global_ids(
+ catalogue_info: CatalogueInfo,
+) -> DefaultDict[str, Set[str]]:
+ catalogue_fields = ["categories", "collections", "products", "variants"]
+ type_names = ["Category", "Collection", "Product", "ProductVariant"]
+ converted_catalogue_info: DefaultDict[str, Set[str]] = defaultdict(set)
+
+ for type_name, catalogue_field in zip(type_names, catalogue_fields):
+ converted_catalogue_info[catalogue_field].update(
+ graphene.Node.to_global_id(type_name, id_)
+ for id_ in catalogue_info[catalogue_field]
+ )
+ return converted_catalogue_info
diff --git a/saleor/graphql/discount/mutations/voucher_add_catalogues.py b/saleor/graphql/discount/mutations/voucher_add_catalogues.py
new file mode 100644
index 0000000000..8bb649df96
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_add_catalogues.py
@@ -0,0 +1,73 @@
+import graphene
+
+from ....core.permissions import DiscountPermissions
+from ...channel import ChannelContext
+from ...core.descriptions import ADDED_IN_31
+from ...core.types import DiscountError, NonNullList
+from ..types import Voucher
+from .sale_base_discount_catalogue import BaseDiscountCatalogueMutation
+
+
+class CatalogueInput(graphene.InputObjectType):
+ products = NonNullList(
+ graphene.ID, description="Products related to the discount.", name="products"
+ )
+ categories = NonNullList(
+ graphene.ID,
+ description="Categories related to the discount.",
+ name="categories",
+ )
+ collections = NonNullList(
+ graphene.ID,
+ description="Collections related to the discount.",
+ name="collections",
+ )
+ variants = NonNullList(
+ graphene.ID,
+ description="Product variant related to the discount." + ADDED_IN_31,
+ name="variants",
+ )
+
+
+class VoucherBaseCatalogueMutation(BaseDiscountCatalogueMutation):
+ voucher = graphene.Field(
+ Voucher, description="Voucher of which catalogue IDs will be modified."
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a voucher.")
+ input = CatalogueInput(
+ required=True,
+ description="Fields required to modify catalogue IDs of voucher.",
+ )
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def mutate(cls, root, info, **data):
+ response = super().mutate(root, info, **data)
+ if response.voucher:
+ response.voucher = ChannelContext(node=response.voucher, channel_slug=None)
+ return response
+
+
+class VoucherAddCatalogues(VoucherBaseCatalogueMutation):
+ class Meta:
+ description = "Adds products, categories, collections to a voucher."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ voucher = cls.get_node_or_error(
+ info, data.get("id"), only_type=Voucher, field="voucher_id"
+ )
+ input_data = data.get("input", {})
+ cls.add_catalogues_to_node(voucher, input_data)
+
+ if input_data:
+ info.context.plugins.voucher_updated(voucher)
+
+ return VoucherAddCatalogues(voucher=voucher)
diff --git a/saleor/graphql/discount/mutations/voucher_channel_listing_update.py b/saleor/graphql/discount/mutations/voucher_channel_listing_update.py
new file mode 100644
index 0000000000..32ad59fe18
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_channel_listing_update.py
@@ -0,0 +1,202 @@
+from collections import defaultdict
+
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import DiscountPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....discount import DiscountValueType, models
+from ....discount.error_codes import DiscountErrorCode
+from ...channel import ChannelContext
+from ...channel.mutations import BaseChannelListingMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types import DiscountError, NonNullList
+from ...core.validators import validate_price_precision
+from ..types import Voucher
+
+
+class VoucherChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ discount_value = PositiveDecimal(description="Value of the voucher.")
+ min_amount_spent = PositiveDecimal(
+ description="Min purchase amount required to apply the voucher."
+ )
+
+
+class VoucherChannelListingInput(graphene.InputObjectType):
+ add_channels = NonNullList(
+ VoucherChannelListingAddInput,
+ description="List of channels to which the voucher should be assigned.",
+ required=False,
+ )
+ remove_channels = NonNullList(
+ graphene.ID,
+ description="List of channels from which the voucher should be unassigned.",
+ required=False,
+ )
+
+
+class VoucherChannelListingUpdate(BaseChannelListingMutation):
+ voucher = graphene.Field(Voucher, description="An updated voucher instance.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a voucher to update.")
+ input = VoucherChannelListingInput(
+ required=True,
+ description="Fields required to update voucher channel listings.",
+ )
+
+ class Meta:
+ description = "Manage voucher's availability in channels."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def clean_discount_values_per_channel(cls, cleaned_input, voucher, error_dict):
+ channel_slugs_assigned_to_voucher = voucher.channel_listings.values_list(
+ "channel__slug", flat=True
+ )
+
+ for cleaned_channel in cleaned_input.get("add_channels", []):
+ channel = cleaned_channel.get("channel", None)
+ if not channel:
+ continue
+ discount_value = cleaned_channel.get("discount_value", "")
+ # New channel listing requires discout value. It raises validation error for
+ # `discout_value` == `None`.
+ # Updating channel listing doesn't require to pass `discout_value`.
+ should_create = channel.slug not in channel_slugs_assigned_to_voucher
+ missing_required_value = not discount_value and should_create
+ if missing_required_value or discount_value is None:
+ error_dict["channels_without_value"].append(
+ cleaned_channel["channel_id"]
+ )
+ # Validate value precision if it is fixed amount voucher
+ if voucher.discount_value_type == DiscountValueType.FIXED:
+ try:
+ validate_price_precision(discount_value, channel.currency_code)
+ except ValidationError:
+ error_dict["channels_with_invalid_value_precision"].append(
+ cleaned_channel["channel_id"]
+ )
+ elif voucher.discount_value_type == DiscountValueType.PERCENTAGE:
+ if discount_value > 100:
+ error_dict["channels_with_invalid_percentage_value"].append(
+ cleaned_channel["channel_id"]
+ )
+
+ min_amount_spent = cleaned_channel.get("min_amount_spent", None)
+ if min_amount_spent:
+ try:
+ validate_price_precision(min_amount_spent, channel.currency_code)
+ except ValidationError:
+ error_dict[
+ "channels_with_invalid_min_amount_spent_precision"
+ ].append(cleaned_channel["channel_id"])
+
+ @classmethod
+ def clean_discount_values(cls, cleaned_input, voucher, errors):
+ error_dict = {
+ "channels_without_value": [],
+ "channels_with_invalid_value_precision": [],
+ "channels_with_invalid_percentage_value": [],
+ "channels_with_invalid_min_amount_spent_precision": [],
+ }
+ cls.clean_discount_values_per_channel(
+ cleaned_input,
+ voucher,
+ error_dict,
+ )
+ channels_without_value = error_dict["channels_without_value"]
+ if channels_without_value:
+ errors["discount_value"].append(
+ ValidationError(
+ "Value is required for voucher.",
+ code=DiscountErrorCode.REQUIRED.value,
+ params={"channels": channels_without_value},
+ )
+ )
+
+ channels_with_invalid_value_precision = error_dict[
+ "channels_with_invalid_value_precision"
+ ]
+ if channels_with_invalid_value_precision:
+ errors["discount_value"].append(
+ ValidationError(
+ "Invalid amount precision.",
+ code=DiscountErrorCode.INVALID.value,
+ params={"channels": channels_with_invalid_value_precision},
+ )
+ )
+
+ channels_with_invalid_percentage_value = error_dict[
+ "channels_with_invalid_percentage_value"
+ ]
+ if channels_with_invalid_percentage_value:
+ errors["discount_value"].append(
+ ValidationError(
+ "Invalid percentage value.",
+ code=DiscountErrorCode.INVALID.value,
+ params={"channels": channels_with_invalid_percentage_value},
+ )
+ )
+
+ channels_with_invalid_min_amount_spent_precision = error_dict[
+ "channels_with_invalid_min_amount_spent_precision"
+ ]
+ if channels_with_invalid_min_amount_spent_precision:
+ errors["min_amount_spent"].append(
+ ValidationError(
+ "Invalid amount precision.",
+ code=DiscountErrorCode.INVALID.value,
+ params={
+ "channels": channels_with_invalid_min_amount_spent_precision
+ },
+ )
+ )
+ return cleaned_input
+
+ @classmethod
+ def add_channels(cls, voucher, add_channels):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ if "discount_value" in add_channel.keys():
+ defaults["discount_value"] = add_channel.get("discount_value")
+ if "min_amount_spent" in add_channel.keys():
+ defaults["min_spent_amount"] = add_channel.get("min_amount_spent", None)
+ models.VoucherChannelListing.objects.update_or_create(
+ voucher=voucher,
+ channel=channel,
+ defaults=defaults,
+ )
+
+ @classmethod
+ def remove_channels(cls, voucher, remove_channels):
+ voucher.channel_listings.filter(channel_id__in=remove_channels).delete()
+
+ @classmethod
+ @traced_atomic_transaction()
+ def save(cls, voucher, cleaned_input):
+ cls.add_channels(voucher, cleaned_input.get("add_channels", []))
+ cls.remove_channels(voucher, cleaned_input.get("remove_channels", []))
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ voucher = cls.get_node_or_error(info, id, only_type=Voucher, field="id")
+ errors = defaultdict(list)
+ cleaned_input = cls.clean_channels(
+ info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
+ )
+ cleaned_input = cls.clean_discount_values(cleaned_input, voucher, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(voucher, cleaned_input)
+ info.context.plugins.voucher_updated(voucher)
+
+ return VoucherChannelListingUpdate(
+ voucher=ChannelContext(node=voucher, channel_slug=None)
+ )
diff --git a/saleor/graphql/discount/mutations/voucher_create.py b/saleor/graphql/discount/mutations/voucher_create.py
new file mode 100644
index 0000000000..8d5c06a7e0
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_create.py
@@ -0,0 +1,121 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import DiscountPermissions
+from ....core.utils.promo_code import generate_promo_code, is_available_promo_code
+from ....discount import models
+from ....discount.error_codes import DiscountErrorCode
+from ...channel import ChannelContext
+from ...core.descriptions import ADDED_IN_31
+from ...core.mutations import ModelMutation
+from ...core.types import DiscountError, NonNullList
+from ...core.validators import validate_end_is_after_start
+from ..enums import DiscountValueTypeEnum, VoucherTypeEnum
+from ..types import Voucher
+
+
+class VoucherInput(graphene.InputObjectType):
+ type = VoucherTypeEnum(
+ description="Voucher type: PRODUCT, CATEGORY SHIPPING or ENTIRE_ORDER."
+ )
+ name = graphene.String(description="Voucher name.")
+ code = graphene.String(description="Code to use the voucher.")
+ start_date = graphene.types.datetime.DateTime(
+ description="Start date of the voucher in ISO 8601 format."
+ )
+ end_date = graphene.types.datetime.DateTime(
+ description="End date of the voucher in ISO 8601 format."
+ )
+ discount_value_type = DiscountValueTypeEnum(
+ description="Choices: fixed or percentage."
+ )
+ products = NonNullList(
+ graphene.ID, description="Products discounted by the voucher.", name="products"
+ )
+ variants = NonNullList(
+ graphene.ID,
+ description="Variants discounted by the voucher." + ADDED_IN_31,
+ name="variants",
+ )
+ collections = NonNullList(
+ graphene.ID,
+ description="Collections discounted by the voucher.",
+ name="collections",
+ )
+ categories = NonNullList(
+ graphene.ID,
+ description="Categories discounted by the voucher.",
+ name="categories",
+ )
+ min_checkout_items_quantity = graphene.Int(
+ description="Minimal quantity of checkout items required to apply the voucher."
+ )
+ countries = NonNullList(
+ graphene.String,
+ description="Country codes that can be used with the shipping voucher.",
+ )
+ apply_once_per_order = graphene.Boolean(
+ description="Voucher should be applied to the cheapest item or entire order."
+ )
+ apply_once_per_customer = graphene.Boolean(
+ description="Voucher should be applied once per customer."
+ )
+ only_for_staff = graphene.Boolean(
+ description="Voucher can be used only by staff user."
+ )
+ usage_limit = graphene.Int(
+ description="Limit number of times this voucher can be used in total."
+ )
+
+
+class VoucherCreate(ModelMutation):
+ class Arguments:
+ input = VoucherInput(
+ required=True, description="Fields required to create a voucher."
+ )
+
+ class Meta:
+ description = "Creates a new voucher."
+ model = models.Voucher
+ object_type = Voucher
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ code = data.get("code", None)
+ if code == "":
+ data["code"] = generate_promo_code()
+ elif not is_available_promo_code(code):
+ raise ValidationError(
+ {
+ "code": ValidationError(
+ "Promo code already exists.",
+ code=DiscountErrorCode.ALREADY_EXISTS,
+ )
+ }
+ )
+ cleaned_input = super().clean_input(info, instance, data)
+
+ return cleaned_input
+
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ super().clean_instance(info, instance)
+ start_date = instance.start_date
+ end_date = instance.end_date
+ try:
+ validate_end_is_after_start(start_date, end_date)
+ except ValidationError as error:
+ error.code = DiscountErrorCode.INVALID.value
+ raise ValidationError({"end_date": error})
+
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.voucher_created(instance)
diff --git a/saleor/graphql/discount/mutations/voucher_delete.py b/saleor/graphql/discount/mutations/voucher_delete.py
new file mode 100644
index 0000000000..7b5533585b
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_delete.py
@@ -0,0 +1,32 @@
+import graphene
+
+from saleor.discount import models
+
+from ....core.permissions import DiscountPermissions
+from ...channel import ChannelContext
+from ...core.mutations import ModelDeleteMutation
+from ...core.types import DiscountError
+from ..types import Voucher
+
+
+class VoucherDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a voucher to delete.")
+
+ class Meta:
+ description = "Deletes a voucher."
+ model = models.Voucher
+ object_type = Voucher
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(instance)
+ return response
+
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.voucher_deleted(instance)
diff --git a/saleor/graphql/discount/mutations/voucher_remove_catalogues.py b/saleor/graphql/discount/mutations/voucher_remove_catalogues.py
new file mode 100644
index 0000000000..edc504a3fd
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_remove_catalogues.py
@@ -0,0 +1,25 @@
+from ....core.permissions import DiscountPermissions
+from ...core.types import DiscountError
+from ..types import Voucher
+from .voucher_add_catalogues import VoucherBaseCatalogueMutation
+
+
+class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):
+ class Meta:
+ description = "Removes products, categories, collections from a voucher."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ voucher = cls.get_node_or_error(
+ info, data.get("id"), only_type=Voucher, field="voucher_id"
+ )
+ input_data = data.get("input", {})
+ cls.remove_catalogues_from_node(voucher, input_data)
+
+ if input_data:
+ info.context.plugins.voucher_updated(voucher)
+
+ return VoucherRemoveCatalogues(voucher=voucher)
diff --git a/saleor/graphql/discount/mutations/voucher_update.py b/saleor/graphql/discount/mutations/voucher_update.py
new file mode 100644
index 0000000000..7fb492256a
--- /dev/null
+++ b/saleor/graphql/discount/mutations/voucher_update.py
@@ -0,0 +1,27 @@
+import graphene
+
+from ....core.permissions import DiscountPermissions
+from ....discount import models
+from ...core.types import DiscountError
+from ..types import Voucher
+from .voucher_create import VoucherCreate, VoucherInput
+
+
+class VoucherUpdate(VoucherCreate):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a voucher to update.")
+ input = VoucherInput(
+ required=True, description="Fields required to update a voucher."
+ )
+
+ class Meta:
+ description = "Updates a voucher."
+ model = models.Voucher
+ object_type = Voucher
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.voucher_updated(instance)
diff --git a/saleor/graphql/discount/schema.py b/saleor/graphql/discount/schema.py
index c91ee08730..3f75cca9a3 100644
--- a/saleor/graphql/discount/schema.py
+++ b/saleor/graphql/discount/schema.py
@@ -9,20 +9,18 @@ from ..core.utils import from_global_id_or_error
from ..translations.mutations import SaleTranslate, VoucherTranslate
from .bulk_mutations import SaleBulkDelete, VoucherBulkDelete
from .filters import SaleFilter, VoucherFilter
-from .mutations import (
- SaleAddCatalogues,
- SaleChannelListingUpdate,
- SaleCreate,
- SaleDelete,
- SaleRemoveCatalogues,
- SaleUpdate,
- VoucherAddCatalogues,
- VoucherChannelListingUpdate,
- VoucherCreate,
- VoucherDelete,
- VoucherRemoveCatalogues,
- VoucherUpdate,
-)
+from .mutations.sale_add_catalogues import SaleAddCatalogues
+from .mutations.sale_channel_listing_update import SaleChannelListingUpdate
+from .mutations.sale_create import SaleCreate
+from .mutations.sale_delete import SaleDelete
+from .mutations.sale_remove_catalogues import SaleRemoveCatalogues
+from .mutations.sale_update import SaleUpdate
+from .mutations.voucher_add_catalogues import VoucherAddCatalogues
+from .mutations.voucher_channel_listing_update import VoucherChannelListingUpdate
+from .mutations.voucher_create import VoucherCreate
+from .mutations.voucher_delete import VoucherDelete
+from .mutations.voucher_remove_catalogues import VoucherRemoveCatalogues
+from .mutations.voucher_update import VoucherUpdate
from .resolvers import resolve_sale, resolve_sales, resolve_voucher, resolve_vouchers
from .sorters import SaleSortingInput, VoucherSortingInput
from .types import Sale, SaleCountableConnection, Voucher, VoucherCountableConnection
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 591a0214e3..343b79c87c 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -12,7 +12,6 @@ from ....discount import DiscountValueType, VoucherType
from ....discount.error_codes import DiscountErrorCode
from ....discount.models import Sale, SaleChannelListing, Voucher
from ....discount.utils import fetch_catalogue_info
-from ....graphql.discount.mutations import convert_catalogue_info_to_global_ids
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.payloads import generate_meta, generate_requestor
from ...tests.utils import (
@@ -21,6 +20,7 @@ from ...tests.utils import (
get_graphql_content_from_response,
)
from ..enums import DiscountValueTypeEnum, VoucherTypeEnum
+from ..mutations.utils import convert_catalogue_info_to_global_ids
@pytest.fixture
diff --git a/saleor/graphql/discount/tests/test_sale_channel_listing.py b/saleor/graphql/discount/tests/test_sale_channel_listing.py
index 02335e2cd8..5e273221a8 100644
--- a/saleor/graphql/discount/tests/test_sale_channel_listing.py
+++ b/saleor/graphql/discount/tests/test_sale_channel_listing.py
@@ -34,7 +34,7 @@ mutation UpdateSaleChannelListing(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_channel_listing_update"
".update_products_discounted_prices_of_discount_task"
)
def test_sale_channel_listing_create_as_staff_user(
@@ -82,7 +82,7 @@ def test_sale_channel_listing_create_as_staff_user(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_channel_listing_update"
".update_products_discounted_prices_of_discount_task"
)
def test_sale_channel_listing_update_as_staff_user(
diff --git a/saleor/graphql/product/tests/test_product_discounted_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
index 67333e827e..a25fa33b9d 100644
--- a/saleor/graphql/product/tests/test_product_discounted_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -178,7 +178,7 @@ def test_collection_remove_products_updates_discounted_price(
@freeze_time("2010-05-31 12:00:01")
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_create"
".update_products_discounted_prices_of_discount_task"
)
def test_sale_create_updates_products_discounted_prices(
@@ -231,7 +231,7 @@ def test_sale_create_updates_products_discounted_prices(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_create"
".update_products_discounted_prices_of_discount_task"
)
def test_sale_update_updates_products_discounted_prices(
@@ -268,7 +268,7 @@ def test_sale_update_updates_products_discounted_prices(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_create"
".update_products_discounted_prices_of_discount_task"
)
def test_sale_delete_updates_products_discounted_prices(
@@ -305,7 +305,7 @@ def test_sale_delete_updates_products_discounted_prices(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_base_discount_catalogue"
".update_products_discounted_prices_of_catalogues_task"
)
def test_sale_add_catalogues_updates_products_discounted_prices(
@@ -365,7 +365,7 @@ def test_sale_add_catalogues_updates_products_discounted_prices(
@patch(
- "saleor.graphql.discount.mutations"
+ "saleor.graphql.discount.mutations.sale_base_discount_catalogue"
".update_products_discounted_prices_of_catalogues_task"
)
def test_sale_remove_catalogues_updates_products_discounted_prices(
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index da45239fe7..8b459aae72 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1,7 +1,18 @@
from copy import copy
from dataclasses import dataclass
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ DefaultDict,
+ Iterable,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ Union,
+)
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
@@ -39,7 +50,6 @@ if TYPE_CHECKING:
from ..discount import DiscountInfo, Voucher
from ..discount.models import Sale
from ..giftcard.models import GiftCard
- from ..graphql.discount.mutations import NodeCatalogueInfo
from ..invoice.models import Invoice
from ..menu.models import Menu, MenuItem
from ..order.models import Fulfillment, Order, OrderLine
@@ -724,17 +734,19 @@ class BasePlugin:
# Trigger when sale is created.
#
# Overwrite this method if you need to trigger specific logic after sale is created.
- sale_created: Callable[["Sale", "NodeCatalogueInfo", Any], Any]
+ sale_created: Callable[["Sale", DefaultDict[str, Set[str]], Any], Any]
# Trigger when sale is deleted.
#
# Overwrite this method if you need to trigger specific logic after sale is deleted.
- sale_deleted: Callable[["Sale", "NodeCatalogueInfo", Any], Any]
+ sale_deleted: Callable[["Sale", DefaultDict[str, Set[str]], Any], Any]
# Trigger when sale is updated.
#
# Overwrite this method if you need to trigger specific logic after sale is updated.
- sale_updated: Callable[["Sale", "NodeCatalogueInfo", "NodeCatalogueInfo", Any], Any]
+ sale_updated: Callable[
+ ["Sale", DefaultDict[str, Set[str]], DefaultDict[str, Set[str]], Any], Any
+ ]
# Trigger when shipping price is created.
#
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index f7eb61bac9..0d92fc224a 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -1,5 +1,14 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Iterable, Optional, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ DefaultDict,
+ Iterable,
+ Optional,
+ Set,
+ Tuple,
+ Union,
+)
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
@@ -23,7 +32,6 @@ if TYPE_CHECKING:
from ...checkout.models import Checkout
from ...discount import DiscountInfo
from ...discount.models import Sale
- from ...graphql.discount.mutations import NodeCatalogueInfo
from ...order.models import Order, OrderLine
from ...product.models import Product, ProductType, ProductVariant
@@ -206,21 +214,27 @@ class PluginSample(BasePlugin):
return {"logoutUrl": "http://www.auth.provider.com/logout/"}
def sale_created(
- self, sale: "Sale", current_catalogue: "NodeCatalogueInfo", previous_value: Any
+ self,
+ sale: "Sale",
+ current_catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
):
return sale, current_catalogue
def sale_updated(
self,
sale: "Sale",
- previous_catalogue: "NodeCatalogueInfo",
- current_catalogue: "NodeCatalogueInfo",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: DefaultDict[str, Set[str]],
previous_value: Any,
):
return sale, previous_catalogue, current_catalogue
def sale_deleted(
- self, sale: "Sale", previous_catalogue: "NodeCatalogueInfo", previous_value: Any
+ self,
+ sale: "Sale",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
):
return sale, previous_catalogue
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index dbf2900dad..8fac6ef8a5 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -12,7 +12,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
from ...core.taxes import TaxType, zero_taxed_money
from ...discount.utils import fetch_catalogue_info
-from ...graphql.discount.mutations import convert_catalogue_info_to_global_ids
+from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
from ...payment.interface import PaymentGateway
from ...product.models import Product
from ..base_plugin import ExternalAccessTokens
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 9e2a863a02..db0b2ad96b 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1,6 +1,6 @@
import json
import logging
-from typing import TYPE_CHECKING, Any, List, Optional, Union
+from typing import TYPE_CHECKING, Any, DefaultDict, List, Optional, Set, Union
import graphene
@@ -56,7 +56,6 @@ if TYPE_CHECKING:
from ...checkout.models import Checkout
from ...discount.models import Sale, Voucher
from ...giftcard.models import GiftCard
- from ...graphql.discount.mutations import NodeCatalogueInfo
from ...invoice.models import Invoice
from ...menu.models import Menu, MenuItem
from ...order.models import Fulfillment, Order
@@ -385,7 +384,10 @@ class WebhookPlugin(BasePlugin):
)
def sale_created(
- self, sale: "Sale", current_catalogue: "NodeCatalogueInfo", previous_value: Any
+ self,
+ sale: "Sale",
+ current_catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
) -> Any:
if not self.active:
return previous_value
@@ -404,8 +406,8 @@ class WebhookPlugin(BasePlugin):
def sale_updated(
self,
sale: "Sale",
- previous_catalogue: "NodeCatalogueInfo",
- current_catalogue: "NodeCatalogueInfo",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: DefaultDict[str, Set[str]],
previous_value: Any,
) -> Any:
if not self.active:
@@ -420,7 +422,10 @@ class WebhookPlugin(BasePlugin):
)
def sale_deleted(
- self, sale: "Sale", previous_catalogue: "NodeCatalogueInfo", previous_value: Any
+ self,
+ sale: "Sale",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ previous_value: Any,
) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 837e0a6630..4583a2a7af 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -28,7 +28,7 @@ from ....core.notification.utils import get_site_context
from ....core.notify_events import NotifyEventType
from ....core.utils.url import prepare_url
from ....discount.utils import fetch_catalogue_info
-from ....graphql.discount.mutations import convert_catalogue_info_to_global_ids
+from ....graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
from ....payment import TransactionAction
from ....payment.interface import TransactionActionData
from ....payment.models import TransactionItem
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index cfd945bd9f..8c4153b778 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -2,7 +2,7 @@ import json
import uuid
from collections import defaultdict
from dataclasses import asdict
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional
+from typing import TYPE_CHECKING, Any, DefaultDict, Dict, Iterable, List, Optional, Set
import graphene
from django.contrib.auth.models import AnonymousUser
@@ -48,7 +48,6 @@ if TYPE_CHECKING:
if TYPE_CHECKING:
from ..discount.models import Sale
- from ..graphql.discount.mutations import NodeCatalogueInfo
from ..invoice.models import Invoice
from ..payment.interface import PaymentData, TransactionActionData
from ..payment.models import Payment
@@ -360,16 +359,16 @@ def _generate_order_payment_payload(payments: Iterable["Payment"]):
def _calculate_added(
- previous_catalogue: "NodeCatalogueInfo",
- current_catalogue: "NodeCatalogueInfo",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: DefaultDict[str, Set[str]],
key: str,
) -> List[str]:
return list(current_catalogue[key] - previous_catalogue[key])
def _calculate_removed(
- previous_catalogue: "NodeCatalogueInfo",
- current_catalogue: "NodeCatalogueInfo",
+ previous_catalogue: DefaultDict[str, Set[str]],
+ current_catalogue: DefaultDict[str, Set[str]],
key: str,
) -> List[str]:
return _calculate_added(current_catalogue, previous_catalogue, key)
@@ -378,8 +377,8 @@ def _calculate_removed(
@traced_payload_generator
def generate_sale_payload(
sale: "Sale",
- previous_catalogue: Optional["NodeCatalogueInfo"] = None,
- current_catalogue: Optional["NodeCatalogueInfo"] = None,
+ previous_catalogue: Optional[DefaultDict[str, Set[str]]] = None,
+ current_catalogue: Optional[DefaultDict[str, Set[str]]] = None,
requestor: Optional["RequestorOrLazyObject"] = None,
):
if previous_catalogue is None: