Skip to content

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

Merge branch 'master' into add-products-csv-export

IKarbowiak713a3db7251f
diff --cc .isort.cfg
index b8795de6a5,19fed2f6f6..b814ace9b0
--- a/.isort.cfg
+++ b/.isort.cfg
@@@ -1,2 -1,2 +1,2 @@@
[settings]
- known_third_party = PIL,babel,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,text_unidecode,tqdm,versatileimagefield
-known_third_party = PIL,babel,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,markdown,measurement,mptt,oauthlib,opentracing,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,versatileimagefield
++known_third_party = PIL,babel,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,versatileimagefield
diff --cc CHANGELOG.md
index e44d4e91fe,06535f905b..e36c12868b
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,12 -14,11 +14,12 @@@ All notable, unreleased changes to thi
- Add our implementation of UUID scalar - #5646 by @koradon
- Add AppTokenVerify mutation - #5716 by @korycins
- Fix specific product voucher in draft orders - #5727 by @fowczarek
+- Add products csv export - #5255 by @IKarbowiak
- Explicit country assignment in default shipping zones - #5736 by @maarcingebala
- Drop `json_content` field from the `Menu` model - #5761 by @maarcingebala
- - Refactor JWT support - #5734 by @korycins
- Strip warehouse name in mutations - #5766 by @koradon
- Add missing OrderEvents during checkout flow - #5684 by @koradon
+ - Update google merchant to get tax rate based by plugin manager - #5823 by @gabmartinez
## 2.10.1
diff --cc pyproject.toml
index 15102e0413,25731c3d13..5511995628
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -43,9 -43,8 +43,9 @@@ html-to-draftjs = "^1.0.1
markdown = "^3.1.1"
maxminddb = "^1.5.4"
maxminddb-geolite2 = "^2018.701"
+petl ="^1.3.0"
opentracing = "^2.3.0"
- phonenumberslite = "^8.12.5"
+ phonenumberslite = "^8.12.6"
prices = "^1.0"
psycopg2-binary = "^2.8.3"
purl = "^1.5"
@@@ -60,9 -59,9 +60,10 @@@ uwsgi = {version = "^2.0.19", platform
weasyprint = ">=48"
oauthlib = "^3.0"
jaeger-client = "^4.3.0"
+openpyxl = "^3.0.3"
django-cache-url = "^3.1.2"
pyjwt = "^1.7.1"
+ python-json-logger = "^0.1.11"
pytimeparse = "^1.1.8"
[tool.poetry.dev-dependencies]
diff --cc requirements.txt
index a80e85a9bc,c99b4b9a62..018bc3d61c
--- a/requirements.txt
+++ b/requirements.txt
@@@ -55,13 -54,12 +55,13 @@@ graphene-federation==0.1.
graphql-core==2.3.2
graphql-relay==2.0.1
html-to-draftjs==1.0.1
- html5lib==1.0.1
+ html5lib==1.1
idna==2.9
jaeger-client==4.3.0
+jdcal==1.4.1
jmespath==0.10.0
jsonfield==3.1.0
- kombu==4.6.10
+ kombu==4.6.11
lxml==4.5.1
markdown==3.2.2
maxminddb==1.5.4
diff --cc saleor/csv/tests/export/products_data/test_get_products_data.py
index 7f2203f5d9,0000000000..ae5ec4cb60
mode 100644,000000..100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@@ -1,220 -1,0 +1,218 @@@
+from measurement.measures import Weight
+
+from .....product.models import Attribute, Product, ProductVariant, VariantImage
+from .....warehouse.models import Warehouse
+from ....utils.products_data import ProductExportFields, get_products_data
+from .utils import (
+ add_product_attribute_data_to_expected_data,
+ add_stocks_to_expected_data,
+ add_variant_attribute_data_to_expected_data,
+)
+
+
+def test_get_products_data(product, product_with_image, collection, image):
+ # given
+ product.weight = Weight(kg=5)
+ product.save()
+
+ collection.products.add(product)
+
+ variant = product.variants.first()
+ VariantImage.objects.create(variant=variant, image=product.images.first())
+
+ products = Product.objects.all()
+ export_fields = set(
+ value
+ for mapping in ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values()
+ for value in mapping.values()
+ )
+ warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
+ attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
+
+ variants = []
+ for variant in product.variants.all():
+ for attr in variant.attributes.all():
+ attribute_ids.append(str(attr.assignment.attribute.pk))
+ variant.weight = Weight(kg=3)
+ variants.append(variant)
+
+ ProductVariant.objects.bulk_update(variants, ["weight"])
+
+ variants = []
+ for variant in product_with_image.variants.all():
+ variant.weight = None
+ variants.append(variant)
+ ProductVariant.objects.bulk_update(variants, ["weight"])
+
+ # when
+ result_data = get_products_data(
+ products, export_fields, attribute_ids, warehouse_ids
+ )
+
+ # then
+ expected_data = []
+ for product in products.order_by("pk"):
+ product_data = {
+ "id": product.id,
+ "name": product.name,
+ "is_published": product.is_published,
+ "description": product.description,
+ "category__slug": product.category.slug,
- "price_amount": product.price_amount,
- "currency": product.currency,
+ "product_type__name": product.product_type.name,
+ "charge_taxes": product.charge_taxes,
+ "collections__slug": (
+ ""
+ if not product.collections.all()
+ else product.collections.first().slug
+ ),
+ "product_weight": (
+ "{} g".format(int(product.weight.value * 1000))
+ if product.weight
+ else ""
+ ),
+ "images__image": (
+ ""
+ if not product.images.all()
+ else "http://mirumee.com{}".format(product.images.first().image.url)
+ ),
+ }
+
+ product_data = add_product_attribute_data_to_expected_data(
+ product_data, product, attribute_ids
+ )
+
+ for variant in product.variants.all():
+ data = {
+ "variants__sku": variant.sku,
+ "variants__currency": variant.currency,
- "variants__price_override_amount": variant.price_override_amount,
++ "variants__price_amount": variant.price_amount,
+ "variants__cost_price_amount": variant.cost_price_amount,
+ "variants__images__image": (
+ ""
+ if not variant.images.all()
+ else "http://mirumee.com{}".format(variant.images.first().image.url)
+ ),
+ "variant_weight": (
+ "{} g".foramt(int(variant.weight.value * 1000))
+ if variant.weight
+ else ""
+ ),
+ }
+ data.update(product_data)
+
+ data = add_stocks_to_expected_data(data, variant, warehouse_ids)
+ data = add_variant_attribute_data_to_expected_data(
+ data, variant, attribute_ids
+ )
+
+ expected_data.append(data)
+
+ assert result_data == expected_data
+
+
+def test_get_products_data_for_specified_attributes(
+ product, product_with_variant_with_two_attributes
+):
+ # given
+ products = Product.objects.all()
+ export_fields = {"id", "variants__sku"}
+ attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()][:1]
+
+ # when
+ result_data = get_products_data(products, export_fields, attribute_ids, [])
+
+ # then
+ expected_data = []
+ for product in products.order_by("pk"):
+ product_data = {"id": product.pk}
+
+ product_data = add_product_attribute_data_to_expected_data(
+ product_data, product, attribute_ids
+ )
+
+ for variant in product.variants.all():
+ data = {}
+ data.update(product_data)
+ data["variants__sku"] = variant.sku
+ data = add_variant_attribute_data_to_expected_data(
+ data, variant, attribute_ids
+ )
+
+ expected_data.append(data)
+
+ assert result_data == expected_data
+
+
+def test_get_products_data_for_specified_warehouses(
+ product, product_with_image, variant_with_many_stocks
+):
+ # given
+ product.variants.add(variant_with_many_stocks)
+
+ products = Product.objects.all()
+ export_fields = {"id", "variants__sku"}
+ warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()][:2]
+ attribute_ids = []
+
+ # when
+ result_data = get_products_data(
+ products, export_fields, attribute_ids, warehouse_ids
+ )
+
+ # then
+ expected_data = []
+ for product in products.order_by("pk"):
+ product_data = {"id": product.pk}
+
+ for variant in product.variants.all():
+ data = {"variants__sku": variant.sku}
+ data.update(product_data)
+
+ data = add_stocks_to_expected_data(data, variant, warehouse_ids)
+
+ expected_data.append(data)
+
+ for res in result_data:
+ assert res in expected_data
+
+
+def test_get_products_data_for_specified_warehouses_and_attributes(
+ product,
+ variant_with_many_stocks,
+ product_with_image,
+ product_with_variant_with_two_attributes,
+):
+ # given
+ product.variants.add(variant_with_many_stocks)
+
+ products = Product.objects.all()
+ export_fields = {"id", "variants__sku"}
+ warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
+ attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
+
+ # when
+ result_data = get_products_data(
+ products, export_fields, attribute_ids, warehouse_ids
+ )
+
+ # then
+ expected_data = []
+ for product in products.order_by("pk"):
+ product_data = {"id": product.id}
+
+ product_data = add_product_attribute_data_to_expected_data(
+ product_data, product, attribute_ids
+ )
+
+ for variant in product.variants.all():
+ data = {"variants__sku": variant.sku}
+ data.update(product_data)
+
+ data = add_stocks_to_expected_data(data, variant, warehouse_ids)
+ data = add_variant_attribute_data_to_expected_data(
+ data, variant, attribute_ids
+ )
+
+ expected_data.append(data)
+
+ assert result_data == expected_data
diff --cc saleor/csv/tests/export/products_data/test_prepare_headers.py
index bac1c2e76a,0000000000..03733a2056
mode 100644,000000..100644
--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py
+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py
@@@ -1,272 -1,0 +1,262 @@@
+from .....graphql.csv.enums import ProductFieldEnum
+from .....product.models import Attribute
+from ....utils.products_data import (
+ get_attributes_headers,
+ get_export_fields_and_headers_info,
+ get_product_export_fields_and_headers,
+ get_warehouses_headers,
+)
+
+
+def test_get_export_fields_and_headers_fields_with_price():
+ # given
+ export_info = {
+ "fields": [
- ProductFieldEnum.PRICE.value,
- ProductFieldEnum.PRICE_OVERRIDE.value,
++ ProductFieldEnum.VARIANT_PRICE.value,
+ ProductFieldEnum.COLLECTIONS.value,
+ ProductFieldEnum.DESCRIPTION.value,
+ ],
+ "warehoses": [],
+ }
+
+ # when
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+
+ # then
+ expected_headers = [
+ "id",
- "price",
- "product currency",
- "price override",
++ "variant price",
+ "variant currency",
+ "collections",
+ "description",
+ ]
+
+ expected_fields = [
+ "id",
- "price_amount",
- "currency",
- "variants__price_override_amount",
++ "variants__price_amount",
+ "variants__currency",
+ "collections__slug",
+ "description",
+ ]
+
+ assert export_fields == expected_fields
+ assert file_headers == expected_headers
+
+
+def test_get_export_fields_and_headers_fields_with_cost_price():
+ # given
+ export_info = {
+ "fields": [
+ ProductFieldEnum.NAME.value,
+ ProductFieldEnum.COST_PRICE.value,
+ ProductFieldEnum.COLLECTIONS.value,
+ ],
+ "warehoses": [],
+ }
+
+ # when
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+
+ # then
+ expected_headers = [
+ "id",
+ "name",
+ "cost price",
+ "variant currency",
+ "collections",
+ ]
+
+ expected_fields = [
+ "id",
+ "name",
+ "variants__cost_price_amount",
+ "variants__currency",
+ "collections__slug",
+ ]
+
+ assert export_fields == expected_fields
+ assert file_headers == expected_headers
+
+
+def test_get_export_fields_and_headers_fields_with_cost_price_and_price_override():
+ # given
+ export_info = {
+ "fields": [
+ ProductFieldEnum.NAME.value,
- ProductFieldEnum.PRICE_OVERRIDE.value,
++ ProductFieldEnum.VARIANT_PRICE.value,
+ ProductFieldEnum.COST_PRICE.value,
+ ProductFieldEnum.COLLECTIONS.value,
+ ],
+ "warehoses": [],
+ }
+
+ # when
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+
+ # then
+ expected_headers = [
+ "id",
+ "name",
- "price override",
++ "variant price",
+ "variant currency",
+ "cost price",
+ "collections",
+ ]
+
+ expected_fields = [
+ "id",
+ "name",
- "variants__price_override_amount",
++ "variants__price_amount",
+ "variants__currency",
+ "variants__cost_price_amount",
+ "collections__slug",
+ ]
+
+ assert export_fields == expected_fields
+ assert file_headers == expected_headers
+
+
+def test_get_export_fields_and_headers_fields_without_price():
+ # given
+ export_info = {
+ "fields": [
+ ProductFieldEnum.COLLECTIONS.value,
+ ProductFieldEnum.DESCRIPTION.value,
+ ProductFieldEnum.VARIANT_SKU.value,
+ ],
+ "warehoses": [],
+ }
+
+ # when
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+
+ # then
+ expected_headers = ["id", "collections", "description", "variant sku"]
+
+ assert set(export_fields) == {
+ "collections__slug",
+ "id",
+ "variants__sku",
+ "description",
+ }
+ assert file_headers == expected_headers
+
+
+def test_get_export_fields_and_headers_no_fields():
+ export_fields, file_headers = get_product_export_fields_and_headers({})
+
+ assert export_fields == ["id"]
+ assert file_headers == ["id"]
+
+
+def test_get_attributes_headers(product_with_multiple_values_attributes):
+ # given
+ attribute_ids = Attribute.objects.values_list("id", flat=True)
+ export_info = {"attributes": attribute_ids}
+
+ # when
+ attributes_headers = get_attributes_headers(export_info)
+
+ # then
+ product_headers = []
+ variant_headers = []
+ for attr in Attribute.objects.all():
+ if attr.product_types.exists():
+ product_headers.append(f"{attr.slug} (product attribute)")
+ if attr.product_variant_types.exists():
+ variant_headers.append(f"{attr.slug} (variant attribute)")
+
+ expected_headers = product_headers + variant_headers
+ assert attributes_headers == expected_headers
+
+
+def test_get_attributes_headers_lack_of_attributes_ids():
+ # given
+ export_info = {}
+
+ # when
+ attributes_headers = get_attributes_headers(export_info)
+
+ # then
+ assert attributes_headers == []
+
+
+def test_get_warehouses_headers(warehouses):
+ # given
+ warehouse_ids = [warehouses[0].pk]
+ export_info = {"warehouses": warehouse_ids}
+
+ # when
+ warehouse_headers = get_warehouses_headers(export_info)
+
+ # then
+ assert warehouse_headers == [f"{warehouses[0].slug} (warehouse quantity)"]
+
+
+def test_get_warehouses_headers_lack_of_warehouse_ids():
+ # given
+ export_info = {}
+
+ # when
+ warehouse_headers = get_warehouses_headers(export_info)
+
+ # then
+ assert warehouse_headers == []
+
+
+def test_get_export_fields_and_headers_info(
+ warehouses, product_with_multiple_values_attributes
+):
+ # given
+ warehouse_ids = [w.pk for w in warehouses]
+ attribute_ids = [attr.pk for attr in Attribute.objects.all()]
+ export_info = {
+ "fields": [
- ProductFieldEnum.PRICE.value,
- ProductFieldEnum.PRICE_OVERRIDE.value,
++ ProductFieldEnum.VARIANT_PRICE.value,
+ ProductFieldEnum.COLLECTIONS.value,
+ ProductFieldEnum.DESCRIPTION.value,
+ ],
+ "warehouses": warehouse_ids,
+ "attributes": attribute_ids,
+ }
+
+ expected_file_headers = [
+ "id",
- "price",
- "product currency",
- "price override",
++ "variant price",
+ "variant currency",
+ "collections",
+ "description",
+ ]
+
+ # when
+ export_fields, file_headers, data_headers = get_export_fields_and_headers_info(
+ export_info
+ )
+
+ # then
+ expected_fields = [
+ "id",
- "price_amount",
- "currency",
- "variants__price_override_amount",
++ "variants__price_amount",
+ "variants__currency",
+ "collections__slug",
+ "description",
+ ]
+
+ product_headers = []
+ variant_headers = []
+ for attr in Attribute.objects.all().order_by("slug"):
+ if attr.product_types.exists():
+ product_headers.append(f"{attr.slug} (product attribute)")
+ if attr.product_variant_types.exists():
+ variant_headers.append(f"{attr.slug} (variant attribute)")
+
+ warehouse_headers = [f"{w.slug} (warehouse quantity)" for w in warehouses]
+ excepted_headers = (
+ expected_fields + product_headers + variant_headers + warehouse_headers
+ )
+
+ expected_file_headers += product_headers + variant_headers + warehouse_headers
+
+ assert expected_file_headers == file_headers
+ assert set(export_fields) == set(expected_fields)
+ assert data_headers == excepted_headers
diff --cc saleor/csv/utils/products_data.py
index b359a7d838,0000000000..2eba96c957
mode 100644,000000..100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@@ -1,467 -1,0 +1,461 @@@
+import os
+from collections import ChainMap, defaultdict
+from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union
+
+from django.conf import settings
+from django.db.models import Case, CharField, Value as V, When
+from django.db.models.functions import Concat
+
+from ...core.utils import build_absolute_uri
+from ...product.models import Attribute
+from ...warehouse.models import Warehouse
+
+if TYPE_CHECKING:
+ # flake8: noqa
+ from django.db.models import QuerySet
+
+
+class ProductExportFields:
+ """Data structure with fields for product export."""
+
+ HEADERS_TO_FIELDS_MAPPING = {
+ "fields": {
+ "id": "id",
+ "name": "name",
+ "description": "description",
+ "visible": "is_published",
+ "category": "category__slug",
+ "product type": "product_type__name",
+ "charge taxes": "charge_taxes",
+ "product weight": "product_weight",
- "price": "price_amount",
- "product currency": "currency",
+ "variant sku": "variants__sku",
+ "variant weight": "variant_weight",
+ "cost price": "variants__cost_price_amount",
- "price override": "variants__price_override_amount",
++ "variant price": "variants__price_amount",
+ "variant currency": "variants__currency",
+ },
+ "product_many_to_many": {
+ "collections": "collections__slug",
+ "product images": "images__image",
+ },
+ "variant_many_to_many": {"variant images": "variants__images__image",},
+ }
+
+ PRODUCT_ATTRIBUTE_FIELDS = {
+ "value": "attributes__values__slug",
+ "slug": "attributes__assignment__attribute__slug",
+ "attribute_pk": "attributes__assignment__attribute__pk",
+ }
+
+ WAREHOUSE_FIELDS = {
+ "slug": "variants__stocks__warehouse__slug",
+ "quantity": "variants__stocks__quantity",
+ "warehouse_pk": "variants__stocks__warehouse__id",
+ }
+
+ VARIANT_ATTRIBUTE_FIELDS = {
+ "value": "variants__attributes__values__slug",
+ "slug": "variants__attributes__assignment__attribute__slug",
+ "attribute_pk": "variants__attributes__assignment__attribute__pk",
+ }
+
+
+def get_export_fields_and_headers_info(
+ export_info: Dict[str, list]
+) -> Tuple[List[str], List[str], List[str]]:
+ """Get export fields, all headers and headers mapping.
+
+ Based on export_info returns exported fields, fields to headers mapping and
+ all headers.
+ Headers contains product, variant, attribute and warehouse headers.
+ """
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+ attributes_headers = get_attributes_headers(export_info)
+ warehouses_headers = get_warehouses_headers(export_info)
+
+ data_headers = export_fields + attributes_headers + warehouses_headers
+ file_headers += attributes_headers + warehouses_headers
+ return export_fields, file_headers, data_headers
+
+
+def get_product_export_fields_and_headers(
+ export_info: Dict[str, list]
+) -> Tuple[List[str], List[str]]:
+ """Get export fields from export info and prepare headers mapping.
+
+ Based on given fields headers from export info, export fields set and
+ headers mapping is prepared.
+ """
+ export_fields = ["id"]
+ file_headers = ["id"]
+
+ fields = export_info.get("fields")
+ if not fields:
+ return export_fields, file_headers
+
+ fields_mapping = dict(
+ ChainMap(*reversed(ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values())) # type: ignore
+ )
+
+ for field in fields:
+ lookup_field = fields_mapping[field]
+ export_fields.append(lookup_field)
+ file_headers.append(field)
+ # if price is exported, currency is needed too
- if field == "price":
- lookup_field = fields_mapping["product currency"]
- export_fields.append(lookup_field)
- file_headers.append("product currency")
- elif field == "price override" or field == "cost price":
++ if field == "variant price" or field == "cost price":
+ lookup_field = fields_mapping["variant currency"]
+ if lookup_field not in export_fields:
+ export_fields.append(lookup_field)
+ file_headers.append("variant currency")
+
+ return export_fields, file_headers
+
+
+def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
+ """Get headers for exported attributes.
+
+ Headers are build from slug and contains information if it's a product or variant
+ attribute. Respectively for product: "slug-value (product attribute)"
+ and for variant: "slug-value (variant attribute)".
+ """
+
+ attribute_ids = export_info.get("attributes")
+ if not attribute_ids:
+ return []
+
+ attributes = Attribute.objects.filter(pk__in=attribute_ids).order_by("slug")
+
+ products_headers = (
+ attributes.filter(product_types__isnull=False)
+ .annotate(header=Concat("slug", V(" (product attribute)")))
+ .values_list("header", flat=True)
+ )
+
+ variant_headers = (
+ attributes.filter(product_variant_types__isnull=False)
+ .annotate(header=Concat("slug", V(" (variant attribute)")))
+ .values_list("header", flat=True)
+ )
+
+ return list(products_headers) + list(variant_headers)
+
+
+def get_warehouses_headers(export_info: Dict[str, list]) -> List[str]:
+ """Get headers for exported warehouses.
+
+ Headers are build from slug. Example: "slug-value (warehouse quantity)"
+ """
+ warehouse_ids = export_info.get("warehouses")
+ if not warehouse_ids:
+ return []
+
+ warehouses_headers = (
+ Warehouse.objects.filter(pk__in=warehouse_ids)
+ .order_by("slug")
+ .annotate(header=Concat("slug", V(" (warehouse quantity)")))
+ .values_list("header", flat=True)
+ )
+
+ return list(warehouses_headers)
+
+
+def get_products_data(
+ queryset: "QuerySet",
+ export_fields: Set[str],
+ attribute_ids: Optional[List[int]],
+ warehouse_ids: Optional[List[int]],
+) -> List[Dict[str, Union[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
+ csv writer and list of attribute and warehouse headers.
+ """
+
+ products_with_variants_data = []
+
+ product_fields = set(
+ ProductExportFields.HEADERS_TO_FIELDS_MAPPING["fields"].values()
+ )
+ product_export_fields = export_fields & product_fields
+ product_export_fields.add("variants__id")
+
+ products_data = (
+ queryset.annotate(
+ product_weight=Case(
+ When(weight__isnull=False, then=Concat("weight", V(" g"))),
+ default=V(""),
+ output_field=CharField(),
+ ),
+ variant_weight=Case(
+ When(
+ variants__weight__isnull=False,
+ then=Concat("variants__weight", V(" g")),
+ ),
+ default=V(""),
+ output_field=CharField(),
+ ),
+ )
+ .order_by("pk", "variants__pk")
+ .values(*product_export_fields)
+ .distinct("pk", "variants__pk")
+ )
+
+ products_relations_data = get_products_relations_data(
+ queryset, export_fields, attribute_ids
+ )
+
+ variants_relations_data = get_variants_relations_data(
+ queryset, export_fields, attribute_ids, warehouse_ids
+ )
+
+ for product_data in products_data:
+ pk = product_data["id"]
+ variant_pk = product_data.pop("variants__id")
+
+ product_relations_data: Dict[str, str] = products_relations_data.get(pk, {})
+ variant_relations_data: Dict[str, str] = variants_relations_data.get(
+ variant_pk, {}
+ )
+
+ data = {**product_data, **product_relations_data, **variant_relations_data}
+
+ products_with_variants_data.append(data)
+
+ return products_with_variants_data
+
+
+def get_products_relations_data(
+ queryset: "QuerySet", export_fields: Set[str], attribute_ids: Optional[List[int]]
+) -> Dict[int, Dict[str, str]]:
+ """Get data about product relations fields.
+
+ 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.
+ """
+ many_to_many_fields = set(
+ ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()
+ )
+ relations_fields = export_fields & many_to_many_fields
+ if relations_fields or attribute_ids:
+ return prepare_products_relations_data(
+ queryset, relations_fields, attribute_ids
+ )
+
+ return {}
+
+
+def prepare_products_relations_data(
+ queryset: "QuerySet", fields: Set[str], attribute_ids: Optional[List[int]]
+) -> 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.
+ """
+ attribute_fields = ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS
+ result_data: Dict[int, dict] = defaultdict(dict)
+
+ fields.add("pk")
+ if attribute_ids:
+ fields.update(ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS.values())
+
+ relations_data = queryset.values(*fields)
+
+ for data in relations_data.iterator():
+ pk = data.get("pk")
+ collection = data.get("collections__slug")
+ image = data.pop("images__image", None)
+
+ result_data = add_image_uris_to_data(pk, image, "images__image", result_data)
+ result_data = add_collection_info_to_data(pk, collection, result_data)
+
+ # handle attributes
+ attribute_data: dict = {}
+
+ attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
+ attribute_data = {
+ "slug": data.pop(attribute_fields["slug"], None),
+ "value": data.pop(attribute_fields["value"], None),
+ }
+
+ if attribute_ids and attribute_pk in attribute_ids:
+ result_data = add_attribute_info_to_data(
+ pk, attribute_data, "product attribute", result_data
+ )
+
+ result: Dict[int, Dict[str, str]] = {
+ pk: {header: ", ".join(sorted(values)) for header, values in data.items()}
+ for pk, data in result_data.items()
+ }
+ return result
+
+
+def get_variants_relations_data(
+ queryset: "QuerySet",
+ export_fields: Set[str],
+ attribute_ids: Optional[List[int]],
+ warehouse_ids: Optional[List[int]],
+) -> Dict[int, Dict[str, str]]:
+ """Get data about variants relations fields.
+
+ If any many to many fields are in export_fields or some attribute_ids or
+ warehouse_ids exists then dict with variant relations fields is returned.
+ Otherwise it returns empty dict.
+ """
+ many_to_many_fields = set(
+ ProductExportFields.HEADERS_TO_FIELDS_MAPPING["variant_many_to_many"].values()
+ )
+ relations_fields = export_fields & many_to_many_fields
+ if relations_fields or attribute_ids or warehouse_ids:
+ return prepare_variants_relations_data(
+ queryset, relations_fields, attribute_ids, warehouse_ids
+ )
+
+ return {}
+
+
+def prepare_variants_relations_data(
+ queryset: "QuerySet",
+ fields: Set[str],
+ attribute_ids: Optional[List[int]],
+ warehouse_ids: Optional[List[int]],
+) -> Dict[int, Dict[str, str]]:
+ """Prepare data about variants relation fields for given queryset.
+
+ It return dict where key is a product pk, value is a dict with relation fields data.
+ """
+ warehouse_fields = ProductExportFields.WAREHOUSE_FIELDS
+ attribute_fields = ProductExportFields.VARIANT_ATTRIBUTE_FIELDS
+
+ result_data: Dict[int, dict] = defaultdict(dict)
+ fields.add("variants__pk")
+
+ if attribute_ids:
+ fields.update(ProductExportFields.VARIANT_ATTRIBUTE_FIELDS.values())
+ if warehouse_ids:
+ fields.update(ProductExportFields.WAREHOUSE_FIELDS.values())
+
+ relations_data = queryset.values(*fields)
+
+ for data in relations_data.iterator():
+ pk = data.get("variants__pk")
+ image = data.pop("variants__images__image", None)
+
+ result_data = add_image_uris_to_data(
+ pk, image, "variants__images__image", result_data
+ )
+
+ # handle attribute and warehouse data
+ attribute_data: dict = {}
+ warehouse_data: dict = {}
+
+ attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
+ attribute_data = {
+ "slug": data.pop(attribute_fields["slug"], None),
+ "value": data.pop(attribute_fields["value"], None),
+ }
+
+ warehouse_pk = str(data.pop(warehouse_fields["warehouse_pk"], ""))
+ warehouse_data = {
+ "slug": data.pop(warehouse_fields["slug"], None),
+ "qty": data.pop(warehouse_fields["quantity"], None),
+ }
+
+ if attribute_ids and attribute_pk in attribute_ids:
+ result_data = add_attribute_info_to_data(
+ pk, attribute_data, "variant attribute", result_data
+ )
+
+ if warehouse_ids and warehouse_pk in warehouse_ids:
+ result_data = add_warehouse_info_to_data(pk, warehouse_data, result_data)
+
+ result: Dict[int, Dict[str, str]] = {
+ pk: {
+ header: ", ".join(sorted(values)) if isinstance(values, set) else values
+ for header, values in data.items()
+ }
+ for pk, data in result_data.items()
+ }
+ return result
+
+
+def add_collection_info_to_data(
+ pk: int, collection: str, result_data: Dict[int, dict]
+) -> Dict[int, dict]:
+ """Add collection info to product data.
+
+ This functions adds info about collection to dict with product data.
+ If some collection info already exists in data, collection slug is added
+ to set with other values.
+ It returns updated product data.
+ """
+
+ if collection:
+ header = "collections__slug"
+ if header in result_data[pk]:
+ result_data[pk][header].add(collection) # type: ignore
+ else:
+ result_data[pk][header] = {collection}
+ return result_data
+
+
+def add_image_uris_to_data(
+ pk: int, image: str, header: str, result_data: Dict[int, dict]
+) -> Dict[int, dict]:
+ """Add absolute uri of given image path to product or variant data.
+
+ This function based on given image path creates absolute uri and adds it to dict
+ with variant or product data. If some info about images already exists in data,
+ absolute uri of given image is added to set with other uris.
+ """
+ if image:
+ uri = build_absolute_uri(os.path.join(settings.MEDIA_URL, image))
+ if header in result_data[pk]:
+ result_data[pk][header].add(uri)
+ else:
+ result_data[pk][header] = {uri}
+ return result_data
+
+
+def add_attribute_info_to_data(
+ pk: int,
+ attribute_data: Dict[str, Optional[Union[str]]],
+ attribute_owner: str,
+ result_data: Dict[int, dict],
+) -> Dict[int, dict]:
+ """Add info about attribute to variant or product data.
+
+ This functions adds info about attribute to dict with variant or product data.
+ If attribute with given slug already exists in data, attribute value is added
+ to set with values.
+ It returns updated data and attribute header created based on attribute slug.
+ """
+ slug = attribute_data["slug"]
+ header = None
+ if slug:
+ header = f"{slug} ({attribute_owner})"
+ if header in result_data[pk]:
+ result_data[pk][header].add(attribute_data["value"]) # type: ignore
+ else:
+ result_data[pk][header] = {attribute_data["value"]}
+ return result_data
+
+
+def add_warehouse_info_to_data(
+ pk: int,
+ warehouse_data: Dict[str, Union[Optional[str]]],
+ result_data: Dict[int, dict],
+) -> Dict[int, dict]:
+ """Add info about stock quantity to variant data.
+
+ This functions adds info about stock quantity to dict with variant data.
+ It returns updated data and warehouse header created based on warehouse slug.
+ """
+
+ slug = warehouse_data["slug"]
+ if slug:
+ warehouse_qty_header = f"{slug} (warehouse quantity)"
+ if warehouse_qty_header not in result_data[pk]:
+ result_data[pk][warehouse_qty_header] = warehouse_data["qty"]
+
+ return result_data
diff --cc saleor/graphql/csv/enums.py
index 9b2155c275,0000000000..f547fe044d
mode 100644,000000..100644
--- a/saleor/graphql/csv/enums.py
+++ b/saleor/graphql/csv/enums.py
@@@ -1,43 -1,0 +1,42 @@@
+import graphene
+
+from ...csv import ExportEvents, FileTypes
+from ...graphql.core.enums import to_enum
+
+ExportEventEnum = to_enum(ExportEvents)
+FileTypeEnum = to_enum(FileTypes)
+
+
+class ExportScope(graphene.Enum):
+ ALL = "all"
+ IDS = "ids"
+ FILTER = "filter"
+
+ @property
+ def description(self):
+ # pylint: disable=no-member
+ description_mapping = {
+ ExportScope.ALL.name: "Export all products.",
+ ExportScope.IDS.name: "Export products with given ids.",
+ ExportScope.FILTER.name: "Export the filtered products.",
+ }
+ if self.name in description_mapping:
+ return description_mapping[self.name]
+ raise ValueError("Unsupported enum value: %s" % self.value)
+
+
+class ProductFieldEnum(graphene.Enum):
+ NAME = "name"
+ DESCRIPTION = "description"
+ PRODUCT_TYPE = "product type"
+ CATEGORY = "category"
+ VISIBLE = "visible"
+ PRODUCT_WEIGHT = "product weight"
+ COLLECTIONS = "collections"
+ CHARGE_TAXES = "charge taxes"
- PRICE = "price"
+ PRODUCT_IMAGES = "product images"
+ VARIANT_SKU = "variant sku"
- PRICE_OVERRIDE = "price override"
++ VARIANT_PRICE = "variant price"
+ COST_PRICE = "cost price"
+ VARIANT_WEIGHT = "variant weight"
+ VARIANT_IMAGES = "variant images"
diff --cc saleor/graphql/csv/tests/mutations/test_export_products.py
index 5b9ebee121,0000000000..daf1e0bdd2
mode 100644,000000..100644
--- a/saleor/graphql/csv/tests/mutations/test_export_products.py
+++ b/saleor/graphql/csv/tests/mutations/test_export_products.py
@@@ -1,321 -1,0 +1,321 @@@
+from unittest.mock import ANY, patch
+
+import graphene
+import pytest
+
+from .....csv import ExportEvents
+from .....csv.models import ExportEvent
+from .....product.models import Attribute
+from .....warehouse.models import Warehouse
+from ....tests.utils import get_graphql_content
+from ...enums import ExportScope, FileTypeEnum, ProductFieldEnum
+
+EXPORT_PRODUCTS_MUTATION = """
+ mutation ExportProducts($input: ExportProductsInput!){
+ exportProducts(input: $input){
+ exportFile {
+ id
+ status
+ createdAt
+ updatedAt
+ url
+ user {
+ email
+ }
+ app {
+ name
+ }
+ }
+ exportErrors {
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+ "input, called_data",
+ [
+ (
+ {
+ "scope": ExportScope.ALL.name,
+ "exportInfo": {},
+ "fileType": FileTypeEnum.CSV.name,
+ },
+ {"all": ""},
+ ),
+ (
+ {
+ "scope": ExportScope.FILTER.name,
+ "filter": {"isPublished": True},
+ "exportInfo": {},
+ "fileType": FileTypeEnum.CSV.name,
+ },
+ {"filter": {"is_published": True}},
+ ),
+ ],
+)
+@patch("saleor.graphql.csv.mutations.export_products_task.delay")
+def test_export_products_mutation(
+ export_products_mock,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ permission_manage_apps,
+ input,
+ called_data,
+):
+ query = EXPORT_PRODUCTS_MUTATION
+ user = staff_api_client.user
+ variables = {"input": input}
+
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[permission_manage_products, permission_manage_apps],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["exportProducts"]
+ export_file_data = data["exportFile"]
+
+ export_products_mock.assert_called_once_with(
+ ANY, called_data, {}, FileTypeEnum.CSV.value
+ )
+
+ assert not data["exportErrors"]
+ assert data["exportFile"]["id"]
+ assert export_file_data["createdAt"]
+ assert export_file_data["user"]["email"] == staff_api_client.user.email
+ assert export_file_data["app"] is None
+ assert ExportEvent.objects.filter(
+ user=user, app=None, type=ExportEvents.EXPORT_PENDING
+ ).exists()
+
+
+@patch("saleor.graphql.csv.mutations.export_products_task.delay")
+def test_export_products_mutation_by_app(
+ export_products_mock,
+ app_api_client,
+ product_list,
+ permission_manage_products,
+ permission_manage_apps,
+ permission_manage_staff,
+):
+ query = EXPORT_PRODUCTS_MUTATION
+ app = app_api_client.app
+ variables = {
+ "input": {
+ "scope": ExportScope.ALL.name,
+ "exportInfo": {},
+ "fileType": FileTypeEnum.CSV.name,
+ }
+ }
+
+ response = app_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[
+ permission_manage_products,
+ permission_manage_apps,
+ permission_manage_staff,
+ ],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["exportProducts"]
+ export_file_data = data["exportFile"]
+
+ export_products_mock.assert_called_once_with(
+ ANY, {"all": ""}, {}, FileTypeEnum.CSV.value
+ )
+
+ assert not data["exportErrors"]
+ assert data["exportFile"]["id"]
+ assert export_file_data["createdAt"]
+ assert export_file_data["user"] is None
+ assert export_file_data["app"]["name"] == app.name
+ assert ExportEvent.objects.filter(
+ user=None, app=app, type=ExportEvents.EXPORT_PENDING
+ ).exists()
+
+
+@patch("saleor.graphql.csv.mutations.export_products_task.delay")
+def test_export_products_mutation_ids_scope(
+ export_products_mock,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ permission_manage_apps,
+):
+ query = EXPORT_PRODUCTS_MUTATION
+ user = staff_api_client.user
+
+ products = product_list[:2]
+
+ ids = []
+ pks = set()
+ for product in products:
+ pks.add(str(product.pk))
+ ids.append(graphene.Node.to_global_id("Product", product.pk))
+
+ variables = {
+ "input": {
+ "scope": ExportScope.IDS.name,
+ "ids": ids,
+ "exportInfo": {
- "fields": [ProductFieldEnum.PRICE_OVERRIDE.name],
++ "fields": [ProductFieldEnum.VARIANT_PRICE.name],
+ "warehouses": [],
+ "attributes": [],
+ },
+ "fileType": FileTypeEnum.XLSX.name,
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[permission_manage_products, permission_manage_apps],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["exportProducts"]
+ export_file_data = data["exportFile"]
+
+ export_products_mock.assert_called_once()
+ (call_args, call_kwargs,) = export_products_mock.call_args
+
+ assert set(call_args[1]["ids"]) == pks
- assert call_args[2] == {"fields": [ProductFieldEnum.PRICE_OVERRIDE.value]}
++ assert call_args[2] == {"fields": [ProductFieldEnum.VARIANT_PRICE.value]}
+ assert call_args[3] == FileTypeEnum.XLSX.value
+
+ assert not data["exportErrors"]
+ assert data["exportFile"]["id"]
+ assert export_file_data["createdAt"]
+ assert export_file_data["user"]["email"] == staff_api_client.user.email
+ assert export_file_data["app"] is None
+ assert ExportEvent.objects.filter(
+ user=user, app=None, type=ExportEvents.EXPORT_PENDING
+ ).exists()
+
+
+@patch("saleor.graphql.csv.mutations.export_products_task.delay")
+def test_export_products_mutation_with_warehouse_and_attribute_ids(
+ export_products_mock,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ permission_manage_apps,
+):
+ query = EXPORT_PRODUCTS_MUTATION
+ user = staff_api_client.user
+
+ products = product_list[:2]
+
+ ids = []
+ pks = set()
+ for product in products:
+ pks.add(str(product.pk))
+ ids.append(graphene.Node.to_global_id("Product", product.pk))
+
+ attribute_pks = [str(attr.pk) for attr in Attribute.objects.all()]
+ warehouse_pks = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
+
+ attribute_ids = [
+ graphene.Node.to_global_id("Attribute", pk) for pk in attribute_pks
+ ]
+ warehouse_ids = [
+ graphene.Node.to_global_id("Warehouse", pk) for pk in warehouse_pks
+ ]
+
+ variables = {
+ "input": {
+ "scope": ExportScope.IDS.name,
+ "ids": ids,
+ "exportInfo": {
- "fields": [ProductFieldEnum.PRICE_OVERRIDE.name],
++ "fields": [ProductFieldEnum.VARIANT_PRICE.name],
+ "warehouses": warehouse_ids,
+ "attributes": attribute_ids,
+ },
+ "fileType": FileTypeEnum.CSV.name,
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query,
+ variables=variables,
+ permissions=[permission_manage_products, permission_manage_apps],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["exportProducts"]
+ export_file_data = data["exportFile"]
+
+ export_products_mock.assert_called_once()
+ (call_args, call_kwargs,) = export_products_mock.call_args
+
+ assert set(call_args[1]["ids"]) == pks
+ assert call_args[2] == {
- "fields": [ProductFieldEnum.PRICE_OVERRIDE.value],
++ "fields": [ProductFieldEnum.VARIANT_PRICE.value],
+ "warehouses": warehouse_pks,
+ "attributes": attribute_pks,
+ }
+ assert call_args[3] == FileTypeEnum.CSV.value
+
+ assert not data["exportErrors"]
+ assert data["exportFile"]["id"]
+ assert export_file_data["createdAt"]
+ assert export_file_data["user"]["email"] == staff_api_client.user.email
+ assert export_file_data["app"] is None
+ assert ExportEvent.objects.filter(
+ user=user, app=None, type=ExportEvents.EXPORT_PENDING
+ ).exists()
+
+
+ "input, error_field",
+ [
+ (
+ {
+ "scope": ExportScope.FILTER.name,
+ "exportInfo": {},
+ "fileType": FileTypeEnum.CSV.name,
+ },
+ "filter",
+ ),
+ (
+ {
+ "scope": ExportScope.IDS.name,
+ "exportInfo": {},
+ "fileType": FileTypeEnum.CSV.name,
+ },
+ "ids",
+ ),
+ ],
+)
+@patch("saleor.graphql.csv.mutations.export_products_task.delay")
+def test_export_products_mutation_failed(
+ export_products_mock,
+ staff_api_client,
+ product_list,
+ permission_manage_products,
+ input,
+ error_field,
+):
+ query = EXPORT_PRODUCTS_MUTATION
+ user = staff_api_client.user
+ variables = {"input": input}
+
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["exportProducts"]
+ errors = data["exportErrors"]
+
+ export_products_mock.assert_not_called()
+
+ assert data["exportErrors"]
+ assert errors[0]["field"] == error_field
+ assert not ExportEvent.objects.filter(
+ user=user, type=ExportEvents.EXPORT_PENDING
+ ).exists()
diff --cc saleor/graphql/schema.graphql
index bdb44d2c5e,4925d28f57..04681fa001
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@@ -3565,24 -3450,6 +3566,23 @@@ enum ProductErrorCode
VARIANT_NO_DIGITAL_CONTENT
}
+enum ProductFieldEnum {
+ NAME
+ DESCRIPTION
+ PRODUCT_TYPE
+ CATEGORY
+ VISIBLE
+ PRODUCT_WEIGHT
+ COLLECTIONS
+ CHARGE_TAXES
- PRICE
+ PRODUCT_IMAGES
+ VARIANT_SKU
- PRICE_OVERRIDE
++ VARIANT_PRICE
+ COST_PRICE
+ VARIANT_WEIGHT
+ VARIANT_IMAGES
+}
+
input ProductFilterInput {
isPublished: Boolean
collections: [ID]