Skip to content

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

Extend product payload

Damian W5d9413b116d9
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 903090cbf6..bfbfa2d65d 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -147,7 +147,7 @@ class WebhookPlugin(BasePlugin):
) -> Any:
if not self.active:
return previous_value
- product_variant_data = generate_product_variant_payload(product_variant)
+ product_variant_data = generate_product_variant_payload([product_variant])
trigger_webhooks_for_event.delay(
WebhookEventType.PRODUCT_VARIANT_CREATED, product_variant_data
)
@@ -157,7 +157,7 @@ class WebhookPlugin(BasePlugin):
) -> Any:
if not self.active:
return previous_value
- product_variant_data = generate_product_variant_payload(product_variant)
+ product_variant_data = generate_product_variant_payload([product_variant])
trigger_webhooks_for_event.delay(
WebhookEventType.PRODUCT_VARIANT_UPDATED, product_variant_data
)
@@ -167,7 +167,7 @@ class WebhookPlugin(BasePlugin):
) -> Any:
if not self.active:
return previous_value
- product_variant_data = generate_product_variant_payload(product_variant)
+ product_variant_data = generate_product_variant_payload([product_variant])
trigger_webhooks_for_event.delay(
WebhookEventType.PRODUCT_VARIANT_DELETED, product_variant_data
)
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index ab4169b31b..f7cb359112 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -208,7 +208,7 @@ def test_product_variant_created(mocked_webhook_trigger, settings, variant):
manager = get_plugins_manager()
manager.product_variant_created(variant)
- expected_data = generate_product_variant_payload(variant)
+ expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.PRODUCT_VARIANT_CREATED, expected_data
)
@@ -220,7 +220,7 @@ def test_product_variant_updated(mocked_webhook_trigger, settings, variant):
manager = get_plugins_manager()
manager.product_variant_updated(variant)
- expected_data = generate_product_variant_payload(variant)
+ expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.PRODUCT_VARIANT_UPDATED, expected_data
)
@@ -232,7 +232,7 @@ def test_product_variant_deleted(mocked_webhook_trigger, settings, variant):
manager = get_plugins_manager()
manager.product_variant_deleted(variant)
- expected_data = generate_product_variant_payload(variant)
+ expected_data = generate_product_variant_payload([variant])
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.PRODUCT_VARIANT_DELETED, expected_data
)
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 3198994dcf..eb5b06f4a0 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -305,20 +305,18 @@ class ProductsQueryset(models.QuerySet):
)
def prefetched_for_webhook(self, single_object=True):
- if single_object:
- return self.prefetch_related(
- "attributes__values",
- "attributes__assignment__attribute",
- "media",
- )
- return self.prefetch_related(
+ common_fields = (
"attributes__values",
"attributes__assignment__attribute",
- "collections",
- "variants__stocks__allocations",
"media",
- "category",
+ "variants__attributes__values",
+ "variants__attributes__assignment__attribute",
+ "variants__variant_media__media",
+ "variants__stocks__allocations",
)
+ if single_object:
+ return self.prefetch_related(*common_fields)
+ return self.prefetch_related("collections", "category", *common_fields)
class Product(SeoModel, ModelWithMetadata):
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index a183787b33..1776e96851 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -243,30 +243,32 @@ PRODUCT_FIELDS = (
)
+def serialize_product_channel_listing_payload(channel_listings):
+ serializer = PayloadSerializer()
+ fields = (
+ "publication_date",
+ "id_published",
+ "visible_in_listings",
+ "available_for_purchase",
+ )
+ channel_listing_payload = serializer.serialize(
+ channel_listings,
+ fields=fields,
+ extra_dict_data={"channel_slug": lambda pch: pch.channel.slug},
+ )
+ return channel_listing_payload
+
+
def generate_product_payload(product: "Product"):
serializer = PayloadSerializer(
extra_model_fields={"ProductVariant": ("quantity", "quantity_allocated")}
)
- product_variant_fields = (
- "sku",
- "name",
- "currency",
- "price_amount",
- "track_inventory",
- "cost_price_amount",
- "private_metadata",
- "metadata",
- )
product_payload = serializer.serialize(
[product],
fields=PRODUCT_FIELDS,
additional_fields={
"category": (lambda p: p.category, ("name", "slug")),
"collections": (lambda p: p.collections.all(), ("name", "slug")),
- "variants": (
- lambda p: p.variants.annotate_quantities().all(),
- product_variant_fields,
- ),
},
extra_dict_data={
"attributes": serialize_product_or_variant_attributes(product),
@@ -281,6 +283,12 @@ def generate_product_payload(product: "Product"):
}
for media_obj in product.media.all()
],
+ "channel_listings": json.loads(
+ serialize_product_channel_listing_payload(
+ product.channel_listings.all()
+ )
+ ),
+ "variants": lambda x: json.loads((generate_product_variant_payload(x))),
},
)
return product_payload
@@ -301,43 +309,55 @@ def generate_product_deleted_payload(product: "Product", variants_id):
PRODUCT_VARIANT_FIELDS = (
- "name",
"sku",
+ "name",
+ "track_inventory",
"private_metadata",
"metadata",
)
-def generate_product_variant_payload(product_variant: "ProductVariant"):
+def generate_product_variant_listings_payload(variant_channel_listings):
+ serializer = PayloadSerializer()
+ fields = (
+ "currency",
+ "price_amount",
+ "cost_price_amount",
+ )
+ channel_listing_payload = serializer.serialize(
+ variant_channel_listings,
+ fields=fields,
+ extra_dict_data={"channel_slug": lambda vch: vch.channel.slug},
+ )
+ return channel_listing_payload
+
+
+def generate_product_variant_media_payload(product_variant):
+ return [
+ {
+ "alt": media_obj.media.alt,
+ "url": (
+ build_absolute_uri(media_obj.media.image.url)
+ if media_obj.media.type == ProductMediaTypes.IMAGE
+ else media_obj.media.external_url
+ ),
+ }
+ for media_obj in product_variant.variant_media.all()
+ ]
+
+
+def generate_product_variant_payload(product_variants: Iterable["ProductVariant"]):
serializer = PayloadSerializer()
- product_id = graphene.Node.to_global_id("Product", product_variant.product.id)
payload = serializer.serialize(
- [product_variant],
+ product_variants,
fields=PRODUCT_VARIANT_FIELDS,
- additional_fields={
- "channel_listings": (
- lambda p: p.channel_listings.all(),
- (
- "currency",
- "price_amount",
- "cost_price_amount",
- ),
- ),
- },
extra_dict_data={
- "attributes": serialize_product_or_variant_attributes(product_variant),
- "product_id": product_id,
- "media": [
- {
- "alt": media_obj.media.alt,
- "url": (
- build_absolute_uri(media_obj.media.image.url)
- if media_obj.media.type == ProductMediaTypes.IMAGE
- else media_obj.media.external_url
- ),
- }
- for media_obj in product_variant.variant_media.all()
- ],
+ "attributes": lambda v: serialize_product_or_variant_attributes(v),
+ "product_id": lambda v: graphene.Node.to_global_id("Product", v.product_id),
+ "media": lambda v: generate_product_variant_media_payload(v),
+ "channel_listings": lambda v: json.loads(
+ generate_product_variant_listings_payload(v.channel_listings.all())
+ ),
},
)
return payload
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index b6e40c16e9..64743e2da2 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -1,5 +1,8 @@
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+import graphene
+
+from ..attribute import AttributeInputType
from ..checkout.fetch import fetch_checkout_lines
from ..product.models import Product
@@ -36,17 +39,35 @@ def serialize_product_or_variant_attributes(
product_or_variant: Union["Product", "ProductVariant"]
) -> List[Dict]:
data = []
+
+ def _prepare_reference(attribute, attr_slug):
+ if attribute.input_type != AttributeInputType.REFERENCE:
+ return
+
+ reference_pk = attr_slug.split("_")[1]
+ reference_id = graphene.Node.to_global_id(attribute.entity_type, reference_pk)
+ return reference_id
+
for attr in product_or_variant.attributes.all():
- attr_data = {
- "name": attr.assignment.attribute.name,
- "id": attr.assignment.attribute.id,
+ attr_id = graphene.Node.to_global_id("Attribute", attr.assignment.attribute_id)
+ attribute = attr.assignment.attribute
+ attr_data: Dict[Any, Any] = {
+ "name": attribute.name,
+ "input_type": attribute.input_type,
+ "slug": attribute.slug,
+ "entity_type": attribute.entity_type,
+ "id": attr_id,
"values": [],
}
for attr_value in attr.values.all():
+ attr_slug = attr_value.slug
value: Dict[str, Optional[Union[str, Dict[str, Any]]]] = {
"name": attr_value.name,
- "slug": attr_value.slug,
+ "slug": attr_slug,
+ "value": attr_value.value,
+ "rich_text": attr_value.rich_text,
+ "reference": _prepare_reference(attribute, attr_slug),
"file": None,
}
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index a4ac2c6a2c..10c950c2d7 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -93,10 +93,10 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
def test_generate_product_variant_payload(
- product_with_variant_with_two_attributes, product_with_images
+ product_with_variant_with_two_attributes, product_with_images, channel_USD
):
variant = product_with_variant_with_two_attributes.variants.first()
- payload = json.loads(generate_product_variant_payload(variant))[0]
+ payload = json.loads(generate_product_variant_payload([variant]))[0]
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
additional_fields = ["channel_listings"]
extra_dict_data = ["attributes", "product_id", "media"]
@@ -117,6 +117,7 @@ def test_generate_product_variant_payload(
"cost_price_amount": "1.000",
"currency": "USD",
"id": ANY,
+ "channel_slug": channel_USD.slug,
"price_amount": "10.000",
"type": "ProductVariantChannelListing",
}
@@ -124,10 +125,10 @@ def test_generate_product_variant_payload(
def test_generate_product_variant_with_external_media_payload(
- product_with_variant_with_external_media,
+ product_with_variant_with_external_media, channel_USD
):
variant = product_with_variant_with_external_media.variants.first()
- payload = json.loads(generate_product_variant_payload(variant))[0]
+ payload = json.loads(generate_product_variant_payload([variant]))[0]
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
additional_fields = ["channel_listings"]
extra_dict_data = ["attributes", "product_id", "media"]
@@ -136,7 +137,6 @@ def test_generate_product_variant_with_external_media_payload(
["id", "type"], PRODUCT_VARIANT_FIELDS, extra_dict_data, additional_fields
)
)
-
for field in payload_fields:
assert payload.get(field) is not None
@@ -152,6 +152,7 @@ def test_generate_product_variant_with_external_media_payload(
"currency": "USD",
"id": ANY,
"price_amount": "10.000",
+ "channel_slug": channel_USD.slug,
"type": "ProductVariantChannelListing",
}
assert len(payload.keys()) == len(payload_fields)
@@ -166,7 +167,7 @@ def test_generate_product_variant_deleted_payload(
"variant_media",
).first()
ProductVariant.objects.filter(id=variant.id).delete()
- payload = json.loads(generate_product_variant_payload(variant))[0]
+ payload = json.loads(generate_product_variant_payload([variant]))[0]
[_, payload_variant_id] = graphene.Node.from_global_id(payload["id"])
additional_fields = ["channel_listings"]
extra_dict_data = ["attributes", "product_id", "media"]
diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index 9bed266c80..fe74ec5ef0 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -13,17 +13,42 @@ def test_serialize_product_attributes(
product_data = serialize_product_or_variant_attributes(
product_with_multiple_values_attributes
)
-
assert len(variant_data) == 2
assert variant_data[1] == {
+ "entity_type": None,
"id": ANY,
+ "input_type": "dropdown",
"name": "Size",
- "values": [{"name": "Small", "slug": "small", "file": None}],
+ "slug": "size",
+ "values": [
+ {
+ "file": None,
+ "name": "Small",
+ "reference": None,
+ "rich_text": None,
+ "slug": "small",
+ "value": "",
+ }
+ ],
}
assert len(product_data) == 1
assert product_data[0]["name"] == "Available Modes"
assert sorted(product_data[0]["values"], key=itemgetter("name")) == [
- {"name": "Eco Mode", "slug": "eco", "file": None},
- {"name": "Performance Mode", "slug": "power", "file": None},
+ {
+ "name": "Eco Mode",
+ "slug": "eco",
+ "file": None,
+ "reference": None,
+ "rich_text": None,
+ "value": "",
+ },
+ {
+ "name": "Performance Mode",
+ "slug": "power",
+ "file": None,
+ "reference": None,
+ "rich_text": None,
+ "value": "",
+ },
]