Skip to content

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

Merge branch 'master' of github.com:mirumee/saleor into SALEOR-2545-variant-channel-listing

Damian We358bbdbb0c1
diff --cc saleor/graphql/channel/mutations.py
index 025ae932c2,36352ba465..09088d9a9c
--- a/saleor/graphql/channel/mutations.py
+++ b/saleor/graphql/channel/mutations.py
@@@ -230,13 -230,8 +230,10 @@@ class BaseChannelListingMutation(BaseMu
)
@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
++ cls, info, input, errors: ErrorType, error_code, input_source="add_channels"
+ ) -> 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(
@@@ -269,10 -264,8 +266,8 @@@
return cleaned_input
@classmethod
- def clean_publication_date(cls, cleaned_input, input_source=None):
- if not input_source:
- input_source = "add_channels"
- 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="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 --cc saleor/graphql/product/mutations/channels.py
index 37196ba46f,aabdd98a7b..67810ad8ec
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@@ -24,8 -23,8 +24,9 @@@ from ...core.types.common import
CollectionChannelListingError,
ProductChannelListingError,
)
- from ...core.utils import get_duplicated_values, get_duplicates_ids
+ from ...core.utils import get_duplicated_values
from ...core.validators import validate_price_precision
++from ...utils.validators import check_for_duplicates
from ..types.products import Collection, Product, ProductVariant
if TYPE_CHECKING:
@@@ -110,12 -97,12 +111,14 @@@ class ProductChannelListingUpdate(BaseC
@classmethod
def clean_available_for_purchase(cls, cleaned_input, errors: ErrorType):
channels_with_invalid_available_for_purchase = []
- for add_channel in cleaned_input.get("update_channels", []):
- for add_channel in cleaned_input.get("add_channels", []):
-- is_available_for_purchase = add_channel.get("is_available_for_purchase")
-- available_for_purchase_date = add_channel.get("available_for_purchase_date")
++ for update_variant in cleaned_input.get("update_channels", []):
++ is_available_for_purchase = update_variant.get("is_available_for_purchase")
++ available_for_purchase_date = update_variant.get(
++ "available_for_purchase_date"
++ )
if not is_available_for_purchase and available_for_purchase_date:
channels_with_invalid_available_for_purchase.append(
-- add_channel["channel_id"]
++ update_variant["channel_id"]
)
if channels_with_invalid_available_for_purchase:
error_msg = (
@@@ -133,10 -120,10 +136,10 @@@
@classmethod
def validate_product_without_category(cls, cleaned_input, errors: ErrorType):
channels_with_published_product_without_category = []
- for add_channel in cleaned_input.get("update_channels", []):
- for add_channel in cleaned_input.get("add_channels", []):
-- if add_channel.get("is_published") is True:
++ for update_channel in cleaned_input.get("update_channels", []):
++ if update_channel.get("is_published") is True:
channels_with_published_product_without_category.append(
-- add_channel["channel_id"]
++ update_channel["channel_id"]
)
if channels_with_published_product_without_category:
errors["is_published"].append(
@@@ -150,17 -137,15 +153,19 @@@
)
@classmethod
- def add_channels(cls, info, product: "ProductModel", add_channels: List[Dict]):
- def add_channels(cls, 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)
++ def update_channels(cls, product: "ProductModel", update_channels: List[Dict]):
++ for update_channel in update_channels:
++ channel = update_channel["channel"]
++ add_variants = update_channel.get("add_variants", None)
++ remove_variants = update_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():
-- defaults[field] = add_channel.get(field, None)
-- is_available_for_purchase = add_channel.get("is_available_for_purchase")
-- available_for_purchase_date = add_channel.get("available_for_purchase_date")
++ if field in update_channel.keys():
++ defaults[field] = update_channel.get(field, None)
++ is_available_for_purchase = update_channel.get("is_available_for_purchase")
++ available_for_purchase_date = update_channel.get(
++ "available_for_purchase_date"
++ )
if is_available_for_purchase is not None:
if is_available_for_purchase is False:
defaults["available_for_purchase"] = None
@@@ -171,103 -156,12 +176,72 @@@
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.add_variants(channel, add_variants)
+ cls.remove_variants(
- info, product_channel_listing, product, channel, remove_variants
++ 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)},
- )
++ def validate_variants(cls, input, errors):
++ for update_channel in input.get("update_channels", []):
++ error = check_for_duplicates(
++ update_channel, "add_variants", "remove_variants", "variants"
+ )
++ if error:
++ error.code = ProductErrorCode.DUPLICATED_INPUT_ITEM.value
++ errors["addVariants"].append(error)
+
+ @classmethod
- def add_variants(cls, info, channel, add_variants: List[Dict]):
++ def add_variants(cls, 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
- ]
-
++ variants_id = cls.get_nodes_or_error(add_variants, "id", ProductVariant)
+ 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.ALREADY_EXISTS.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
- ]
++ variants_id = cls.get_nodes_or_error(remove_variants, "id", ProductVariant)
+ 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()
@@@ -278,7 -172,7 +252,7 @@@
@classmethod
@transaction.atomic()
def save(cls, info, product: "ProductModel", cleaned_input: Dict):
- cls.add_channels(info, product, cleaned_input.get("update_channels", []))
- cls.add_channels(product, cleaned_input.get("add_channels", []))
++ cls.update_channels(product, cleaned_input.get("update_channels", []))
cls.remove_channels(product, cleaned_input.get("remove_channels", []))
info.context.plugins.product_updated(product)
@@@ -292,10 -186,9 +266,11 @@@
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)
++ cls.validate_variants(cleaned_input, errors)
if not product.category:
cls.validate_product_without_category(cleaned_input, errors)
if errors:
diff --cc saleor/graphql/product/tests/test_product_channel_listing_update.py
index a6e3f1d83a,61352ec298..cbd0b23b04
--- a/saleor/graphql/product/tests/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_product_channel_listing_update.py
@@@ -1002,227 -988,3 +1002,227 @@@ def test_product_channel_listing_update
assert errors[0]["code"] == ProductErrorCode.PRODUCT_WITHOUT_CATEGORY.name
assert errors[0]["channels"] == [channel_usd_id]
assert len(errors) == 1
+
+
+def test_product_channel_listing_add_variant_as_staff_user(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product.variants.all().delete()
+ variant_1 = ProductVariant.objects.create(product=product, sku="321")
+ variant_2 = ProductVariant.objects.create(product=product, sku="333")
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.pk)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", variant_2.pk)
+ variants = [variant_1_id, variant_2_id]
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [{"channelId": channel_id, "addVariants": variants}]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ variant_data = data["product"]["variants"]
+
+ assert not data["productChannelListingErrors"]
+ assert variant_data[0]["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert variant_data[1]["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_product_channel_listing_add_variant_as_app(
+ app_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product.variants.all().delete()
+ variant_1 = ProductVariant.objects.create(product=product, sku="321")
+ variant_2 = ProductVariant.objects.create(product=product, sku="333")
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.pk)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", variant_2.pk)
+ variants = [variant_1_id, variant_2_id]
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [{"channelId": channel_id, "addVariants": variants}]
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ variant_data = data["product"]["variants"]
+
+ assert not data["productChannelListingErrors"]
+ assert variant_data[0]["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert variant_data[1]["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_product_channel_listing_remove_variant_as_staff_user(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ variant = product.variants.first()
+ ProductVariantChannelListing.objects.create(channel=channel_PLN, variant=variant)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [
+ {"channelId": channel_id, "removeVariants": [variant_id]}
+ ]
+ },
+ }
+
+ assert len(variant.channel_listings.all()) == 2
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ assert not data["productChannelListingErrors"]
+
+ assert len(variant.channel_listings.all()) == 1
+
+
+def test_product_channel_listing_remove_variant_as_app(
+ app_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ variant = product.variants.first()
+ ProductVariantChannelListing.objects.create(channel=channel_PLN, variant=variant)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [
+ {"channelId": channel_id, "removeVariants": [variant_id]}
+ ]
+ },
+ }
+
+ assert len(variant.channel_listings.all()) == 2
+ # when
+ response = app_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ assert not data["productChannelListingErrors"]
+
+ assert len(variant.channel_listings.all()) == 1
+
+
+def test_product_channel_listing_add_variant_duplicated_ids_in_add_and_remove(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ variant = product.variants.first()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variants = [variant_id]
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": True,
+ "addVariants": variants,
+ "removeVariants": variants,
+ }
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
- assert errors[0]["field"] == "input"
++ assert errors[0]["field"] == "addVariants"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["variants"] == variants
+
+
+def test_product_channel_listing_add_variant_with_existing_channel_listing(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ variant = product.variants.first()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variants = [variant_id]
+ variables = {
+ "id": product_id,
+ "input": {
+ "updateChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": True,
+ "addVariants": variants,
+ }
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addVariants"
+ assert errors[0]["code"] == ProductErrorCode.ALREADY_EXISTS.name