Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix productVariantBulkUpdate 500 error on duplicate channel listing create (#19355)
ayesha waris54b8326112fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 194ea57e07..03f20574f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,7 @@ All notable, unreleased changes to this project will be documented in this file.- Removed the deprecated `variant` field from the `Product` type. Use the top-level `variant` query instead.- Removed the deprecated `note` field from the `Checkout` type. Use `customerNote` instead.- Removed the deprecated `isDigital` field from the `ProductType` type, the `isDigital` input from `ProductTypeInput`, the `DIGITAL` value from the `ProductTypeEnum` filter, and the `DIGITAL` value from `ProductTypeSortField`. These had no effect; use metadata or attributes instead (or `SHIPPING_REQUIRED` for sorting).+- Fixed `productVariantBulkUpdate` returning a 500 error when `channelListings.create` targeted a channel the variant was already listed in. The mutation now returns a `DUPLICATED_INPUT_ITEM` error recommending the `update` field, and respects the selected `errorPolicy` - #19355 by @ayesha-waris### Webhooksdiff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.pyindex 4a3487df32..497c16392e 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py@@ -394,7 +394,17 @@ class ProductVariantBulkCreate(BaseMutation):variant_index,index_error_map,path_prefix="channelListings",+ existing_channel_ids=None,):+ """Validate channel listings to create for a variant.++ ``existing_channel_ids`` holds the channel global IDs the variant is+ already listed on (only relevant when updating). Listings targeting one+ of them produce a ``DUPLICATED_INPUT_ITEM`` error and are dropped from+ the result, so the unique ``(variant, channel)`` constraint never raises+ an ``IntegrityError`` at insert time.+ """+ existing_channel_ids = existing_channel_ids or set()channel_ids = [channel_listing["channel_id"] for channel_listing in channel_listings]@@ -433,6 +443,22 @@ class ProductVariantBulkCreate(BaseMutation):channel_id = channel_listing["channel_id"]errors_count_before_prices = len(index_error_map[variant_index])+ if channel_id in existing_channel_ids:+ index_error_map[variant_index].append(+ ProductVariantBulkError(+ field="channelId",+ path=f"{path_prefix}.{listing_index}.channelId",+ message=(+ "Channel listing already exists for this variant. "+ "Use the `update` field to modify an existing "+ "channel listing."+ ),+ code=ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.value,+ channels=[channel_id],+ )+ )+ continue+if channel_id in channels_not_assigned_to_product:code = ProductVariantBulkErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.valueindex_error_map[variant_index].append(diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.pyindex 9c930898a5..39f7c98916 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py@@ -228,6 +228,12 @@ class ProductVariantBulkUpdate(BaseMutation):index_error_map,):if listings_data := cleaned_input["channel_listings"].get("create"):+ variant = cleaned_input["id"]+ existing_channel_ids = {+ graphene.Node.to_global_id("Channel", listing.channel_id)+ for listing in listings_global_id_to_instance_map.values()+ if listing.variant_id == variant.id+ }cleaned_input["channel_listings"]["create"] = (ProductVariantBulkCreate.clean_channel_listings(listings_data,@@ -236,6 +242,7 @@ class ProductVariantBulkUpdate(BaseMutation):variant_index,index_error_map,"channelListings.create",+ existing_channel_ids=existing_channel_ids,))if listings_data := cleaned_input["channel_listings"].get("update"):diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.pyindex b0806c29bf..8ecf0aa4f1 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py@@ -474,6 +474,215 @@ def test_product_variant_bulk_update_create_already_existing_stock(assert errors[0]["warehouses"] == [warehouse_global_id]+def test_product_variant_bulk_update_create_already_existing_channel_listing(+ staff_api_client,+ variant,+ permission_manage_products,+ channel_USD,+):+ # given+ product = variant.product+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ existing_listing = variant.channel_listings.get(channel=channel_USD)+ existing_price = existing_listing.price_amount+ assert variant.channel_listings.count() == 1+ channel_global_id = graphene.Node.to_global_id("Channel", channel_USD.pk)++ new_price = 50.0+ variants = [+ {+ "id": variant_id,+ "channelListings": {+ "create": [+ {+ "price": new_price,+ "channelId": channel_global_id,+ }+ ]+ },+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "channelId"+ assert errors[0]["path"] == "channelListings.create.0.channelId"+ assert errors[0]["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ assert errors[0]["message"] == (+ "Channel listing already exists for this variant. "+ "Use the `update` field to modify an existing channel listing."+ )+ assert errors[0]["channels"] == [channel_global_id]+ assert data["count"] == 0+ assert variant.channel_listings.count() == 1+ existing_listing.refresh_from_db()+ assert existing_listing.price_amount == existing_price+++ "error_policy",+ [+ ErrorPolicyEnum.REJECT_EVERYTHING.name,+ ErrorPolicyEnum.REJECT_FAILED_ROWS.name,+ ErrorPolicyEnum.IGNORE_FAILED.name,+ ],+)+def test_product_variant_bulk_update_create_already_existing_channel_listing_error_policy(+ error_policy,+ staff_api_client,+ variant,+ permission_manage_products,+ channel_USD,+):+ # given+ product = variant.product+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ existing_listing = variant.channel_listings.get(channel=channel_USD)+ existing_price = existing_listing.price_amount+ assert variant.channel_listings.count() == 1+ channel_global_id = graphene.Node.to_global_id("Channel", channel_USD.pk)++ new_name = "Updated variant name"+ new_price = 50.0+ variants = [+ {+ "id": variant_id,+ "name": new_name,+ "channelListings": {+ "create": [+ {+ "price": new_price,+ "channelId": channel_global_id,+ }+ ]+ },+ }+ ]++ variables = {+ "productId": product_id,+ "variants": variants,+ "errorPolicy": error_policy,+ }++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name++ variant.refresh_from_db()+ existing_listing.refresh_from_db()++ # no duplicate channel listing is ever created+ assert variant.channel_listings.count() == 1+ assert existing_listing.price_amount == existing_price++ if error_policy == ErrorPolicyEnum.IGNORE_FAILED.name:+ # the variant is updated, only the offending listing entry is dropped+ assert data["count"] == 1+ assert data["results"][0]["productVariant"]["name"] == new_name+ assert variant.name == new_name+ else:+ # REJECT_EVERYTHING / REJECT_FAILED_ROWS save nothing for the row+ assert data["count"] == 0+ assert not data["results"][0]["productVariant"]+ assert variant.name != new_name+++def test_product_variant_bulk_update_create_duplicate_and_invalid_channel_listing_error_paths(+ staff_api_client,+ variant,+ permission_manage_products,+ channel_USD,+ channel_PLN,+):+ # given+ # The variant is already listed on channel_USD, and its product is NOT+ # assigned to channel_PLN. The `create` list mixes:+ # index 0 -> duplicate listing for channel_USD (caught by the new check)+ # index 1 -> a listing for channel_PLN (product not assigned to that channel)+ # so two different input entries each produce an error, and their reported+ # `path` indices must stay aligned with the input positions.+ product = variant.product+ product_id = graphene.Node.to_global_id("Product", product.pk)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ assert variant.channel_listings.count() == 1+ usd_global_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ pln_global_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)++ variants = [+ {+ "id": variant_id,+ "channelListings": {+ "create": [+ {"price": 50.0, "channelId": usd_global_id}, # index 0: duplicate+ {+ "price": 20.0,+ "channelId": pln_global_id,+ }, # index 1: not assigned+ ]+ },+ }+ ]++ variables = {"productId": product_id, "variants": variants}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkUpdate"]++ # then+ errors = data["results"][0]["errors"]+ assert len(errors) == 2++ errors_by_code = {error["code"]: error for error in errors}++ duplicate_error = errors_by_code[+ ProductVariantBulkErrorCode.DUPLICATED_INPUT_ITEM.name+ ]+ assert duplicate_error["path"] == "channelListings.create.0.channelId"+ assert duplicate_error["channels"] == [usd_global_id]++ not_assigned_error = errors_by_code[+ ProductVariantBulkErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.name+ ]+ # The entry was at input index 1; the reported path must keep that index even+ # though the duplicate at index 0 was dropped before creation.+ assert not_assigned_error["path"] == "channelListings.create.1.channelId"+ assert not_assigned_error["channels"] == [pln_global_id]++ assert data["count"] == 0+ assert variant.channel_listings.count() == 1++def test_product_variant_bulk_update_and_remove_stock(staff_api_client,variant_with_many_stocks,