Skip to content

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

Apply `InstanceTracker` to `ProductVariantUpdate` mutation (#17640)

Piotr Zabieglike27fd5fdab2e
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index 9300ab283f..d4c3e678af 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -9,7 +9,10 @@ from .....product import models
from .....product.error_codes import ProductErrorCode
from .....product.utils.variants import generate_and_set_variant_name
from ....attribute.types import AttributeValueInput
-from ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput
+from ....attribute.utils import (
+ AttributeAssignmentMixin,
+ AttrValuesInput,
+)
from ....channel import ChannelContext
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
index e1fc0d6331..24ce110805 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py
@@ -1,8 +1,11 @@
+from typing import cast
+
import graphene
from django.core.exceptions import ValidationError
from .....attribute import models as attribute_models
from .....core.tracing import traced_atomic_transaction
+from .....core.utils.update_mutation_manager import InstanceTracker
from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
@@ -23,6 +26,7 @@ from ....meta.inputs import MetadataInput
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import ProductVariant
from ...utils import clean_variant_sku, get_used_variants_attribute_values
+from ..utils import PRODUCT_VARIANT_UPDATE_FIELDS
from . import product_variant_cleaner as cleaner
from .product_variant_create import ProductVariantInput
@@ -55,6 +59,8 @@ class ProductVariantUpdate(DeprecatedModelMutation):
support_meta_field = True
support_private_meta_field = True
+ FIELDS_TO_TRACK = list(PRODUCT_VARIANT_UPDATE_FIELDS)
+
@classmethod
def get_instance(cls, info: ResolveInfo, **data) -> models.ProductVariant | None:
"""Prefetch related fields that are needed to process the mutation.
@@ -110,12 +116,12 @@ class ProductVariantUpdate(DeprecatedModelMutation):
cleaner.clean_weight(cleaned_input)
cleaner.clean_quantity_limit(cleaned_input)
- cls.clean_attributes(cleaned_input, instance)
+ attribute_modified = cls.clean_attributes(cleaned_input, instance)
if "sku" in cleaned_input:
cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))
cleaner.clean_preorder_settings(cleaned_input)
- return cleaned_input
+ return cleaned_input, attribute_modified
@classmethod
def clean_attributes(cls, cleaned_input: dict, instance: models.ProductVariant):
@@ -183,29 +189,42 @@ class ProductVariantUpdate(DeprecatedModelMutation):
instance.track_inventory = track_inventory
@classmethod
- def _save_variant_instance(cls, instance, changed_fields):
- update_fields = ["updated_at"] + changed_fields
+ def _save_variant_instance(cls, instance, modified_instance_fields):
+ update_fields = ["updated_at"] + modified_instance_fields
instance.save(update_fields=update_fields)
@classmethod
def _save(
- cls, info: ResolveInfo, instance, cleaned_input, changed_fields
- ) -> tuple[bool, bool, bool]:
- metadata_changed = (
- "metadata" in changed_fields or "private_metadata" in changed_fields
+ cls,
+ instance_tracker: InstanceTracker,
+ cleaned_input,
+ attribute_modified: bool,
+ ) -> tuple[bool, bool]:
+ instance = cast(models.ProductVariant, instance_tracker.instance)
+ modified_instance_fields = instance_tracker.get_modified_fields()
+ metadata_modified = (
+ "metadata" in modified_instance_fields
+ or "private_metadata" in modified_instance_fields
)
refresh_product_search_index = False
with traced_atomic_transaction():
- if changed_fields:
- cls._save_variant_instance(instance, changed_fields)
- if "sku" in changed_fields or "name" in changed_fields:
+ # handle product variant
+ if modified_instance_fields:
+ cls._save_variant_instance(instance, modified_instance_fields)
+ if (
+ "sku" in modified_instance_fields
+ or "name" in modified_instance_fields
+ ):
refresh_product_search_index = True
- if attributes := cleaned_input.get("attributes"):
- AttributeAssignmentMixin.save(instance, attributes)
+ # handle attributes
+ if attribute_modified:
+ attributes_data = cleaned_input.get("attributes")
+ AttributeAssignmentMixin.save(instance, attributes_data)
refresh_product_search_index = True
+ # handle product
if refresh_product_search_index:
instance.product.search_index_dirty = True
product_update_fields = ["updated_at", "search_index_dirty"]
@@ -217,7 +236,7 @@ class ProductVariantUpdate(DeprecatedModelMutation):
if product_update_fields:
instance.product.save(update_fields=product_update_fields)
- return bool(changed_fields), bool(attributes), metadata_changed
+ return bool(modified_instance_fields), metadata_modified
@classmethod
def construct_instance(cls, instance, cleaned_input) -> models.ProductVariant:
@@ -293,28 +312,26 @@ class ProductVariantUpdate(DeprecatedModelMutation):
instance = cls.get_instance(
info, id=id, sku=sku, external_reference=external_reference, input=input
)
- old_instance_data = instance.serialize_for_comparison() # type: ignore[union-attr]
- cleaned_input = cls.clean_input(info, instance, input) # type: ignore[arg-type]
+ instance = cast(models.ProductVariant, instance)
+ instance_tracker = InstanceTracker(instance, cls.FIELDS_TO_TRACK)
- cls.handle_metadata(instance, cleaned_input)
+ cleaned_input, attribute_modified = cls.clean_input(info, instance, input)
- instance = cls.construct_instance(instance, cleaned_input)
+ cls.handle_metadata(instance, cleaned_input)
+ cls.construct_instance(instance, cleaned_input)
cls.clean_instance(info, instance)
- new_instance_data = instance.serialize_for_comparison()
-
- changed_fields = cls.diff_instance_data_fields(
- instance.comparison_fields,
- old_instance_data,
- new_instance_data,
- )
- variant_modified, attributes_modified, metadata_modified = cls._save(
- info, instance, cleaned_input, changed_fields
+ variant_modified, metadata_modified = cls._save(
+ instance_tracker, cleaned_input, attribute_modified
)
cls._save_m2m(info, instance, cleaned_input)
cls._post_save_action(
- info, instance, variant_modified, attributes_modified, metadata_modified
+ info,
+ instance,
+ variant_modified,
+ attribute_modified,
+ metadata_modified,
)
return cls.success_response(instance)
diff --git a/saleor/graphql/product/mutations/utils.py b/saleor/graphql/product/mutations/utils.py
index 45d61a02d8..b818a473ea 100644
--- a/saleor/graphql/product/mutations/utils.py
+++ b/saleor/graphql/product/mutations/utils.py
@@ -2,6 +2,20 @@ from django.db.models import Q
from ....tax.models import TaxClass
+PRODUCT_VARIANT_UPDATE_FIELDS = {
+ "external_reference",
+ "is_preorder",
+ "metadata",
+ "name",
+ "preorder_end_date",
+ "preorder_global_threshold",
+ "private_metadata",
+ "quantity_limit_per_customer",
+ "sku",
+ "track_inventory",
+ "weight",
+}
+
def clean_tax_code(cleaned_input: dict):
"""Clean deprecated `taxCode` field.
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 2bc46bed75..2a870b6f40 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -1,19 +1,21 @@
import datetime
import json
-from unittest.mock import ANY, call, patch
+from unittest.mock import ANY, patch
from uuid import uuid4
import graphene
import pytest
from django.conf import settings
from django.utils.text import slugify
+from measurement.measures import Weight
from .....attribute import AttributeInputType
from .....attribute.models import AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
-from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from .....product.error_codes import ProductErrorCode
+from ....core.utils import snake_to_camel_case
from ....tests.utils import get_graphql_content
+from ...mutations.product_variant.product_variant_create import ProductVariantInput
def test_product_variant_update_with_new_attributes(
@@ -165,223 +167,6 @@ def test_update_product_variant_by_id(
product_variant_created_webhook_mock.assert_not_called()
-QUERY_UPDATE_VARIANT_CHANGING_FIELDS = """
- mutation updateVariant (
- $id: ID!
- $sku: String!
- $quantityLimitPerCustomer: Int!
- $trackInventory: Boolean!
- $externalReference: String
- $metadata: [MetadataInput!]
- $privateMetadata: [MetadataInput!]
- $preorder: PreorderSettingsInput
- $attributes: [AttributeValueInput!]) {
- productVariantUpdate(
- id: $id,
- input: {
- sku: $sku,
- trackInventory: $trackInventory,
- attributes: $attributes,
- externalReference: $externalReference
- quantityLimitPerCustomer: $quantityLimitPerCustomer,
- metadata: $metadata,
- preorder: $preorder,
- privateMetadata: $privateMetadata,
- }) {
- productVariant {
- name
- sku
- quantityLimitPerCustomer
- externalReference
- channelListings {
- channel {
- slug
- }
- }
- metadata {
- key
- value
- }
- privateMetadata {
- key
- value
- }
- }
- errors {
- field
- message
- attributes
- code}
- }
- }
- """
-
-
- ("fields", "changed_fields"),
- [
- ({"sku": 1234}, ["sku"]),
- ({"metadata": [{"key": "test_key1", "value": "test_value2"}]}, ["metadata"]),
- ({"trackInventory": False}, ["track_inventory"]),
- ({"quantityLimitPerCustomer": 5}, ["quantity_limit_per_customer"]),
- (
- {"preorder": {"globalThreshold": 11, "endDate": "2024-12-03T00:00Z"}},
- ["preorder_end_date", "preorder_global_threshold"],
- ),
- (
- {"preorder": {"globalThreshold": 10, "endDate": "2024-12-03T00:00Z"}},
- ["preorder_end_date"],
- ),
- (
- {"preorder": {"globalThreshold": 11, "endDate": "2024-12-02T00:00Z"}},
- ["preorder_global_threshold"],
- ),
- ({"externalReference": "test-ext-ref2"}, ["external_reference"]),
- (
- {"sku": 1234, "trackInventory": False, "externalReference": "test-ext-ref"},
- ["sku", "track_inventory"],
- ),
- ],
-)
-@patch(
- "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate.call_event"
-)
-@patch(
- "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate._save_variant_instance"
-)
-def test_update_product_variant_update_fields_when_necessary(
- save_variant_mock,
- call_event_mock,
- staff_api_client,
- product,
- permission_manage_products,
- fields,
- changed_fields,
-):
- # given
- variant = product.variants.first()
- quantity_limit = 9
- external_reference = "test-ext-ref"
- variant_name = variant.attributes.first().values.first().name
- variant_sku = "123"
- product.default_variant = variant
- product.save(update_fields=["default_variant"])
- variant.name = variant_name
- variant.metadata = {"test_key1": "test_value1"}
- variant.private_metadata = {"private_key1": "private_value_1"}
- variant.external_reference = external_reference
- variant.quantity_limit_per_customer = quantity_limit
- variant.track_inventory = True
- variant.is_preorder = True
- variant.preorder_global_threshold = 10
- variant.preorder_end_date = "2024-12-02T00:00Z"
- variant.save()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
-
- variables = {
- "id": variant_id,
- "sku": variant_sku,
- "trackInventory": True,
- "quantityLimitPerCustomer": quantity_limit,
- "externalReference": external_reference,
- "metadata": [{"key": "test_key1", "value": "test_value1"}],
- "privateMetadata": [{"key": "private_key1", "value": "private_value_1"}],
- }
-
- for field, value in fields.items():
- variables[field] = value
-
- # when
- response = staff_api_client.post_graphql(
- QUERY_UPDATE_VARIANT_CHANGING_FIELDS,
- variables,
- permissions=[permission_manage_products],
- )
-
- # then
- variant.refresh_from_db()
- get_graphql_content(response)
- save_variant_mock.assert_called_once_with(variant, changed_fields)
- call_event_mock.assert_has_calls(
- [
- call(ANY, variant),
- call(mark_active_catalogue_promotion_rules_as_dirty, ANY),
- ]
- )
-
-
- "field_values",
- [
- ["sku", 123],
- ["metadata", [{"key": "test_key1", "value": "test_value1"}]],
- ["trackInventory", True],
- ["quantityLimitPerCustomer", 9],
- ["preorder", {"globalThreshold": 10, "endDate": "2024-12-02T00:00Z"}],
- ["externalReference", "test-ext-ref"],
- ],
-)
-@patch(
- "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate.call_event"
-)
-@patch(
- "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate._save_variant_instance"
-)
-def test_update_product_variant_skip_updating_fields_when_unchanged(
- save_variant_mock,
- call_event_mock,
- staff_api_client,
- product,
- permission_manage_products,
- field_values,
-):
- # given
- variant = product.variants.first()
- quantity_limit = 9
- external_reference = "test-ext-ref"
- variant_name = variant.attributes.first().values.first().name
- variant_sku = "123"
- product.default_variant = variant
- product.save(update_fields=["default_variant"])
- variant.name = variant_name
- variant.is_preorder = True
- variant.preorder_global_threshold = 10
- variant.preorder_end_date = "2024-12-02T00:00Z"
- variant.metadata = {"test_key1": "test_value1"}
- variant.private_metadata = {"private_key1": "private_value_1"}
- variant.external_reference = external_reference
- variant.quantity_limit_per_customer = quantity_limit
- variant.track_inventory = True
- variant.save()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
-
- variables = {
- "id": variant_id,
- "sku": variant_sku,
- "trackInventory": True,
- "quantityLimitPerCustomer": quantity_limit,
- "externalReference": external_reference,
- "metadata": [{"key": "test_key1", "value": "test_value1"}],
- "privateMetadata": [{"key": "private_key1", "value": "private_value_1"}],
- }
-
- field, value = field_values
- variables[field] = value
-
- # when
- response = staff_api_client.post_graphql(
- QUERY_UPDATE_VARIANT_CHANGING_FIELDS,
- variables,
- permissions=[permission_manage_products],
- )
-
- # then
- variant.refresh_from_db()
- get_graphql_content(response)
- save_variant_mock.assert_not_called()
- call_event_mock.assert_not_called()
-
-
def test_update_product_variant_marks_prices_as_dirty(
staff_api_client,
product,
@@ -2812,3 +2597,186 @@ def test_update_product_variant_with_existing_metadata_and_event_when_write_diff
# no empty event emitted
product_variant_updated_webhook_mock.assert_called_once()
product_variant_metadata_updated_webhook_mock.assert_called_once()
+
+
+PRODUCT_VARIANT_UPDATE_MUTATION = """
+mutation ProductVariantUpdate($id: ID!, $input: ProductVariantInput!) {
+ productVariantUpdate(id: $id, input: $input) {
+ errors {
+ field
+ code
+ message
+ }
+ productVariant {
+ id
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate.call_event"
+)
+@patch(
+ "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate._save_variant_instance"
+)
+def test_update_product_variant_nothing_changed(
+ save_variant_mock,
+ call_event_mock,
+ staff_api_client,
+ product_with_variant_with_two_attributes,
+ permission_manage_products,
+ color_attribute,
+ size_attribute,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product = product_with_variant_with_two_attributes
+ variant = product.variants.first()
+
+ variant.name = "some_name"
+ variant.sku = "some_sku"
+ variant.external_reference = "some-ext-ref"
+ key = "some_key"
+ value = "some_value"
+ variant.metadata = {key: value}
+ variant.private_metadata = {key: value}
+ variant.is_preorder = True
+ variant.preorder_global_threshold = 10
+ variant.preorder_end_date = "2024-12-02T00:00Z"
+ variant.track_inventory = True
+ variant.weight = Weight(kg=10)
+ variant.quantity_limit_per_customer = 10
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+
+ attribute_slug_1 = variant.attributes.first().values.first().slug
+ attribute_slug_2 = variant.attributes.last().values.first().slug
+
+ input_fields = [
+ snake_to_camel_case(key) for key in ProductVariantInput._meta.fields.keys()
+ ]
+
+ input = {
+ "attributes": [
+ {"id": color_attribute_id, "values": [attribute_slug_1]},
+ {"id": size_attribute_id, "values": [attribute_slug_2]},
+ ],
+ "sku": variant.sku,
+ "name": variant.name,
+ "trackInventory": variant.track_inventory,
+ "weight": 10,
+ "preorder": {
+ "globalThreshold": variant.preorder_global_threshold,
+ "endDate": variant.preorder_end_date,
+ },
+ "quantityLimitPerCustomer": variant.quantity_limit_per_customer,
+ "metadata": [{"key": key, "value": value}],
+ "privateMetadata": [{"key": key, "value": value}],
+ "externalReference": variant.external_reference,
+ }
+ assert set(input_fields) == set(input.keys())
+
+ variables = {"id": variant_id, "input": input}
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_UPDATE_MUTATION,
+ variables,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["productVariantUpdate"]["errors"]
+ variant.refresh_from_db()
+ call_event_mock.assert_not_called()
+ save_variant_mock.assert_not_called()
+
+
+@patch(
+ "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate.call_event"
+)
+@patch(
+ "saleor.graphql.product.mutations.product_variant.ProductVariantUpdate._save_variant_instance"
+)
+def test_update_product_variant_emit_event(
+ save_variant_mock,
+ call_event_mock,
+ staff_api_client,
+ product_with_variant_with_two_attributes,
+ permission_manage_products,
+ color_attribute,
+ size_attribute,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product = product_with_variant_with_two_attributes
+ variant = product.variants.first()
+
+ variant.name = "some_name"
+ variant.sku = "some_sku"
+ variant.external_reference = "some-ext-ref"
+ key = "some_key"
+ value = "some_value"
+ variant.metadata = {key: value}
+ variant.private_metadata = {key: value}
+ variant.is_preorder = True
+ variant.preorder_global_threshold = 10
+ variant.preorder_end_date = "2024-12-02T00:00Z"
+ variant.track_inventory = True
+ variant.weight = Weight(kg=10)
+ variant.quantity_limit_per_customer = 10
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+
+ input_fields = [
+ snake_to_camel_case(key) for key in ProductVariantInput._meta.fields.keys()
+ ]
+
+ input = {
+ "attributes": [
+ {"id": color_attribute_id, "values": ["new_color"]},
+ {"id": size_attribute_id, "values": ["new_size"]},
+ ],
+ "sku": variant.sku + "_new",
+ "name": variant.name + "_new",
+ "trackInventory": not variant.track_inventory,
+ "weight": 11,
+ "preorder": {
+ "globalThreshold": variant.preorder_global_threshold + 1,
+ "endDate": "2024-12-03T00:00Z",
+ },
+ "quantityLimitPerCustomer": variant.quantity_limit_per_customer + 1,
+ "metadata": [{"key": key + "_new", "value": value + "_new"}],
+ "privateMetadata": [{"key": key + "_new", "value": value + "_new"}],
+ "externalReference": variant.external_reference + "_new",
+ }
+ assert set(input_fields) == set(input.keys())
+
+ # fields making changes to related models (other than variant)
+ non_variant_instance_fields = ["attributes"]
+
+ for key, value in input.items():
+ variables = {"id": variant_id, "input": {key: value}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_UPDATE_MUTATION,
+ variables,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["productVariantUpdate"]["errors"]
+ call_event_mock.assert_called()
+ call_event_mock.reset_mock()
+ if key not in non_variant_instance_fields:
+ save_variant_mock.assert_called()
+ save_variant_mock.reset_mock()
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 99b21146f6..f50d73feb1 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -1,4 +1,3 @@
-import copy
import datetime
from collections.abc import Iterable
from decimal import Decimal
@@ -12,7 +11,6 @@ from django.contrib.postgres.search import SearchVectorField
from django.core.validators import MinValueValidator
from django.db import models, transaction
from django.db.models import JSONField, TextField
-from django.forms.models import model_to_dict
from django.urls import reverse
from django.utils import timezone
from django_measurement.models import MeasurementField
@@ -459,25 +457,6 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferenc
self.preorder_end_date is None or timezone.now() <= self.preorder_end_date
)
- @property
- def comparison_fields(self):
- return [
- "sku",
- "name",
- "track_inventory",
- "is_preorder",
- "quantity_limit_per_customer",
- "weight",
- "external_reference",
- "metadata",
- "private_metadata",
- "preorder_end_date",
- "preorder_global_threshold",
- ]
-
- def serialize_for_comparison(self):
- return copy.deepcopy(model_to_dict(self, fields=self.comparison_fields))
-
class ProductVariantTranslation(Translation):
product_variant = models.ForeignKey(