Skip to content

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

Assing variants to channel

Damian Wfe74e381ac14
diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.py
index 36352ba465..025ae932c2 100644
--- a/saleor/graphql/channel/mutations.py
+++ b/saleor/graphql/channel/mutations.py
@@ -230,15 +230,20 @@ class BaseChannelListingMutation(BaseMutation):
)
@classmethod
- def clean_channels(cls, info, input, errors: ErrorType, error_code) -> Dict:
- add_channels = input.get("add_channels", [])
+ def clean_channels(
+ cls, info, input, errors: ErrorType, error_code, input_source=None
+ ) -> Dict:
+ if not input_source:
+ input_source = "add_channels"
+
+ add_channels = input.get(input_source, [])
add_channels_ids = [channel["channel_id"] for channel in add_channels]
remove_channels_ids = input.get("remove_channels", [])
cls.validate_duplicated_channel_ids(
add_channels_ids, remove_channels_ids, errors, error_code
)
cls.validate_duplicated_channel_values(
- add_channels_ids, "add_channels", errors, error_code
+ add_channels_ids, input_source, errors, error_code
)
cls.validate_duplicated_channel_values(
remove_channels_ids, "remove_channels", errors, error_code
@@ -255,17 +260,19 @@ class BaseChannelListingMutation(BaseMutation):
remove_channels_ids, Channel
)
- cleaned_input = {"add_channels": [], "remove_channels": remove_channels_pks}
+ cleaned_input = {input_source: [], "remove_channels": remove_channels_pks}
for channel_listing, channel in zip(add_channels, channels_to_add):
channel_listing["channel"] = channel
- cleaned_input["add_channels"].append(channel_listing)
+ cleaned_input[input_source].append(channel_listing)
return cleaned_input
@classmethod
- def clean_publication_date(cls, cleaned_input):
- for add_channel in cleaned_input.get("add_channels", []):
+ def clean_publication_date(cls, cleaned_input, input_source=None):
+ if not input_source:
+ input_source = "add_channels"
+ for add_channel in cleaned_input.get(input_source, []):
is_published = add_channel.get("is_published")
publication_date = add_channel.get("publication_date")
if is_published and not publication_date:
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index c8710c0059..a9f09bb21a 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -216,6 +216,11 @@ class ProductChannelListingError(ProductError):
description="List of channels IDs which causes the error.",
required=False,
)
+ variants = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of variants IDs which causes the error.",
+ required=False,
+ )
class CollectionChannelListingError(ProductError):
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index aabdd98a7b..a16c09c779 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -1,10 +1,11 @@
import datetime
from collections import defaultdict
-from typing import TYPE_CHECKING, DefaultDict, Dict, List
+from typing import TYPE_CHECKING, DefaultDict, Dict, Iterable, List
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
+from django.db.utils import IntegrityError
from ....core.permissions import ProductPermissions
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
@@ -23,7 +24,7 @@ from ...core.types.common import (
CollectionChannelListingError,
ProductChannelListingError,
)
-from ...core.utils import get_duplicated_values
+from ...core.utils import get_duplicated_values, get_duplicates_ids
from ...core.validators import validate_price_precision
from ..types.products import Collection, Product, ProductVariant
@@ -63,12 +64,24 @@ class ProductChannelListingAddInput(PublishableChannelListingInput):
"the current day is assumed."
)
)
+ add_variants = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of variants to which the channel should be assigned.",
+ required=False,
+ )
+ remove_variants = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of variants from which the channel should be unassigned.",
+ required=False,
+ )
class ProductChannelListingUpdateInput(graphene.InputObjectType):
- add_channels = graphene.List(
+ update_channels = graphene.List(
graphene.NonNull(ProductChannelListingAddInput),
- description="List of channels to which the product should be assigned.",
+ description=(
+ "List of channels to which the product should be assigned or updated."
+ ),
required=False,
)
remove_channels = graphene.List(
@@ -97,7 +110,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def clean_available_for_purchase(cls, cleaned_input, errors: ErrorType):
channels_with_invalid_available_for_purchase = []
- for add_channel in cleaned_input.get("add_channels", []):
+ for add_channel in cleaned_input.get("update_channels", []):
is_available_for_purchase = add_channel.get("is_available_for_purchase")
available_for_purchase_date = add_channel.get("available_for_purchase_date")
if not is_available_for_purchase and available_for_purchase_date:
@@ -120,7 +133,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
@classmethod
def validate_product_without_category(cls, cleaned_input, errors: ErrorType):
channels_with_published_product_without_category = []
- for add_channel in cleaned_input.get("add_channels", []):
+ for add_channel in cleaned_input.get("update_channels", []):
if add_channel.get("is_published") is True:
channels_with_published_product_without_category.append(
add_channel["channel_id"]
@@ -137,9 +150,11 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
)
@classmethod
- def add_channels(cls, product: "ProductModel", add_channels: List[Dict]):
+ def add_channels(cls, info, product: "ProductModel", add_channels: List[Dict]):
for add_channel in add_channels:
channel = add_channel["channel"]
+ add_variants = add_channel.get("add_variants", None)
+ remove_variants = add_channel.get("remove_variants", None)
defaults = {"currency": channel.currency_code}
for field in ["is_published", "publication_date", "visible_in_listings"]:
if field in add_channel.keys():
@@ -156,12 +171,103 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
defaults["available_for_purchase"] = datetime.date.today()
else:
defaults["available_for_purchase"] = available_for_purchase_date
- ProductChannelListing.objects.update_or_create(
+ product_channel_listing, _ = ProductChannelListing.objects.update_or_create(
product=product, channel=channel, defaults=defaults
)
+ cls.validate_variants(add_variants, remove_variants)
+ cls.add_variants(info, channel, add_variants)
+ cls.remove_variants(
+ info, product_channel_listing, product, channel, remove_variants
+ )
+
+ @classmethod
+ def validate_variants(cls, add_variants, remove_variants):
+ error_code = ProductErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+ cls.validate_duplicated_variant_ids(
+ add_variants, remove_variants, errors, error_code
+ )
+ if errors:
+ raise ValidationError(errors)
+
+ @classmethod
+ def validate_duplicated_variant_ids(
+ cls,
+ add_variant_ids: Iterable[str],
+ remove_variant_ids: Iterable[str],
+ errors: ErrorType,
+ error_code,
+ ):
+ duplicated_ids = get_duplicates_ids(add_variant_ids, remove_variant_ids)
+ if duplicated_ids:
+ error_msg = (
+ "The same object cannot be in both lists "
+ "for adding and removing items."
+ )
+ errors["input"].append(
+ ValidationError(
+ error_msg,
+ code=error_code,
+ params={"variants": list(duplicated_ids)},
+ )
+ )
+
+ @classmethod
+ def add_variants(cls, info, channel, add_variants: List[Dict]):
+ if not add_variants:
+ return
+ variants_id = [
+ cls.get_node_or_error(info, id, only_type=ProductVariant, field="id")
+ for id in add_variants
+ ]
+
+ variant_channel_listings = []
+ for variant in variants_id:
+ variant_channel_listings.append(
+ ProductVariantChannelListing(channel=channel, variant=variant)
+ )
+
+ try:
+ ProductVariantChannelListing.objects.bulk_create(variant_channel_listings)
+ except IntegrityError:
+ raise ValidationError(
+ {
+ "addVariants": ValidationError(
+ "One of channel listing already "
+ "exists for this product variant.",
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ )
+ }
+ )
+
+ @classmethod
+ def remove_variants(
+ cls,
+ info,
+ product_channel_listing,
+ product,
+ channel,
+ remove_variants: List[Dict],
+ ):
+ if not remove_variants:
+ return
+ variants_id = [
+ cls.get_node_or_error(info, id, only_type=ProductVariant, field="id")
+ for id in remove_variants
+ ]
+ if (
+ len(variants_id)
+ == ProductVariantChannelListing.objects.filter(
+ channel=channel, variant__product_id=product
+ ).count()
+ ):
+ product_channel_listing.delete()
+ ProductVariantChannelListing.objects.filter(
+ channel=channel, variant_id__in=variants_id
+ ).delete()
@classmethod
- def remove_channels(cls, product: "ProductModel", remove_channels: List[int]):
+ def remove_channels(cls, product: "ProductModel", remove_channels: List[Dict]):
ProductChannelListing.objects.filter(
product=product, channel_id__in=remove_channels
).delete()
@@ -172,7 +278,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
@classmethod
@transaction.atomic()
def save(cls, info, product: "ProductModel", cleaned_input: Dict):
- cls.add_channels(product, cleaned_input.get("add_channels", []))
+ cls.add_channels(info, product, cleaned_input.get("update_channels", []))
cls.remove_channels(product, cleaned_input.get("remove_channels", []))
info.context.plugins.product_updated(product)
@@ -186,8 +292,9 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
input,
errors,
ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ input_source="update_channels",
)
- cls.clean_publication_date(cleaned_input)
+ cls.clean_publication_date(cleaned_input, input_source="update_channels")
cls.clean_available_for_purchase(cleaned_input, errors)
if not product.category:
cls.validate_product_without_category(cleaned_input, errors)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 4a5b97ca62..7011ae8339 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3914,6 +3914,8 @@ input ProductChannelListingAddInput {
visibleInListings: Boolean
isAvailableForPurchase: Boolean
availableForPurchaseDate: Date
+ addVariants: [ID!]
+ removeVariants: [ID!]
}
type ProductChannelListingError {
@@ -3923,6 +3925,7 @@ type ProductChannelListingError {
attributes: [ID!]
values: [ID!]
channels: [ID!]
+ variants: [ID!]
}
type ProductChannelListingUpdate {
@@ -3932,7 +3935,7 @@ type ProductChannelListingUpdate {
}
input ProductChannelListingUpdateInput {
- addChannels: [ProductChannelListingAddInput!]
+ updateChannels: [ProductChannelListingAddInput!]
removeChannels: [ID!]
}
diff --git a/saleor/product/migrations/0142_auto_20210304_1052.py b/saleor/product/migrations/0142_auto_20210304_1052.py
new file mode 100644
index 0000000000..06b84539a9
--- /dev/null
+++ b/saleor/product/migrations/0142_auto_20210304_1052.py
@@ -0,0 +1,20 @@
+# Generated by Django 3.1.7 on 2021-03-04 10:52
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0141_update_descritpion_fields"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="productvariantchannellisting",
+ name="price_amount",
+ field=models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 2d632e4f11..b8fcba1c49 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -556,6 +556,8 @@ class ProductVariantChannelListing(models.Model):
price_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ blank=True,
+ null=True,
)
price = MoneyField(amount_field="price_amount", currency_field="currency")