Skip to content

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

Fix csv exporter for products (#17321)

Maciej Korycinski7227135c55a3
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index 1c9b917c83..b567c3b894 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -1,10 +1,9 @@
import datetime
from unittest.mock import patch
-from .....attribute.models import (
- Attribute,
- AttributeValue,
-)
+from django.utils import timezone
+
+from .....attribute.models import Attribute, AttributeValue
from .....attribute.tests.model_helpers import get_product_attributes
from .....attribute.utils import associate_attribute_values_to_instance
from .....product.models import Product, ProductMedia, ProductVariant, VariantMedia
@@ -277,16 +276,20 @@ def test_prepare_products_relations_data_only_attributes_ids(
def test_prepare_products_relations_data_only_channel_ids(
- product_with_image, collection_list, channel_PLN, channel_USD
+ collection_list, channel_PLN, channel_USD, product_available_in_many_channels
):
# given
- pk = product_with_image.pk
- collection_list[0].products.add(product_with_image)
- collection_list[1].products.add(product_with_image)
+ pk = product_available_in_many_channels.pk
+
+ collection_list[0].products.add(product_available_in_many_channels)
+ collection_list[1].products.add(product_available_in_many_channels)
qs = Product.objects.all()
fields = {"name"}
attribute_ids = []
channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
+ product_available_in_many_channels.channel_listings.update(
+ published_at=timezone.now()
+ )
# when
result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
@@ -295,12 +298,59 @@ def test_prepare_products_relations_data_only_channel_ids(
expected_result = {pk: {}}
expected_result = add_channel_to_expected_product_data(
- expected_result, product_with_image, channel_ids, pk
+ expected_result, product_available_in_many_channels, channel_ids, pk
)
assert result == expected_result
+def test_prepare_products_relations_data_sets_published_dates(
+ collection_list, channel_PLN, channel_USD, product_available_in_many_channels
+):
+ # givenq
+ collection_list[0].products.add(product_available_in_many_channels)
+ collection_list[1].products.add(product_available_in_many_channels)
+ qs = Product.objects.all()
+ fields = {"name"}
+ attribute_ids = []
+ channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
+ product_available_in_many_channels.channel_listings.update(
+ published_at=timezone.now()
+ )
+ usd_listing = product_available_in_many_channels.channel_listings.get(
+ channel=channel_USD
+ )
+ pln_listing = product_available_in_many_channels.channel_listings.get(
+ channel=channel_PLN
+ )
+
+ # when
+ result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
+
+ # then
+ single_result = result[product_available_in_many_channels.pk]
+
+ assert usd_listing.published_at
+ assert pln_listing.published_at
+ assert (
+ single_result.get(f"{channel_USD.slug} (channel published at)")
+ == usd_listing.published_at
+ )
+ assert (
+ single_result.get(f"{channel_USD.slug} (channel publication date)")
+ == usd_listing.published_at
+ )
+
+ assert (
+ single_result.get(f"{channel_PLN.slug} (channel published at)")
+ == pln_listing.published_at
+ )
+ assert (
+ single_result.get(f"{channel_PLN.slug} (channel publication date)")
+ == pln_listing.published_at
+ )
+
+
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
def test_get_variants_relations_data(prepare_variants_data_mocked, product_list):
# given
@@ -1454,10 +1504,9 @@ def test_add_channel_info_to_data(product):
"published": True,
}
input_data = {pk: {}}
- fields = ["currency_code", "published"]
# when
- result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+ result = add_channel_info_to_data(product.pk, channel_data, input_data)
# then
assert len(result[pk]) == 2
@@ -1482,10 +1531,9 @@ def test_add_channel_info_to_data_not_changed(product):
f"{slug} (channel published)": True,
}
}
- fields = ["currency_code", "published"]
# when
- result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+ result = add_channel_info_to_data(product.pk, channel_data, input_data)
# then
assert result == input_data
@@ -1500,10 +1548,9 @@ def test_add_channel_info_to_data_no_slug(product):
"published": None,
}
input_data = {pk: {}}
- fields = ["currency_code"]
# when
- result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+ result = add_channel_info_to_data(product.pk, channel_data, input_data)
# then
assert result == input_data
diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.py
index e475103078..03f451cb34 100644
--- a/saleor/csv/tests/export/test_export.py
+++ b/saleor/csv/tests/export/test_export.py
@@ -57,6 +57,7 @@ def test_export_products(
ProductFieldEnum.NAME.value,
ProductFieldEnum.VARIANT_ID.value,
ProductFieldEnum.VARIANT_SKU.value,
+ ProductFieldEnum.CHARGE_TAXES.value,
],
"warehouses": [],
"attributes": [],
@@ -73,17 +74,20 @@ def test_export_products(
# then
create_file_with_headers_mock.assert_called_once_with(
- ["id", "name", "variant id", "variant sku"], ",", file_type
+ ["id", "name", "variant id", "variant sku", "charge taxes"], ",", file_type
)
assert export_products_in_batches_mock.call_count == 1
args, kwargs = export_products_in_batches_mock.call_args
assert set(args[0].values_list("pk", flat=True)) == set(
Product.objects.all().values_list("pk", flat=True)
)
+ # charge taxes are deprecated, and do not return any value. In case of requesting
+ # them, the headers number needs to match to the size of the row
+ expected_charge_taxes = ""
assert args[1:] == (
export_info,
- {"id", "name", "variants__id", "variants__sku"},
- ["id", "name", "variants__id", "variants__sku"],
+ {"id", "name", "variants__id", "variants__sku", expected_charge_taxes},
+ ["id", "name", "variants__id", "variants__sku", expected_charge_taxes],
",",
mock_file,
file_type,
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index 4dfa9c6440..fab0e991ae 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -8,6 +8,8 @@ class ProductExportFields:
"description": "description_as_str",
"category": "category__slug",
"product type": "product_type__name",
+ # charge taxes are deprecated, and do not return any value. In case of
+ # requesting them, the headers number needs to match to the size of the row
"charge taxes": "", # deprecated; remove in Saleor 4.0
"product weight": "product_weight",
"variant id": "variants__id",
@@ -43,14 +45,14 @@ class ProductExportFields:
}
PRODUCT_CHANNEL_LISTING_FIELDS = {
- "channel_pk": "channel_listings__channel__pk",
- "slug": "channel_listings__channel__slug",
- "product_currency_code": "channel_listings__currency",
- "published": "channel_listings__is_published",
- "publication_date": "channel_listings__published_at",
- "published_at": "channel_listings__published_at",
- "searchable": "channel_listings__visible_in_listings",
- "available for purchase": "channel_listings__available_for_purchase_at",
+ "channel_pk": "channel_id",
+ "slug": "channel__slug",
+ "product_currency_code": "currency",
+ "published": "is_published",
+ "publication_date": "published_at",
+ "published_at": "published_at",
+ "searchable": "visible_in_listings",
+ "available for purchase": "available_for_purchase_at",
}
WAREHOUSE_FIELDS = {
@@ -60,30 +62,28 @@ class ProductExportFields:
}
VARIANT_ATTRIBUTE_FIELDS = {
- "value_slug": "variants__attributes__values__slug",
- "value_name": "variants__attributes__values__name",
- "file_url": "variants__attributes__values__file_url",
- "rich_text": "variants__attributes__values__rich_text",
- "value": "variants__attributes__values__value",
- "boolean": "variants__attributes__values__boolean",
- "date_time": "variants__attributes__values__date_time",
- "slug": "variants__attributes__assignment__attribute__slug",
- "input_type": "variants__attributes__assignment__attribute__input_type",
- "entity_type": "variants__attributes__assignment__attribute__entity_type",
- "unit": "variants__attributes__assignment__attribute__unit",
- "attribute_pk": "variants__attributes__assignment__attribute__pk",
- "reference_page": "variants__attributes__values__reference_page",
- "reference_product": "variants__attributes__values__reference_product",
- "reference_variant": "variants__attributes__values__reference_variant",
+ "value_slug": "values__slug",
+ "value_name": "values__name",
+ "file_url": "values__file_url",
+ "rich_text": "values__rich_text",
+ "value": "values__value",
+ "boolean": "values__boolean",
+ "date_time": "values__date_time",
+ "slug": "assignment__attribute__slug",
+ "input_type": "assignment__attribute__input_type",
+ "entity_type": "assignment__attribute__entity_type",
+ "unit": "assignment__attribute__unit",
+ "attribute_pk": "assignment__attribute__pk",
+ "reference_page": "values__reference_page",
+ "reference_product": "values__reference_product",
+ "reference_variant": "values__reference_variant",
}
VARIANT_CHANNEL_LISTING_FIELDS = {
- "channel_pk": "variants__channel_listings__channel__pk",
- "slug": "variants__channel_listings__channel__slug",
- "price_amount": "variants__channel_listings__price_amount",
- "variant_currency_code": "variants__channel_listings__currency",
- "variant_cost_price": "variants__channel_listings__cost_price_amount",
- "variant_preorder_quantity_threshold": (
- "variants__channel_listings__preorder_quantity_threshold"
- ),
+ "channel_pk": "channel__pk",
+ "slug": "channel__slug",
+ "price_amount": "price_amount",
+ "variant_currency_code": "currency",
+ "variant_cost_price": "cost_price_amount",
+ "variant_preorder_quantity_threshold": "preorder_quantity_threshold",
}
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index 8ba802d6de..da72944683 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
from ..models import ExportFile
-BATCH_SIZE = 10000
+BATCH_SIZE = 1000
def export_products(
@@ -214,7 +214,6 @@ def export_products_in_batches(
"category",
)
)
-
export_data = get_products_data(
product_batch, export_fields, attributes, warehouses, channels
)
diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.py
index b97e380406..bfe1177fc8 100644
--- a/saleor/csv/utils/product_headers.py
+++ b/saleor/csv/utils/product_headers.py
@@ -52,8 +52,7 @@ def get_product_export_fields_and_headers(
for field in fields:
lookup_field = fields_mapping[field]
- if lookup_field:
- export_fields.append(lookup_field)
+ export_fields.append(lookup_field)
file_headers.append(field)
return export_fields, file_headers
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 6c3beac800..0c5374313c 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -5,13 +5,19 @@ from urllib.parse import urljoin
import graphene
from django.conf import settings
-from django.db.models import Case, CharField, When
+from django.db.models import Case, CharField, Exists, OuterRef, When
from django.db.models import Value as V
from django.db.models.functions import Cast, Concat
from ...attribute import AttributeInputType
+from ...attribute.models import AssignedVariantAttribute, Attribute, AttributeValue
from ...core.utils import build_absolute_uri
from ...core.utils.editorjs import clean_editor_js
+from ...product.models import (
+ ProductChannelListing,
+ ProductVariant,
+ ProductVariantChannelListing,
+)
from . import ProductExportFields
if TYPE_CHECKING:
@@ -27,16 +33,19 @@ def get_products_data(
) -> list[dict[str, str | bool]]:
"""Create data list of products and their variants with fields values.
- It return list with product and variant data which can be used as import to
+ It returns list with product and variant data which can be used as import to
csv writer and list of attribute and warehouse headers.
"""
products_with_variants_data = []
export_variant_id = "variants__id" in export_fields
- product_fields = set(
- ProductExportFields.HEADERS_TO_FIELDS_MAPPING["fields"].values()
- )
+ # skip generation of the field without a lookup
+ product_fields = {
+ p_field
+ for p_field in ProductExportFields.HEADERS_TO_FIELDS_MAPPING["fields"].values()
+ if p_field
+ }
product_export_fields = export_fields & product_fields
if not export_variant_id:
product_export_fields.add("variants__id")
@@ -106,7 +115,7 @@ def get_products_relations_data(
If any many to many fields are in export_fields or some attribute_ids exists then
dict with product relations fields is returned.
- Otherwise it returns empty dict.
+ Otherwise, it returns empty dict.
"""
many_to_many_fields = set(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()
@@ -128,22 +137,14 @@ def prepare_products_relations_data(
) -> dict[int, dict[str, str]]:
"""Prepare data about products relation fields for given queryset.
- It return dict where key is a product pk, value is a dict with relation fields data.
+ It returns dict where key is a product pk, value is a dict with relation fields data.
"""
- attribute_fields = ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS
- channel_fields = ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS.copy()
result_data: dict[int, dict] = defaultdict(dict)
fields.add("pk")
- if attribute_ids:
- fields.update(attribute_fields.values())
- if channel_ids:
- fields.update(channel_fields.values())
relations_data = queryset.values(*fields)
- channel_pk_lookup = channel_fields.pop("channel_pk")
- channel_slug_lookup = channel_fields.pop("slug")
for data in relations_data.iterator():
pk = data.get("pk")
collection = data.get("collections__slug")
@@ -152,18 +153,47 @@ def prepare_products_relations_data(
result_data = add_image_uris_to_data(pk, image, "media__image", result_data)
result_data = add_collection_info_to_data(pk, collection, result_data)
- result_data, data = handle_attribute_data(
- pk, data, attribute_ids, result_data, attribute_fields, "product attribute"
+ if channel_ids:
+ channel_fields = ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS
+ fields_for_channel = {"product_id"}
+ fields_for_channel.update(channel_fields.values())
+ listings = ProductChannelListing.objects.filter(
+ Exists(queryset.filter(id=OuterRef("product_id"))),
+ channel_id__in=channel_ids,
+ ).values(*fields_for_channel)
+
+ for listing in listings:
+ pk = listing.get("product_id")
+ result_data, _ = handle_channel_data(
+ pk,
+ listing,
+ result_data,
+ ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS,
+ )
+
+ if attribute_ids:
+ attribute_fields = ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS
+
+ fields_for_attrs = {"pk"}
+ attributes = Attribute.objects.filter(id__in=attribute_ids)
+ attr_values = AttributeValue.objects.filter(
+ Exists(attributes.filter(id=OuterRef("attribute_id"))),
)
- result_data, data = handle_channel_data(
- pk,
- data,
- channel_ids,
- result_data,
- channel_pk_lookup,
- channel_slug_lookup,
- channel_fields,
+ relations_data = queryset.filter(
+ Exists(attr_values.filter(id=OuterRef("attributevalues__value_id")))
)
+ fields_for_attrs.update(attribute_fields.values())
+ relations_data = relations_data.values(*fields_for_attrs)
+ for data in relations_data.iterator():
+ pk = data.get("pk")
+ result_data, data = handle_attribute_data(
+ pk,
+ data,
+ attribute_ids,
+ result_data,
+ attribute_fields,
+ "product attribute",
+ )
result: dict[int, dict[str, str]] = {
pk: {
@@ -211,25 +241,16 @@ def prepare_variants_relations_data(
It return dict where key is a product pk, value is a dict with relation fields data.
"""
- attribute_fields = ProductExportFields.VARIANT_ATTRIBUTE_FIELDS
warehouse_fields = ProductExportFields.WAREHOUSE_FIELDS
- channel_fields = ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS.copy()
result_data: dict[int, dict] = defaultdict(dict)
fields.add("variants__pk")
- if attribute_ids:
- fields.update(attribute_fields.values())
if warehouse_ids:
fields.update(warehouse_fields.values())
- if channel_ids:
- fields.update(channel_fields.values())
relations_data = queryset.values(*fields)
- channel_pk_lookup = channel_fields.pop("channel_pk")
- channel_slug_lookup = channel_fields.pop("slug")
-
for data in relations_data.iterator():
pk = data.get("variants__pk")
image = data.pop("variants__media__image", None)
@@ -237,22 +258,53 @@ def prepare_variants_relations_data(
result_data = add_image_uris_to_data(
pk, image, "variants__media__image", result_data
)
- result_data, data = handle_attribute_data(
- pk, data, attribute_ids, result_data, attribute_fields, "variant attribute"
- )
- result_data, data = handle_channel_data(
- pk,
- data,
- channel_ids,
- result_data,
- channel_pk_lookup,
- channel_slug_lookup,
- channel_fields,
- )
result_data, data = handle_warehouse_data(
pk, data, warehouse_ids, result_data, warehouse_fields
)
+ if channel_ids:
+ channel_fields = ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS
+ fields_for_channel = {"variant_id"}
+ fields_for_channel.update(channel_fields.values())
+ variants = ProductVariant.objects.filter(
+ Exists(queryset.filter(id=OuterRef("product_id")))
+ )
+ listings = ProductVariantChannelListing.objects.filter(
+ Exists(variants.filter(id=OuterRef("variant_id"))),
+ channel_id__in=channel_ids,
+ ).values(*fields_for_channel)
+
+ for listing in listings:
+ pk = listing.get("variant_id")
+ result_data, _ = handle_channel_data(
+ pk,
+ listing,
+ result_data,
+ ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS,
+ )
+
+ if attribute_ids:
+ fields_for_variant_attributes = {"variant_id"}
+ fields_for_variant_attributes.update(
+ ProductExportFields.VARIANT_ATTRIBUTE_FIELDS.values()
+ )
+ variants = ProductVariant.objects.filter(
+ Exists(queryset.filter(id=OuterRef("product_id")))
+ )
+ assigned_variant_attrs = AssignedVariantAttribute.objects.filter(
+ Exists(variants.filter(id=OuterRef("variant_id"))),
+ ).values(*fields_for_variant_attributes)
+ for assigned_variant_attr in assigned_variant_attrs:
+ pk = assigned_variant_attr.get("variant_id")
+ result_data, data = handle_attribute_data(
+ pk,
+ assigned_variant_attr,
+ attribute_ids,
+ result_data,
+ ProductExportFields.VARIANT_ATTRIBUTE_FIELDS,
+ "variant attribute",
+ )
+
result: dict[int, dict[str, str]] = {
pk: {
header: ", ".join(sorted(values)) if isinstance(values, set) else values
@@ -347,26 +399,19 @@ def handle_attribute_data(
def handle_channel_data(
pk: int,
data: dict,
- channel_ids: list[str] | None,
result_data: dict[int, dict],
- pk_lookup: str,
- slug_lookup: str,
fields: dict,
):
channel_data: dict = {}
-
- channel_pk = str(data.pop(pk_lookup, ""))
- channel_data = {
- "slug": data.pop(slug_lookup, None),
- }
for field, lookup in fields.items():
- channel_data[field] = data.pop(lookup, None)
-
- if channel_ids and channel_pk in channel_ids:
- result_data = add_channel_info_to_data(
- pk, channel_data, result_data, list(fields.keys())
- )
-
+ if field == "channel_pk":
+ continue
+ channel_data[field] = data.get(lookup, None)
+ result_data = add_channel_info_to_data(
+ pk,
+ channel_data,
+ result_data,
+ )
return result_data, data
@@ -428,9 +473,11 @@ def prepare_attribute_value(attribute_data: AttributeData):
AttributeInputType.FILE: _get_file_value,
AttributeInputType.REFERENCE: _get_reference_value,
AttributeInputType.NUMERIC: (
- lambda data: data.value_name
- if not attribute_data.unit
- else f"{data.value_name} {data.unit}"
+ lambda data: (
+ data.value_name
+ if not attribute_data.unit
+ else f"{data.value_name} {data.unit}"
+ )
),
AttributeInputType.RICH_TEXT: (
lambda data: clean_editor_js(data.rich_text, to_string=True)
@@ -503,16 +550,15 @@ def add_channel_info_to_data(
pk: int,
channel_data: dict[str, str | None],
result_data: dict[int, dict],
- fields: list[str],
) -> dict[int, dict]:
"""Add info about channel currency code, whether is published and publication date.
This functions adds info about channel to dict with product data.
It returns updated data.
"""
- slug = channel_data["slug"]
+ slug = channel_data.pop("slug", None)
if slug:
- for field in fields:
+ for field in channel_data.keys():
header = f"{slug} (channel {field.replace('_', ' ')})"
if header not in result_data[pk]:
result_data[pk][header] = channel_data[field]