Skip to content

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

Support empty SKUs for products variants (#7633)

Rafał Pitoń6142cbea9342
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01d1894ccf..e7a2b50867 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -271,6 +271,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Use root level channel argument for filtering and sorting - #7374 by @IKarbowiak
- drop `channel` field from filters and sorters
- Drop top-level `checkoutLine` query from the schema with related resolver, use `checkout` query instead - #7623 by @dexon44
+- Make SKU an optional field on `ProductVariant` - #7633 by @rafalp
### Other
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 32da2d9d3b..06d5046270 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -197,6 +197,7 @@ def _create_line_for_order(
translated_product_name=translated_product_name,
translated_variant_name=translated_variant_name,
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/core/analytics.py b/saleor/core/analytics.py
index 6abd553af3..5b49ab636d 100644
--- a/saleor/core/analytics.py
+++ b/saleor/core/analytics.py
@@ -52,7 +52,7 @@ def get_order_payloads(order):
str(order_line),
order_line.unit_price.gross,
quantity=order_line.quantity,
- item_id=order_line.product_sku,
+ item_id=order_line.product_sku or order_line.product_variant_id,
)
for order_line in order.lines.all()
]
diff --git a/saleor/core/tests/test_analytics.py b/saleor/core/tests/test_analytics.py
index 97ebd33186..19b355888d 100644
--- a/saleor/core/tests/test_analytics.py
+++ b/saleor/core/tests/test_analytics.py
@@ -28,6 +28,31 @@ def test_get_order_payloads(order_with_lines):
assert Decimal(item["ip"]) == line.unit_price.gross.amount
+def test_get_order_without_sku_payloads(order_with_lines):
+ order = order_with_lines
+ order.lines.update(product_sku=None, product_variant_id="TEST_ID")
+
+ generator = get_order_payloads(order)
+ data = list(generator)
+ assert len(data) == order.lines.count() + 1
+
+ transaction = data[0]
+ assert transaction["ti"] == order.pk
+ assert transaction["cu"] == order.total.currency
+ assert Decimal(transaction["tr"]) == order.total.gross.amount
+ assert Decimal(transaction["tt"]) == order.total.tax.amount
+ assert Decimal(transaction["ts"]) == order.shipping_price.net.amount
+
+ for i, line in enumerate(order.lines.all()):
+ item = data[i + 1]
+ assert item["ti"] == order.pk
+ assert item["in"] == line.variant.display_product()
+ assert item["ic"] == line.product_variant_id
+ assert item["iq"] == str(int(line.quantity))
+ assert item["cu"] == line.unit_price.currency
+ assert Decimal(item["ip"]) == line.unit_price.gross.amount
+
+
@mock.patch("google_measurement_protocol.report")
def test_report_order_has_no_errors(mocked_ga_report, order_with_lines, settings):
settings.GOOGLE_ANALYTICS_TRACKING_ID = "ga_id"
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 52a92525e8..648529093a 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -599,6 +599,7 @@ def create_order_lines(order, discounts, how_many=10):
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index c1a995fb82..ae42f9a21f 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
@@ -34,6 +34,10 @@ def test_get_products_data(product, product_with_image, collection, image, chann
variant = product.variants.first()
VariantMedia.objects.create(variant=variant, media=product.media.first())
+ variant_without_sku = product.variants.last()
+ variant_without_sku.sku = None
+ variant_without_sku.save()
+
products = Product.objects.all()
export_fields = set(
value
@@ -99,6 +103,9 @@ def test_get_products_data(product, product_with_image, collection, image, chann
for variant in product.variants.all():
data = {
+ "variants__id": graphene.Node.to_global_id(
+ "ProductVariant", variant.pk
+ ),
"variants__sku": variant.sku,
"variants__media__image": (
""
@@ -271,6 +278,10 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
date_time_attribute,
)
+ variant_without_sku = product.variants.last()
+ variant_without_sku.sku = None
+ variant_without_sku.save()
+
# add boolean attribute
associate_attribute_values_to_instance(
variant_with_many_stocks,
diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.py
index e651df2d8d..b53fb75af2 100644
--- a/saleor/csv/tests/export/test_export.py
+++ b/saleor/csv/tests/export/test_export.py
@@ -46,7 +46,11 @@ def test_export_products(
):
# given
export_info = {
- "fields": [ProductFieldEnum.NAME.value],
+ "fields": [
+ ProductFieldEnum.NAME.value,
+ ProductFieldEnum.VARIANT_ID.value,
+ ProductFieldEnum.VARIANT_SKU.value,
+ ],
"warehouses": [],
"attributes": [],
"channels": [],
@@ -55,12 +59,14 @@ def test_export_products(
mock_file = MagicMock(spec=File)
create_file_with_headers_mock.return_value = mock_file
+ product_list[0].variants.update(sku=None)
+
# when
export_products(user_export_file, {"all": ""}, export_info, file_type)
# then
create_file_with_headers_mock.assert_called_once_with(
- ["id", "name"], ";", file_type
+ ["id", "name", "variant id", "variant sku"], ";", file_type
)
assert export_products_in_batches_mock.call_count == 1
args, kwargs = export_products_in_batches_mock.call_args
@@ -69,8 +75,8 @@ def test_export_products(
)
assert args[1:] == (
export_info,
- {"id", "name"},
- ["id", "name"],
+ {"id", "name", "variants__id", "variants__sku"},
+ ["id", "name", "variants__id", "variants__sku"],
";",
mock_file,
file_type,
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index 74f8710e58..8aa4bd1436 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -10,6 +10,7 @@ class ProductExportFields:
"product type": "product_type__name",
"charge taxes": "charge_taxes",
"product weight": "product_weight",
+ "variant id": "variants__id",
"variant sku": "variants__sku",
"variant weight": "variant_weight",
},
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 93af8fe536..d9f84dc1b6 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -32,12 +32,14 @@ def get_products_data(
"""
products_with_variants_data = []
+ export_variant_id = "variants__id" in export_fields
product_fields = set(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["fields"].values()
)
product_export_fields = export_fields & product_fields
- product_export_fields.add("variants__id")
+ if not export_variant_id:
+ product_export_fields.add("variants__id")
products_data = (
queryset.annotate(
@@ -71,7 +73,10 @@ def get_products_data(
for product_data in products_data:
pk = product_data["id"]
- variant_pk = product_data.pop("variants__id")
+ if export_variant_id:
+ variant_pk = product_data.get("variants__id")
+ else:
+ 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(
@@ -79,6 +84,11 @@ def get_products_data(
)
product_data["id"] = graphene.Node.to_global_id("Product", pk)
+ if export_variant_id:
+ product_data["variants__id"] = graphene.Node.to_global_id(
+ "ProductVariant", variant_pk
+ )
+
data = {**product_data, **product_relations_data, **variant_relations_data}
products_with_variants_data.append(data)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
index 5be15bc37a..de46a4f41a 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
@@ -88,7 +88,7 @@ def attributes_for_filtering_with_channels(
),
]
)
- variant = ProductVariant.objects.create(product=product)
+ variant = ProductVariant.objects.create(product=product, sku="TEST_SKU")
ProductVariantChannelListing.objects.create(
variant=variant,
channel=channel_USD,
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 193750344e..9ac37e5dbe 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -189,6 +189,35 @@ def test_checkout_create_with_default_channel(
)
+def test_checkout_create_with_variant_without_sku(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ variant = stock.product_variant
+ variant.sku = None
+ variant.save()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ quantity = 1
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": quantity, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ get_graphql_content(response)["data"]["checkoutCreate"]
+
+ new_checkout = Checkout.objects.first()
+ lines = fetch_checkout_lines(new_checkout)
+ assert new_checkout.channel == channel_USD
+ assert calculate_checkout_quantity(lines) == quantity
+ assert lines[0].variant.sku is None
+
+
def test_checkout_create_with_inactive_channel(
api_client, stock, graphql_address_data, channel_USD
):
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 083b37295f..f6f4ad2aee 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -477,6 +477,63 @@ def test_checkout_complete_gift_card_bought(
assert Fulfillment.objects.count() == 1
+def test_checkout_complete_with_variant_without_sku(
+ site_settings,
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ checkout = checkout_with_item
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.sku = None
+ checkout_line_variant.save()
+
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = calculations.calculate_checkout_total_with_gift_cards(
+ manager, checkout_info, lines, address
+ )
+ site_settings.automatically_confirm_all_new_orders = True
+ site_settings.save()
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ redirect_url = "https://www.example.com"
+ variables = {"token": checkout.token, "redirectUrl": redirect_url}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order_token = data["order"]["token"]
+ assert Order.objects.count() == orders_count + 1
+ order = Order.objects.get(token=order_token)
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.origin == OrderOrigin.CHECKOUT
+
+ order_line = order.lines.first()
+ assert order_line.product_sku is None
+ assert order_line.product_variant_id == order_line.variant.get_global_id()
+
+
def test_checkout_complete_with_variant_without_price(
site_settings,
user_api_client,
diff --git a/saleor/graphql/core/validators.py b/saleor/graphql/core/validators.py
index 1ff013657a..e031a94da8 100644
--- a/saleor/graphql/core/validators.py
+++ b/saleor/graphql/core/validators.py
@@ -62,7 +62,9 @@ def validate_variants_available_in_channel(
"""Validate available variants in specific channel."""
available_variants = ProductVariantChannelListing.objects.filter(
- variant__id__in=variants_id, channel_id=channel_id, price_amount__isnull=False
+ variant__id__in=variants_id,
+ channel_id=channel_id,
+ price_amount__isnull=False,
).values_list("variant_id", flat=True)
not_available_variants = variants_id - set(available_variants)
if not_available_variants:
diff --git a/saleor/graphql/csv/enums.py b/saleor/graphql/csv/enums.py
index 216b4ddad5..e0d09af9a8 100644
--- a/saleor/graphql/csv/enums.py
+++ b/saleor/graphql/csv/enums.py
@@ -34,6 +34,7 @@ class ProductFieldEnum(graphene.Enum):
COLLECTIONS = "collections"
CHARGE_TAXES = "charge taxes"
PRODUCT_MEDIA = "product media"
+ VARIANT_ID = "variant id"
VARIANT_SKU = "variant sku"
VARIANT_WEIGHT = "variant weight"
VARIANT_MEDIA = "variant media"
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 12f6975cfc..6facea264e 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -12,6 +12,7 @@ from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
from ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatus
from ....plugins.manager import get_plugins_manager
+from ....product.models import ProductVariant
from ....warehouse.models import Allocation, Stock
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -864,6 +865,70 @@ def test_order_fulfill_lines_with_empty_quantity(
)
[email protected]("fulfillment_auto_approve", [True, False])
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+def test_order_fulfill_without_sku(
+ mock_create_fulfillments,
+ fulfillment_auto_approve,
+ staff_api_client,
+ staff_user,
+ order_with_lines,
+ permission_manage_orders,
+ warehouse,
+ site_settings,
+):
+ ProductVariant.objects.update(sku=None)
+ site_settings.fulfillment_auto_approve = fulfillment_auto_approve
+ site_settings.save(update_fields=["fulfillment_auto_approve"])
+ order = order_with_lines
+ query = ORDER_FULFILL_QUERY
+ order.lines.update(product_sku=None)
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ order_line, order_line2 = order.lines.all()
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "order": order_id,
+ "input": {
+ "notifyCustomer": True,
+ "lines": [
+ {
+ "orderLineId": order_line_id,
+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
+ },
+ {
+ "orderLineId": order_line2_id,
+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],
+ },
+ ],
+ },
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfill"]
+ assert not data["errors"]
+
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ True,
+ allow_stock_to_be_exceeded=False,
+ approved=fulfillment_auto_approve,
+ )
+
+
@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill_zero_quantity(
mock_create_fulfillments,
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index 89a5715bf0..c6458595ae 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -759,6 +759,7 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index 580d843ed4..f9b5bbaf5c 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -831,6 +831,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index bcf571783f..95e41761b8 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -945,6 +945,64 @@ def test_order_confirm(
)
+@patch("saleor.plugins.manager.PluginsManager.notify")
+@patch("saleor.payment.gateway.capture")
+def test_order_confirm_without_sku(
+ capture_mock,
+ mocked_notify,
+ staff_api_client,
+ order_unconfirmed,
+ permission_manage_orders,
+ payment_txn_preauth,
+):
+ order_unconfirmed.lines.update(product_sku=None)
+ ProductVariant.objects.update(sku=None)
+
+ payment_txn_preauth.order = order_unconfirmed
+ payment_txn_preauth.save()
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ assert not OrderEvent.objects.exists()
+ response = staff_api_client.post_graphql(
+ ORDER_CONFIRM_MUTATION,
+ {"id": graphene.Node.to_global_id("Order", order_unconfirmed.id)},
+ )
+ order_data = get_graphql_content(response)["data"]["orderConfirm"]["order"]
+
+ assert order_data["status"] == OrderStatus.UNFULFILLED.upper()
+ order_unconfirmed.refresh_from_db()
+ assert order_unconfirmed.status == OrderStatus.UNFULFILLED
+ assert OrderEvent.objects.count() == 2
+ assert OrderEvent.objects.filter(
+ order=order_unconfirmed,
+ user=staff_api_client.user,
+ type=order_events.OrderEvents.CONFIRMED,
+ ).exists()
+
+ assert OrderEvent.objects.filter(
+ order=order_unconfirmed,
+ user=staff_api_client.user,
+ type=order_events.OrderEvents.PAYMENT_CAPTURED,
+ parameters__amount=payment_txn_preauth.get_total().amount,
+ ).exists()
+
+ capture_mock.assert_called_once_with(
+ payment_txn_preauth, ANY, channel_slug=order_unconfirmed.channel.slug
+ )
+ expected_payload = {
+ "order": get_default_order_payload(order_unconfirmed, ""),
+ "recipient_email": order_unconfirmed.user.email,
+ "requester_user_id": staff_api_client.user.id,
+ "requester_app_id": None,
+ "site_name": "mirumee.com",
+ "domain": "mirumee.com",
+ }
+ mocked_notify.assert_called_once_with(
+ NotifyEventType.ORDER_CONFIRMED,
+ expected_payload,
+ channel_slug=order_unconfirmed.channel.slug,
+ )
+
+
def test_order_confirm_unfulfilled(staff_api_client, order, permission_manage_orders):
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(
@@ -1731,6 +1789,93 @@ def test_draft_order_create_with_inactive_channel(
assert created_draft_event.parameters == {}
+def test_draft_order_create_without_sku(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ ProductVariant.objects.update(sku=None)
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
+ assert data["redirectUrl"] == redirect_url
+ assert (
+ data["billingAddress"]["streetAddress1"]
+ == graphql_address_data["streetAddress1"]
+ )
+ assert (
+ data["shippingAddress"]["streetAddress1"]
+ == graphql_address_data["streetAddress1"]
+ )
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ assert order.shipping_method == shipping_method
+ assert order.billing_address
+ assert order.shipping_address
+
+ order_line = order.lines.get(variant=variant)
+ assert order_line.product_sku is None
+ assert order_line.product_variant_id == variant.get_global_id()
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+
def test_draft_order_create_variant_with_0_price(
staff_api_client,
permission_manage_orders,
@@ -2707,6 +2852,21 @@ def test_can_finalize_order(staff_api_client, permission_manage_orders, draft_or
assert not content["data"]["order"]["errors"]
+def test_can_finalize_order_without_sku(
+ staff_api_client, permission_manage_orders, draft_order
+):
+ ProductVariant.objects.update(sku=None)
+ draft_order.lines.update(product_sku=None)
+
+ order_id = graphene.Node.to_global_id("Order", draft_order.id)
+ variables = {"id": order_id}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["order"]["canFinalize"] is True
+ assert not content["data"]["order"]["errors"]
+
+
def test_can_finalize_order_invalid_shipping_method_set(
staff_api_client, permission_manage_orders, draft_order
):
@@ -2810,6 +2970,13 @@ def test_validate_draft_order(draft_order):
assert validate_draft_order(draft_order, "US") is None
+def test_validate_draft_order_without_sku(draft_order):
+ ProductVariant.objects.update(sku=None)
+ draft_order.lines.update(product_sku=None)
+ # should not raise any errors
+ assert validate_draft_order(draft_order, "US") is None
+
+
def test_validate_draft_order_wrong_shipping(draft_order):
order = draft_order
shipping_zone = order.shipping_method.shipping_zone
@@ -3033,6 +3200,58 @@ def test_draft_order_complete(
)
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_draft_order_complete_without_sku(
+ product_variant_out_of_stock_webhook_mock,
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ draft_order,
+):
+ ProductVariant.objects.update(sku=None)
+ draft_order.lines.update(product_sku=None)
+
+ order = draft_order
+
+ # Ensure no events were created
+ assert not OrderEvent.objects.exists()
+
+ # Ensure no allocation were created
+ assert not Allocation.objects.filter(order_line__order=order).exists()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderComplete"]["order"]
+ order.refresh_from_db()
+ assert data["status"] == order.status.upper()
+ assert data["origin"] == OrderOrigin.DRAFT.upper()
+
+ for line in order.lines.all():
+ allocation = line.allocations.get()
+ assert allocation.quantity_allocated == line.quantity_unfulfilled
+
+ # ensure there are only 2 events with correct types
+ event_params = {
+ "user": staff_user,
+ "type__in": [
+ order_events.OrderEvents.PLACED_FROM_DRAFT,
+ order_events.OrderEvents.CONFIRMED,
+ ],
+ "parameters": {},
+ }
+ matching_events = OrderEvent.objects.filter(**event_params)
+ assert matching_events.count() == 2
+ assert matching_events[0].type != matching_events[1].type
+ assert not OrderEvent.objects.exclude(**event_params).exists()
+ product_variant_out_of_stock_webhook_mock.assert_called_once_with(
+ Stock.objects.last()
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
def test_draft_order_complete_with_out_of_stock_webhook(
product_variant_out_of_stock_webhook_mock,
@@ -3427,6 +3646,7 @@ ORDER_LINES_CREATE_MUTATION = """
id
quantity
productSku
+ productVariantId
}
order {
total {
@@ -3540,6 +3760,7 @@ def test_order_lines_create(
content = get_graphql_content(response)
data = content["data"]["orderLinesCreate"]
assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
assert data["orderLines"][0]["quantity"] == quantity
# mutation should fail when quantity is lower than 1
@@ -3623,6 +3844,7 @@ def test_order_lines_create_with_existing_variant(
content = get_graphql_content(response)
data = content["data"]["orderLinesCreate"]
assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
assert data["orderLines"][0]["quantity"] == old_quantity + quantity
assert_proper_webhook_called_once(
order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
@@ -3704,6 +3926,56 @@ def test_order_lines_create_with_variant_not_assigned_to_channel(
draft_order_update_webhook_mock.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+def test_order_lines_create_without_sku(
+ product_variant_out_of_stock_webhook_mock,
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+ variant_with_many_stocks,
+):
+ ProductVariant.objects.update(sku=None)
+ order_with_lines.lines.update(product_sku=None)
+
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ variant = variant_with_many_stocks
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ # mutation should fail without proper permissions
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+ assert not OrderEvent.objects.exists()
+
+ # assign permissions
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query, variables)
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] is None
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
+ assert data["orderLines"][0]["quantity"] == quantity
+
+ # mutation should fail when quantity is lower than 1
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": 0}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "quantity"
+ assert data["errors"][0]["variants"] == [variant_id]
+ product_variant_out_of_stock_webhook_mock.assert_not_called()
+
+
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
def test_invalid_order_when_creating_lines(
@@ -3946,6 +4218,63 @@ def test_order_line_update(
assert data["errors"][0]["field"] == "quantity"
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+def test_order_line_update_without_sku(
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+ staff_user,
+):
+ ProductVariant.objects.update(sku=None)
+
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ line = order.lines.first()
+ new_quantity = 1
+ removed_quantity = 2
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"lineId": line_id, "quantity": new_quantity}
+
+ # Ensure the line has the expected quantity
+ assert line.quantity == 3
+
+ # No event should exist yet
+ assert not OrderEvent.objects.exists()
+
+ # mutation should fail without proper permissions
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+
+ # assign permissions
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+ assert data["orderLine"]["quantity"] == new_quantity
+
+ removed_items_event = OrderEvent.objects.last() # type: OrderEvent
+ assert removed_items_event.type == order_events.OrderEvents.REMOVED_PRODUCTS
+ assert removed_items_event.user == staff_user
+ assert removed_items_event.parameters == {
+ "lines": [{"quantity": removed_quantity, "line_pk": line.pk, "item": str(line)}]
+ }
+
+ line.refresh_from_db()
+ assert line.product_sku
+ assert line.product_variant_id == line.variant.get_global_id()
+
+ # mutation should fail when quantity is lower than 1
+ variables = {"lineId": line_id, "quantity": 0}
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "quantity"
+
+
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
def test_invalid_order_when_updating_lines(
@@ -4271,6 +4600,45 @@ def test_order_update_with_draft_order(
order_updated_webhook_mock.assert_not_called()
+@patch("saleor.plugins.base_plugin.BasePlugin.order_updated")
+def test_order_update_without_sku(
+ plugin_mock,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ graphql_address_data,
+):
+ ProductVariant.objects.update(sku=None)
+ order_with_lines.lines.update(product_sku=None)
+
+ order = order_with_lines
+ order.user = None
+ order.save()
+ email = "[email protected]"
+ assert not order.user_email == email
+ assert not order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert not order.billing_address.last_name == graphql_address_data["lastName"]
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id, "email": email, "address": graphql_address_data}
+ response = staff_api_client.post_graphql(
+ ORDER_UPDATE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["orderUpdate"]["errors"]
+ data = content["data"]["orderUpdate"]["order"]
+ assert data["userEmail"] == email
+
+ order.refresh_from_db()
+ order.shipping_address.refresh_from_db()
+ order.billing_address.refresh_from_db()
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ assert order.billing_address.last_name == graphql_address_data["lastName"]
+ assert order.user_email == email
+ assert order.user is None
+ assert order.status == OrderStatus.UNFULFILLED
+ assert plugin_mock.called is True
+
+
def test_order_update_anonymous_user_no_user_email(
staff_api_client, order_with_lines, permission_manage_orders, graphql_address_data
):
@@ -5930,6 +6298,41 @@ def test_order_bulk_cancel_as_app(
assert mock_cancel_order.call_count == expected_count
+@patch("saleor.graphql.order.bulk_mutations.orders.cancel_order")
+def test_order_bulk_cancel_without_sku(
+ mock_cancel_order,
+ staff_api_client,
+ order_list,
+ fulfilled_order_with_all_cancelled_fulfillments,
+ permission_manage_orders,
+ address,
+):
+ ProductVariant.objects.update(sku=None)
+ OrderLine.objects.update(product_sku=None)
+
+ orders = order_list
+ orders.append(fulfilled_order_with_all_cancelled_fulfillments)
+ expected_count = sum(order.can_cancel() for order in orders)
+ variables = {
+ "ids": [graphene.Node.to_global_id("Order", order.id) for order in orders],
+ }
+ response = staff_api_client.post_graphql(
+ MUTATION_ORDER_BULK_CANCEL, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderBulkCancel"]
+ assert data["count"] == expected_count
+ assert not data["errors"]
+
+ calls = [
+ call(order=order, user=staff_api_client.user, app=None, manager=ANY)
+ for order in orders
+ ]
+
+ mock_cancel_order.assert_has_calls(calls, any_order=True)
+ mock_cancel_order.call_count == expected_count
+
+
def test_order_query_with_filter_channels_with_one_channel(
orders_query_with_filter,
staff_api_client,
@@ -6511,6 +6914,7 @@ def test_orders_query_with_filter_search(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=3,
@@ -6679,6 +7083,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
product_name=str(product),
variant_name=str(variants[0]),
product_sku=variants[0].sku,
+ product_variant_id=variants[0].get_global_id(),
is_shipping_required=variants[0].is_shipping_required(),
is_gift_card=variants[0].is_gift_card(),
quantity=quantity,
@@ -6694,6 +7099,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
product_name=str(product),
variant_name=str(variants[1]),
product_sku=variants[1].sku,
+ product_variant_id=variants[1].get_global_id(),
is_shipping_required=variants[1].is_shipping_required(),
is_gift_card=variants[1].is_gift_card(),
quantity=quantity,
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 5b0fa635e6..5df0031784 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -468,6 +468,7 @@ class OrderLine(CountableDjangoObjectType):
"product_name",
"variant_name",
"product_sku",
+ "product_variant_id",
"quantity",
"quantity_fulfilled",
"tax_rate",
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index 613bbb5259..73c41478a4 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -42,6 +42,7 @@ from ..mutations.products import (
)
from ..types import Product, ProductType, ProductVariant
from ..utils import (
+ clean_variant_sku,
create_stocks,
get_draft_order_lines_data_for_variants,
get_used_variants_attribute_values,
@@ -204,7 +205,7 @@ class ProductVariantBulkCreateInput(ProductVariantInput):
description="List of prices assigned to channels.",
required=False,
)
- sku = graphene.String(required=True, description="Stock keeping unit.")
+ sku = graphene.String(description="Stock keeping unit.")
class ProductVariantBulkCreate(BaseMutation):
@@ -271,6 +272,8 @@ class ProductVariantBulkCreate(BaseMutation):
if stocks:
cls.clean_stocks(stocks, errors, variant_index)
+ cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))
+
return cleaned_input
@classmethod
@@ -444,9 +447,10 @@ class ProductVariantBulkCreate(BaseMutation):
cleaned_inputs.append(cleaned_input if cleaned_input else None)
- if not variant_data.sku:
- continue
- cls.validate_duplicated_sku(variant_data.sku, index, sku_list, errors)
+ if cleaned_input["sku"]:
+ cls.validate_duplicated_sku(
+ cleaned_input["sku"], index, sku_list, errors
+ )
return cleaned_inputs
@classmethod
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index e0de0c2e16..52f91d62cd 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -60,6 +60,7 @@ from ..types import (
ProductVariant,
)
from ..utils import (
+ clean_variant_sku,
create_stocks,
get_draft_order_lines_data_for_variants,
get_used_attribute_values_for_variant,
@@ -884,6 +885,9 @@ class ProductVariantCreate(ModelMutation):
except ValidationError as exc:
raise ValidationError({"attributes": exc})
+ if "sku" in cleaned_input:
+ cleaned_input["sku"] = clean_variant_sku(cleaned_input.get("sku"))
+
return cleaned_input
@classmethod
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 524d800fe6..5f06438883 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -380,6 +380,7 @@ def test_delete_products(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -394,6 +395,7 @@ def test_delete_products(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -1068,6 +1070,7 @@ def test_delete_product_variants_in_draft_orders(
product_name=str(second_product),
variant_name=str(second_variant_in_draft),
product_sku=second_variant_in_draft.sku,
+ product_variant_id=second_variant_in_draft.get_global_id(),
is_shipping_required=second_variant_in_draft.is_shipping_required(),
is_gift_card=second_variant_in_draft.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -1090,6 +1093,7 @@ def test_delete_product_variants_in_draft_orders(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 0b2b55f9cb..73798d10c1 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -509,6 +509,84 @@ def test_product_query_by_id_as_app_without_channel_slug(
assert product_data["name"] == product.name
+def test_product_variants_without_sku_query_by_staff(
+ staff_api_client, product, channel_USD
+):
+ product.variants.update(sku=None)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {
+ "id": product_id,
+ "channel": channel_USD.slug,
+ }
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_BY_ID,
+ variables=variables,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+
+ assert product_data is not None
+ assert product_data["id"] == product_id
+
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert product_data["variants"] == [{"id": variant_id}]
+
+
+def test_product_only_with_variants_without_sku_query_by_customer(
+ user_api_client, product, channel_USD
+):
+ product.variants.update(sku=None)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {
+ "id": product_id,
+ "channel": channel_USD.slug,
+ }
+
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_BY_ID,
+ variables=variables,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+
+ assert product_data is not None
+ assert product_data["id"] == product_id
+
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert product_data["variants"] == [{"id": variant_id}]
+
+
+def test_product_only_with_variants_without_sku_query_by_anonymous(
+ api_client, product, channel_USD
+):
+ product.variants.update(sku=None)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {
+ "id": product_id,
+ "channel": channel_USD.slug,
+ }
+
+ response = api_client.post_graphql(
+ QUERY_PRODUCT_BY_ID,
+ variables=variables,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+
+ assert product_data is not None
+ assert product_data["id"] == product_id
+
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert product_data["variants"] == [{"id": variant_id}]
+
+
QUERY_COLLECTION_FROM_PRODUCT = """
query ($id: ID, $channel:String){
product(
@@ -7174,6 +7252,7 @@ def test_delete_product_variant_in_draft_order(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -7188,6 +7267,7 @@ def test_delete_product_variant_in_draft_order(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -8426,6 +8506,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
@@ -8439,6 +8520,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
diff --git a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
index e3b9fa71b7..d8f1337cf3 100644
--- a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
+++ b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
@@ -554,3 +554,27 @@ def test_products_with_filtering_and_not_existing_channel(
content = get_graphql_content(response)
products_nodes = content["data"]["products"]["edges"]
assert len(products_nodes) == 0
+
+
+def test_published_products_without_sku_as_staff(
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ ProductVariant.objects.update(sku=None)
+ variables = {"filter": {"isPublished": True}, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert len(products_nodes) == 3
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 697c93798e..6084fc8e4d 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -1549,6 +1549,116 @@ def test_create_variant_with_date_time_attribute(
created_webhook_mock.assert_called_once_with(variant)
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_create_variant_with_empty_string_for_sku(
+ updated_webhook_mock,
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+):
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = ""
+ weight = 10.22
+ variant_slug = product_type.variant_attributes.first().slug
+ variant_id = graphene.Node.to_global_id(
+ "Attribute", product_type.variant_attributes.first().pk
+ )
+ variant_value = "test-value"
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "productId": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "weight": weight,
+ "attributes": [{"id": variant_id, "values": [variant_value]}],
+ "trackInventory": True,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+
+ assert not content["errors"]
+ data = content["productVariant"]
+ assert data["name"] == variant_value
+ assert data["sku"] is None
+ assert data["attributes"][0]["attribute"]["slug"] == variant_slug
+ assert data["attributes"][0]["values"][0]["slug"] == variant_value
+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
+ assert data["weight"]["value"] == weight
+ assert len(data["stocks"]) == 1
+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+ updated_webhook_mock.assert_not_called()
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_create_variant_without_sku(
+ updated_webhook_mock,
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+):
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ weight = 10.22
+ variant_slug = product_type.variant_attributes.first().slug
+ variant_id = graphene.Node.to_global_id(
+ "Attribute", product_type.variant_attributes.first().pk
+ )
+ variant_value = "test-value"
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "productId": product_id,
+ "stocks": stocks,
+ "weight": weight,
+ "attributes": [{"id": variant_id, "values": [variant_value]}],
+ "trackInventory": True,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+
+ assert not content["errors"]
+ data = content["productVariant"]
+ assert data["name"] == variant_value
+ assert data["sku"] is None
+ assert data["attributes"][0]["attribute"]["slug"] == variant_slug
+ assert data["attributes"][0]["values"][0]["slug"] == variant_value
+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
+ assert data["weight"]["value"] == weight
+ assert len(data["stocks"]) == 1
+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+ updated_webhook_mock.assert_not_called()
+
+
def test_product_variant_update_with_new_attributes(
staff_api_client, permission_manage_products, product, size_attribute
):
@@ -1725,6 +1835,93 @@ def test_update_product_variant_with_negative_weight(
assert error["code"] == ProductErrorCode.INVALID.name
+QUERY_UPDATE_VARIANT_SKU = """
+ mutation updateVariant (
+ $id: ID!,
+ $sku: String
+ ) {
+ productVariantUpdate(
+ id: $id,
+ input: {
+ sku: $sku
+ }
+ ){
+ productVariant {
+ sku
+ }
+ errors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+def test_update_product_variant_change_sku(
+ staff_api_client, product, permission_manage_products
+):
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "sku": "n3wSKU"}
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_SKU, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantUpdate"]["productVariant"]
+ assert data["sku"] == "n3wSKU"
+ variant.refresh_from_db()
+ assert variant.sku == "n3wSKU"
+
+
+def test_update_product_variant_without_sku_keep_it_empty(
+ staff_api_client, product, permission_manage_products
+):
+ variant = product.variants.first()
+ variant.sku = None
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "sku": ""}
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_SKU, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantUpdate"]
+ assert data["productVariant"]["sku"] is None
+ assert not data["errors"]
+ variant.refresh_from_db()
+ assert variant.sku is None
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_update_product_variant_change_sku_to_empty_string(
+ product_variant_updated_webhook_mock,
+ product_variant_created_webhook_mock,
+ staff_api_client,
+ product,
+ permission_manage_products,
+):
+ variant = product.variants.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "sku": ""}
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_SKU, variables, permissions=[permission_manage_products]
+ )
+ variant.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantUpdate"]["productVariant"]
+
+ assert data["sku"] is None
+ product_variant_updated_webhook_mock.assert_called_once_with(
+ product.variants.last()
+ )
+ product_variant_created_webhook_mock.assert_not_called()
+
+
QUERY_UPDATE_VARIANT_ATTRIBUTES = """
mutation updateVariant (
$id: ID!,
@@ -2850,6 +3047,7 @@ def test_delete_variant_in_draft_order(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=unit_price,
@@ -2866,6 +3064,7 @@ def test_delete_variant_in_draft_order(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=unit_price,
@@ -3099,8 +3298,70 @@ def test_fetch_all_variants_anonymous_user(
assert data["totalCount"] == 0
+def test_fetch_all_variants_without_sku_staff_user(
+ staff_api_client, product, permission_manage_products
+):
+ variant = product.variants.first()
+ variant.sku = None
+ variant.save()
+
+ data = _fetch_all_variants(
+ staff_api_client, permissions=[permission_manage_products]
+ )
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert data["totalCount"] == 1
+ assert data["edges"][0]["node"]["id"] == variant_id
+
+
+def test_fetch_all_variants_without_sku_staff_user_with_channel(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ channel_USD,
+):
+ variant = product.variants.first()
+ variant.sku = None
+ variant.save()
+
+ variables = {"channel": channel_USD.slug}
+ data = _fetch_all_variants(
+ staff_api_client, variables, permissions=[permission_manage_products]
+ )
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert data["totalCount"] == 1
+ assert data["edges"][0]["node"]["id"] == variant_id
+
+
+def test_fetch_all_variants_without_sku_as_customer_with_channel(
+ user_api_client, product, channel_USD
+):
+ variant = product.variants.first()
+ variant.sku = None
+ variant.save()
+
+ ProductVariant.objects.update(sku=None)
+ data = _fetch_all_variants(user_api_client, variables={"channel": channel_USD.slug})
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert data["totalCount"] == 1
+ assert data["edges"][0]["node"]["id"] == variant_id
+
+
+def test_fetch_all_variants_without_sku_as_anonymous_user_with_channel(
+ api_client, product, channel_USD
+):
+ variant = product.variants.first()
+ variant.sku = None
+ variant.save()
+
+ ProductVariant.objects.update(sku=None)
+ data = _fetch_all_variants(api_client, variables={"channel": channel_USD.slug})
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ assert data["totalCount"] == 1
+ assert data["edges"][0]["node"]["id"] == variant_id
+
+
QUERY_PRODUCT_VARIANTS_BY_IDS = """
- query getProduct($ids: [ID!], $channel: String) {
+ query getProductVariants($ids: [ID!], $channel: String) {
productVariants(ids: $ids, first: 1, channel: $channel) {
edges {
node {
@@ -3284,6 +3545,61 @@ def test_fetch_unpublished_variant_anonymous_user(
assert data is None
+def test_fetch_variant_without_sku_staff_user(
+ staff_api_client, product, variant, permission_manage_products
+):
+ variant.sku = None
+ variant.save()
+
+ data = _fetch_variant(
+ staff_api_client,
+ variant,
+ permissions=[permission_manage_products],
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ assert data["id"] == variant_id
+ assert data["product"]["id"] == product_id
+
+
+def test_fetch_variant_without_sku_customer(
+ user_api_client, product, variant, channel_USD
+):
+ variant.sku = None
+ variant.save()
+
+ data = _fetch_variant(
+ user_api_client,
+ variant,
+ channel_slug=channel_USD.slug,
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ assert data["id"] == variant_id
+ assert data["product"]["id"] == product_id
+
+
+def test_fetch_variant_without_sku_anonymous(api_client, product, variant, channel_USD):
+ variant.sku = None
+ variant.save()
+
+ data = _fetch_variant(
+ api_client,
+ variant,
+ channel_slug=channel_USD.slug,
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ assert data["id"] == variant_id
+ assert data["product"]["id"] == product_id
+
+
PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
mutation ProductVariantBulkCreate(
$variants: [ProductVariantBulkCreateInput]!, $productId: ID!
@@ -4028,6 +4344,39 @@ def test_product_variant_bulk_create_duplicated_sku_in_input(
assert product_variant_count == ProductVariant.objects.count()
+def test_product_variant_bulk_create_without_sku(
+ staff_api_client, product, size_attribute, permission_manage_products
+):
+ product_variant_count = ProductVariant.objects.count()
+ attribute_value_count = size_attribute.values.count()
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ attribute_value = size_attribute.values.last()
+ variants = [
+ {
+ "sku": " ",
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ {
+ "sku": None,
+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert not data["errors"]
+ assert data["count"] == 2
+ assert product_variant_count + 2 == ProductVariant.objects.count()
+ assert attribute_value_count + 1 == size_attribute.values.count()
+ assert ProductVariant.objects.filter(sku__isnull=True).count() == 2
+
+
def test_product_variant_bulk_create_many_errors(
staff_api_client, product, size_attribute, permission_manage_products
):
diff --git a/saleor/graphql/product/tests/test_variant_query.py b/saleor/graphql/product/tests/test_variant_query.py
index cf475078a0..13f57a1c7f 100644
--- a/saleor/graphql/product/tests/test_variant_query.py
+++ b/saleor/graphql/product/tests/test_variant_query.py
@@ -14,6 +14,7 @@ query variant(
$id: ID, $sku: String, $variantSelection: VariantAttributeScope, $channel: String
){
productVariant(id:$id, sku:$sku, channel: $channel){
+ id
sku
attributes(variantSelection: $variantSelection) {
attribute {
@@ -223,6 +224,100 @@ def test_get_variant_by_id_as_anonymous_user(api_client, variant, channel_USD):
assert data["sku"] == variant.sku
+def test_get_variant_without_sku_by_id_as_staff(
+ staff_api_client, permission_manage_products, variant
+):
+ # given
+ variant.sku = None
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ VARIANT_QUERY,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert data["id"] == variant_id
+
+
+def test_get_variant_without_sku_by_id_as_app(
+ app_api_client, permission_manage_products, variant
+):
+ # given
+ variant.sku = None
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ VARIANT_QUERY,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert data["id"] == variant_id
+
+
+def test_get_variant_without_sku_by_id_as_customer(
+ user_api_client, variant, channel_USD
+):
+ # given
+ variant.sku = None
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = user_api_client.post_graphql(
+ VARIANT_QUERY,
+ variables,
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert data["id"] == variant_id
+
+
+def test_get_variant_without_sku_by_id_as_anonymous_user(
+ api_client, variant, channel_USD
+):
+ # given
+ variant.sku = None
+ variant.save()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(
+ VARIANT_QUERY,
+ variables,
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert data["id"] == variant_id
+
+
def test_get_unpublished_variant_by_sku_as_staff(
staff_api_client, permission_manage_products, unavailable_product_with_variant
):
diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.py
index d33accbccb..b06db192c3 100644
--- a/saleor/graphql/product/tests/test_variant_with_filtering.py
+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py
@@ -51,6 +51,12 @@ def products_for_variant_filtering(product_type, category):
category=category,
product_type=product_type,
),
+ Product(
+ name="ProductNoSku",
+ slug="prod4",
+ category=category,
+ product_type=product_type,
+ ),
]
)
ProductVariant.objects.bulk_create(
@@ -73,6 +79,13 @@ def products_for_variant_filtering(product_type, category):
product=products[4],
sku="P3-V1",
),
+ ProductVariant(
+ product=products[5],
+ sku="P-NO-SKU",
+ ),
+ ProductVariant(
+ product=products[5],
+ ),
]
)
return products
@@ -87,7 +100,8 @@ def products_for_variant_filtering(product_type, category):
({"search": "XXL"}, ["PP2-V1"]),
({"search": "PP2-V1"}, ["PP2-V1"]),
({"search": "P1"}, ["P1-V1", "P1-V2", "PP1-V1"]),
- ({"search": ["invalid"]}, []),
+ ({"search": "invalid"}, []),
+ ({"search": "ProductNoSku"}, ["P-NO-SKU", None]),
({"sku": ["P1"]}, []),
({"sku": ["P1-V1", "P1-V2", "PP1-V1"]}, ["P1-V1", "P1-V2", "PP1-V1"]),
({"sku": ["PP1-V1", "PP2-V1"]}, ["PP1-V1", "PP2-V1"]),
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 75a145706b..f55ebc40ab 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,5 +1,5 @@
from collections import defaultdict, namedtuple
-from typing import TYPE_CHECKING, Dict, Iterable, List
+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
import graphene
from django.core.exceptions import ValidationError
@@ -105,3 +105,9 @@ def get_draft_order_lines_data_for_variants(
order_pks.add(line.order_id)
return DraftOrderLinesData(order_to_lines_mapping, line_pks, order_pks)
+
+
+def clean_variant_sku(sku: Optional[str]) -> Optional[str]:
+ if sku:
+ return sku.strip() or None
+ return None
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 62484be8e7..86cd381546 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4356,7 +4356,8 @@ type OrderLine implements Node {
id: ID!
productName: String!
variantName: String!
- productSku: String!
+ productSku: String
+ productVariantId: String
isShippingRequired: Boolean!
quantity: Int!
quantityFulfilled: Int!
@@ -5320,6 +5321,7 @@ enum ProductFieldEnum {
COLLECTIONS
CHARGE_TAXES
PRODUCT_MEDIA
+ VARIANT_ID
VARIANT_SKU
VARIANT_WEIGHT
VARIANT_MEDIA
@@ -5607,7 +5609,7 @@ type ProductUpdate {
type ProductVariant implements Node & ObjectWithMetadata {
id: ID!
name: String!
- sku: String!
+ sku: String
product: Product!
trackInventory: Boolean!
weight: Weight
@@ -5637,7 +5639,7 @@ type ProductVariantBulkCreate {
input ProductVariantBulkCreateInput {
attributes: [BulkAttributeValueInput!]!
- sku: String!
+ sku: String
trackInventory: Boolean
weight: WeightScalar
stocks: [StockInput!]
diff --git a/saleor/order/migrations/0120_orderline_optional_sku.py b/saleor/order/migrations/0120_orderline_optional_sku.py
new file mode 100644
index 0000000000..ab44ee2112
--- /dev/null
+++ b/saleor/order/migrations/0120_orderline_optional_sku.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.6 on 2021-08-26 15:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0119_orderline_is_gift_card"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderline",
+ name="product_sku",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="product_variant_id",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index dce6343c4f..d011181f9c 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -418,7 +418,9 @@ class OrderLine(models.Model):
variant_name = models.CharField(max_length=255, default="", blank=True)
translated_product_name = models.CharField(max_length=386, default="", blank=True)
translated_variant_name = models.CharField(max_length=255, default="", blank=True)
- product_sku = models.CharField(max_length=255)
+ product_sku = models.CharField(max_length=255, null=True, blank=True)
+ # str with GraphQL ID used as fallback when product SKU is not available
+ product_variant_id = models.CharField(max_length=255, null=True, blank=True)
is_shipping_required = models.BooleanField()
is_gift_card = models.BooleanField()
quantity = models.IntegerField(validators=[MinValueValidator(1)])
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index d9749dc865..ebe000087f 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -106,6 +106,7 @@ def get_order_line_payload(line: "OrderLine"):
"variant": variant_dependent_fields.get("variant"), # type: ignore
"translated_variant_name": line.translated_variant_name or line.variant_name,
"product_sku": line.product_sku,
+ "product_variant_id": line.product_variant_id,
"quantity": line.quantity,
"quantity_fulfilled": line.quantity_fulfilled,
"currency": line.currency,
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index a39647d799..9bc8adaef4 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -140,6 +140,7 @@ def test_get_order_line_payload(order_line):
"product_name": order_line.product_name,
"variant_name": order_line.variant_name,
"product_sku": order_line.product_sku,
+ "product_variant_id": order_line.product_variant_id,
"is_shipping_required": order_line.is_shipping_required,
"quantity": order_line.quantity,
"quantity_fulfilled": order_line.quantity_fulfilled,
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 55c5ca7ee9..33258198a0 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -89,6 +89,7 @@ def test_add_variant_to_order_adds_line_for_new_variant(
line = order.lines.last()
assert order.lines.count() == lines_before + 1
assert line.product_sku == variant.sku
+ assert line.product_variant_id == variant.get_global_id()
assert line.quantity == 1
assert line.unit_price == TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))
assert line.translated_product_name == str(variant.product.translated)
@@ -118,6 +119,7 @@ def test_add_variant_to_draft_order_adds_line_for_new_variant_with_tax(
line = order.lines.last()
assert order.lines.count() == lines_before + 1
assert line.product_sku == variant.sku
+ assert line.product_variant_id == variant.get_global_id()
assert line.quantity == 1
assert line.unit_price == unit_price
assert line.total_price == total_price
@@ -144,6 +146,7 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
line = order.lines.last()
assert order.lines.count() == lines_before + 1
assert line.product_sku == variant.sku
+ assert line.product_variant_id == variant.get_global_id()
assert line.quantity == 1
assert line.unit_price == TaxedMoney(net=Money(0, "USD"), gross=Money(0, "USD"))
assert line.translated_product_name == str(variant.product.translated)
@@ -189,6 +192,7 @@ def test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines,
existing_line.refresh_from_db()
assert order_with_lines.lines.count() == lines_before
assert existing_line.product_sku == variant.sku
+ assert existing_line.product_variant_id == variant.get_global_id()
assert existing_line.quantity == line_quantity_before + 1
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 1348c42d95..4f377725c1 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -54,6 +54,7 @@ def order_with_digital_line(order, digital_content, stock, site_settings):
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index 1f136ff1c7..bf68554073 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -350,6 +350,7 @@ def test_create_return_fulfillment_only_order_lines_with_replace_request(
assert replaced_line.product_name == expected_replaced_line.product_name
assert replaced_line.variant_name == expected_replaced_line.variant_name
assert replaced_line.product_sku == expected_replaced_line.product_sku
+ assert replaced_line.product_variant_id == expected_replaced_line.product_variant_id
assert (
replaced_line.is_shipping_required
== expected_replaced_line.is_shipping_required
@@ -504,6 +505,7 @@ def test_create_return_fulfillment_only_fulfillment_lines_replace_order(
assert replaced_line.product_name == expected_replaced_line.product_name
assert replaced_line.variant_name == expected_replaced_line.variant_name
assert replaced_line.product_sku == expected_replaced_line.product_sku
+ assert replaced_line.product_variant_id == expected_replaced_line.product_variant_id
assert (
replaced_line.is_shipping_required
== expected_replaced_line.is_shipping_required
@@ -556,6 +558,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index dd255641e2..e2814e0a1a 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -357,6 +357,7 @@ def add_variant_to_order(
translated_product_name=translated_product_name,
translated_variant_name=translated_variant_name,
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
index 5e5760cec5..dfada597e2 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -80,6 +80,56 @@ def test_append_checkout_details(
}
+def test_append_checkout_details_without_sku(
+ dummy_payment_data, payment_dummy, checkout_ready_to_complete
+):
+ # given
+ checkout_ready_to_complete.payments.add(payment_dummy)
+ channel_id = checkout_ready_to_complete.channel_id
+ line = checkout_ready_to_complete.lines.first()
+ line.variant.sku = None
+ line.variant.save()
+ payment_data = {
+ "reference": "test",
+ }
+ country_code = checkout_ready_to_complete.get_country()
+
+ # when
+ result = append_checkout_details(dummy_payment_data, payment_data)
+
+ # then
+ variant_channel_listing = line.variant.channel_listings.get(channel_id=channel_id)
+ variant_price = variant_channel_listing.price_amount
+ variant_currency = variant_channel_listing.currency
+ price = price_to_minor_unit(variant_price, variant_currency)
+
+ assert result == {
+ "reference": "test",
+ "shopperLocale": get_shopper_locale_value(country_code),
+ "countryCode": country_code,
+ "lineItems": [
+ {
+ "description": f"{line.variant.product.name}, {line.variant.name}",
+ "quantity": line.quantity,
+ "id": line.variant.get_global_id(),
+ "taxAmount": "0",
+ "taxPercentage": 0,
+ "amountExcludingTax": price,
+ "amountIncludingTax": price,
+ },
+ {
+ "amountExcludingTax": "1000",
+ "amountIncludingTax": "1000",
+ "description": "Shipping - DHL",
+ "id": f"Shipping:{checkout_ready_to_complete.shipping_method.id}",
+ "quantity": 1,
+ "taxAmount": "0",
+ "taxPercentage": 0,
+ },
+ ],
+ }
+
+
@mock.patch("saleor.payment.gateways.adyen.utils.common.get_plugins_manager")
@mock.patch("saleor.payment.gateways.adyen.utils.common.checkout_line_total")
def test_append_checkout_details_tax_included(
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index b62cb0e234..dc6c15664b 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -269,7 +269,7 @@ def append_checkout_details(payment_information: "PaymentData", payment_data: di
"description": (
f"{line_info.variant.product.name}, {line_info.variant.name}"
),
- "id": line_info.variant.sku,
+ "id": line_info.variant.sku or line_info.variant.get_global_id(),
"taxAmount": price_to_minor_unit(tax_amount, currency),
"amountIncludingTax": price_to_minor_unit(unit_gross, currency),
}
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index ddca7b56b9..4aeb5379e5 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -251,6 +251,7 @@ def get_checkout_lines_data(
product = line_info.product
name = product.name
product_type = line_info.product_type
+ item_code = line_info.variant.sku or line_info.variant.get_global_id()
tax_code = retrieve_tax_code_from_meta(product, default=None)
tax_code = tax_code or retrieve_tax_code_from_meta(product_type)
append_line_to_data(
@@ -262,7 +263,7 @@ def get_checkout_lines_data(
discounts,
).gross.amount,
tax_code=tax_code,
- item_code=line_info.variant.sku,
+ item_code=item_code,
name=name,
)
@@ -298,13 +299,12 @@ def get_order_lines_data(
line.unit_price_gross_amount != line.unit_price_net_amount
)
tax_included = line_has_included_taxes or system_tax_included
-
append_line_to_data(
data=data,
quantity=line.quantity,
amount=line.unit_price_gross_amount * line.quantity,
tax_code=tax_code,
- item_code=line.variant.sku,
+ item_code=line.variant.sku or line.variant.get_global_id(),
name=line.variant.product.name,
tax_included=tax_included,
)
@@ -336,7 +336,6 @@ def generate_request_data(
config: AvataxConfiguration,
currency: str,
):
-
data = {
"companyCode": config.company_name,
"type": transaction_type,
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 6f7692d7de..fe17f23ad5 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -370,8 +370,11 @@ class AvataxPlugin(BasePlugin):
return base_total
taxes_data = get_checkout_tax_data(checkout_info, lines, discounts, self.config)
+ variant = checkout_line_info.variant
return self._calculate_line_total_price(
- taxes_data, checkout_line_info.variant.sku, previous_value
+ taxes_data,
+ variant.sku or variant.get_global_id(),
+ previous_value,
)
def calculate_order_line_total(
@@ -392,7 +395,11 @@ class AvataxPlugin(BasePlugin):
return zero_taxed_money(order.total.currency)
taxes_data = self._get_order_tax_data(order, previous_value)
- return self._calculate_line_total_price(taxes_data, variant.sku, previous_value)
+ return self._calculate_line_total_price(
+ taxes_data,
+ variant.sku or variant.get_global_id(),
+ previous_value,
+ )
@staticmethod
def _calculate_line_total_price(
@@ -435,10 +442,11 @@ class AvataxPlugin(BasePlugin):
taxes_data = self._get_checkout_tax_data(
checkout_info, lines, discounts, previous_value
)
+ variant = checkout_line_info.variant
return self._calculate_unit_price(
taxes_data,
checkout_line_info.line,
- checkout_line_info.variant.sku,
+ variant.sku or variant.get_global_id(),
previous_value,
)
@@ -454,7 +462,10 @@ class AvataxPlugin(BasePlugin):
return previous_value
taxes_data = self._get_order_tax_data(order, previous_value)
return self._calculate_unit_price(
- taxes_data, order_line, variant.sku, previous_value
+ taxes_data,
+ order_line,
+ variant.sku or variant.get_global_id(),
+ previous_value,
)
@staticmethod
@@ -542,8 +553,11 @@ class AvataxPlugin(BasePlugin):
response = self._get_checkout_tax_data(
checkout_info, lines, discounts, previous_value
)
+ variant = checkout_line_info.variant
return self._get_unit_tax_rate(
- response, checkout_line_info.variant.sku, previous_value
+ response,
+ variant.sku or variant.get_global_id(),
+ previous_value,
)
def get_order_line_tax_rate(
@@ -557,7 +571,11 @@ class AvataxPlugin(BasePlugin):
if not product.charge_taxes:
return previous_value
response = self._get_order_tax_data(order, previous_value)
- return self._get_unit_tax_rate(response, variant.sku, previous_value)
+ return self._get_unit_tax_rate(
+ response,
+ variant.sku or variant.get_global_id(),
+ previous_value,
+ )
def get_checkout_shipping_tax_rate(
self,
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-24.39-30.00-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-24.39-30.00-True].yaml
new file mode 100644
index 0000000000..0209a036aa
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-24.39-30.00-True].yaml
@@ -0,0 +1,77 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "UHJvZHVjdFZhcmlhbnQ6Mg", "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR020100", "taxIncluded": true,
+ "itemCode": "Shipping", "description": null}], "code": "2194be97-150f-4689-ab4b-fe582004bcde",
+ "date": "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1":
+ "Teczowa 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL",
+ "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "",
+ "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},
+ "commit": false, "currencyCode": "USD", "email": ""}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '776'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: !!binary |
+ C88HAICqqqrq/3QNkLOZgdrmi928PNIho8DT3dPdPBMgCvwgpirmppFqqlaqoh5uVRC+76T9NBtY
+ y40DrE+bLbKysnKyMnLbDbB28uQkQiKM5B42NfUwRnqaqWfyO/+DVtCIBKRTBA0U+brqaL1M81r0
+ abVYrVPsqi7tqV4VQlSdVAQaODVOaOc3BU1RFetlnYBCNkKnRJGnYpWWOSQw4TyS5Vf28OnAyDFA
+ Ay2Nk/PoZ0iA58kOzlzQUDh6R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TbuZqhiK8E2t7BivNuD4Be7WXQ06QtXg3UVZaXcPXC8vMhNc9WyzOU7jDu6YtJWvPvdmdRiFyI
+ qQjCkPmp1XJVqdO/GK2m1K7ei6kI0swCSn8WrJIXIyxJ5ynoPRZYpdAndPlOrNLY9mBVknggrLLd
+ ucpuyyZm5SmEhewNpXPxScI87+lBOyLmdz3VEA2ypXUF/mjwM/zBl3w4IYxcAKaSfFp5QpZ6x4GD
+ 3+fjdr/5XWkYPfTsIYHJBUYz0nDQQF2mubgBW5tBZXye9UjG/k4h6lwUCRhkzVGXWkjAOHsn9fuh
+ +DNB+Zbkf+4TX5aGsT+mxjtp8PNcnxdiiSXdLKzZdMLXxtTeEghxHP/YQbbnrRRtLE72sSVBh9m2
+ d7NyNNXxAYuiunbYaXfqNveNtG3c3qj2I4bBYvOGHRCg0DT9UxJJeYjX+5Yt/1mFjRcjMRZrm2hm
+ kSyRfKSdhUZk4uv2NQ==
+ headers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 31 Aug 2021 10:39:46 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/0
+ Server:
+ - Kestrel
+ ServerDuration:
+ - '00:00:00.0162823'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-30.00-36.90-False].yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-30.00-36.90-False].yaml
new file mode 100644
index 0000000000..af7debfe70
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[False-30.00-36.90-False].yaml
@@ -0,0 +1,77 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ false, "itemCode": "UHJvZHVjdFZhcmlhbnQ6Mg", "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR020100", "taxIncluded": false,
+ "itemCode": "Shipping", "description": null}], "code": "2482942f-12af-473f-a6af-071e2c2c3ba3",
+ "date": "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1":
+ "Teczowa 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL",
+ "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "",
+ "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},
+ "commit": false, "currencyCode": "USD", "email": ""}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '778'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: !!binary |
+ C8YHAICqqqrq/3QNkLOag5qauXu43bw80iGjwNPdM9w8EyAK/CCuKuamkWqqVqqiHm5VEL7vJP2y
+ kiulfem1o1yyE0FDQ8NAQ8Ekl3aUGh4MHIADBO7edK7Kx3OT4VKgVvbv/A/WQCMF6GAIGlD1s1rV
+ qitKhV1RL6uuwAV2hVyWpLTS1RUr8MClYUQ/vRpoVK1Wy7kAgxyELklVFvK5qEoQMOI0kOcX9fTl
+ xMg5QQMtDWOIGCcQwNMYB1dO6CgdoqEIAq7Iut+cMPRAgM4xkteTlK+cTy8ggB66R3+jN2TaGH3w
+ ROfEYaB4Tnijdqcgvs6z5emcKCIbWN+aX+RNiDo2qXzbij09aBh5H8Cb/iSSDl5bRwaaDl0iAS5o
+ ZBu8HxsYwo0hsvW3nXrKjTnqHhMlT5vAuaOcsT2lpQqhjhRT7HfPOTC69RCyZ2hqOZNitm/HpAyN
+ 9FZfbNKmYSN3LT6gWc2UI7ctPvDqKNj7XouPDT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 3fp3n2H0vrMHAWNIjO4+w0ED86oo5Q44Gggq4+PNj+TOP1FyXkolwCFbzr7UggAX/E00nufh7yTl
+ W9L/hU98WgbG+ZyaGLTDz3V/XsjJldJAYc2AE342p/YiIOVh+CcHGZmPSnQwL9nHcIR0k22zNydN
+ KrW+Xmqa5g07jkzD4aARx4zHg9R5ujCYaD5xggASL81/jsRQHuH9lGWrv1J08FaofDOqiV+WYnDk
+ ng0eGjmTX5evAQ==
+ headers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 31 Aug 2021 10:39:47 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/0
+ Server:
+ - Kestrel
+ ServerDuration:
+ - '00:00:00.0192459'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-12.20-15.00-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-12.20-15.00-True].yaml
new file mode 100644
index 0000000000..87314fc105
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-12.20-15.00-True].yaml
@@ -0,0 +1,77 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "UHJvZHVjdFZhcmlhbnQ6Mg", "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR020100", "taxIncluded": true,
+ "itemCode": "Shipping", "description": null}], "code": "8a104357-dc1f-47b6-9458-e48d0d2545b5",
+ "date": "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1":
+ "Teczowa 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL",
+ "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "",
+ "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},
+ "commit": false, "currencyCode": "USD", "email": ""}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '776'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: !!binary |
+ C8oHAICqqqrq/3QNkLOagdoWbm43L490yCjwdPcMN88EiAI/iKuKu2mkmqqVqqiHWxWE7ztJv6yk
+ o7SX3jrKZSsRNDQ0DDQUTHJpR6nhwcABOEDg7k3nCn08l0wABUrl/s7/YDR0UoDymqCDFgtZV80i
+ 06q4ZvXi8pwt66bNqG611GVTN5cGLHBpnNDNrxq6si6Xi0aARnaCa6Usi0y2WVWAgAnnkRy/iKcv
+ R0ZOETroaZx8wDCDAJ4nP7hyREtxHzQFEHBBVsP6hqEHAlQKgZyad/nK6fgCAuihBnQ3ekOmtdIH
+ T1SK7EcKp4g36k8KYuscG55PkTyygfZb84uc9kHGJoU/ttueHjROvPNgTX8SSHmnjCUN3RVtJAHW
+ K2TjnR0bKMJNPrBxt614yk0pqAEjBU8bx/lKMWN7S4sZQp0oRN/vLrBntKvRJ8fQlTKvqn22b/ek
+ FTqZy12uLyYq3bDZ9z0+oKvz54Uetz0+8GLJ3U2vx8carUoWOU5YbUIN6o8UudLovxFG76CDneeV
+ hCppEHmA/TGBpmW9U4hGFVbkEJvS+W/XKyk2dwLMBzvlAl0RDhoa0VjIK7nRa3M1pK2nrvSF7Kpl
+ Vzd5IxdFK8t3sHirp0gBw9Rpq2JZCmB8OJmSEFrjKEL3T7OMLQd0EVVpIS5MqgW/S+OFAnQAfXwT
+ 4lpNUQUzOURsh07kpyl4nRQrQItlq9JyLFnC3aPtuqbAl+KkN8OoMfGVaazq2OGQSIBh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ers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 31 Aug 2021 10:39:45 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/0
+ Server:
+ - Kestrel
+ ServerDuration:
+ - '00:00:00.0178705'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-15.00-18.45-False].yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-15.00-18.45-False].yaml
new file mode 100644
index 0000000000..29fb92aabb
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_without_sku_total[True-15.00-18.45-False].yaml
@@ -0,0 +1,77 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
+ false, "itemCode": "UHJvZHVjdFZhcmlhbnQ6Mg", "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR020100", "taxIncluded": false,
+ "itemCode": "Shipping", "description": null}], "code": "cf258f7c-5bbc-4b7f-8779-d4ab01d5be93",
+ "date": "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1":
+ "Teczowa 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL",
+ "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "",
+ "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},
+ "commit": false, "currencyCode": "USD", "email": ""}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '778'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.av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N/
+ NCnlMgf2LM47nPn+EBquDTVyVpRSooivopDCL4fEY+pFNIyPc2o1kIoXOICYUh72zOg0Bv3Evoha
+ u07c+2B4chsS5DvoygHFcB1LCps0qXQPziAgOcOH7gtG82igHCnw/FAuzhwTfRP33h0xxqYPCWu/
+ mLglkvi5ObXpPifuGptvmA10X0qfbAKUs0lk1H11oNHYtbPLFm1Gi8YabI2tEUuShqylAJ9XIEky
+ MdwHn279S6/6ehXQt9Kg0Ik4EfnVxRTQKdoGMreeT8vljlw77hx356wo5SHLGpTqHXlPVJSbCUxX
+ 5Kcgtg/QYn3YE3BXe+7NOBrHVmNZzpqd9C9dec3Xp5RiVjY8yXuY18N9g8ImFBS6eRCvk3Gqv9me
+ ZCFzKS+FE4VcnzpfLOfe9D8mq6m0+xhIMwsn/VmuCoeYSEkaL1Hek1GVyvVHVkxN6bXmLaYKBk9E
+ VLpdN+l1zsSiA8U4i72jtD49R1imHd1pPMTyZsYKskF2NKnAHix+xD/4lN9MiCIXQKgkf7VcLisz
+ 3sDAr9Nhs1v/whlKbzxbEDD6yGjvMwzUUJVZLnfA1lBQGR8nP5I7/6CQVS4LARbZcPKlFgRY724i
+ f5yHv5KUbUj98x/4tAiM4zk1wSuLH+v2/CznVxKiWw0535tTexUQ0zB80UEG560SbcxM+j4gId1k
+ 3ezNSZNKHV6vYJpGDj2OTcPmrBEnjf1h6jhdKAw17zhAAImXMtRfW04M5RG+n7TiR5LyY/EqKlYD
+ m3hmKcZH7hnvoJYz+Xn9HA==
+ headers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 31 Aug 2021 10:39:46 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/0
+ Server:
+ - Kestrel
+ ServerDuration:
+ - '00:00:00.0168043'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_total.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_total.yaml
index 212788b20a..6648f2d425 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_total.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_total.yaml
@@ -1,12 +1,12 @@
interactions:
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
- "lines": [{"quantity": 3, "amount": "36.900", "taxCode": "O9999999", "taxIncluded":
+ "lines": [{"quantity": 3, "amount": "30.000", "taxCode": "O9999999", "taxIncluded":
true, "itemCode": "SKU_A", "description": "Test product"}, {"quantity": 1, "amount":
"10.000", "taxCode": "FR020100", "taxIncluded": true, "itemCode": "Shipping",
- "description": null}], "code": "f52d00ae-f27a-46f8-86ab-2593ad4dba0d", "date":
- "2021-04-23", "customerCode": 0, "addresses": {"shipFrom": {"line1": "T\u0119czowa
- 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode":
+ "description": null}], "code": "f9f25492-10bd-463d-89bd-a6fe24253539", "date":
+ "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1": "Teczowa
+ 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
"53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
"region": "", "country": "PL", "postalCode": "53-105"}}, "commit": false, "currencyCode":
"USD", "email": "[email protected]"}}'
@@ -14,68 +14,69 @@ interactions:
Accept:
- '*/*'
Accept-Encoding:
- - gzip, deflate
+ - gzip, deflate, br
Authorization:
- Basic Og==
Connection:
- keep-alive
Content-Length:
- - '786'
+ - '778'
User-Agent:
- - python-requests/2.25.1
+ - python-requests/2.26.0
method: POST
uri: https://rest.avatax.com/api/v2/transactions/createoradjust
response:
body:
string: !!binary |
- H4sIAAAAAAAEA+1ZW2/bNhT+K4WeY0M327Kf5uUyBAvsIHZaoEMxMBJtq5Ulj6LSeEX++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09LOkK1glG0xG
+ UGDHOXAwts+kEK2UVd3oTlcFsK/I0ru5A0uLbXoAKEBbahCiPLi6+SWGCT4LfW4WtRZRWAqt6p+g
+ T68lfkSfeAyuVHLtXMb2xxOJ1z7liN7QSyR3uXLKqVzADdmWabDfHBZKi91i0VNVuiFvYYqiudRR
+ hI3wr6Q73JF2/S5R66XWPwbESVc3z6gDLuXDrZW6UuoF+Q1yZouXXxnk7LLsogzXMQ7qSEGArLrl
+ 5c7tM6p6eRVKSCFaoCaBeZSqtquOqx8T40izLqLWW59XFf8RMQ5zn7UpXCebnsQeSigjGeL8KKs1
+ 4DUgTmhWPwPCoVJslv7l95UAh25rJfYAjuP4KwDOsBWiqmTd9nXdgIrtXmd6YYAjnT6LtMMB9ADO
+ g/q8PsCRl3WTvHfn2UNLwp2eYsKTnVvDICdt6EYjK+Tvbq4hIxA9DSJQ70b8SL/wSd6LIMHPJPhX
+ 9NLRuOkFKvj2ulttlt8eFLCPFMdQzCExjrcpKhig1gspvgD79G3excIPm80Wuh1GeV9nT30k83/4
+ wKfWhumD5hQxmBE/1u2xEYMwPGoO3wF+gszWKukNcNVSCTho9KASQvatbHWRlrMnHwb9r1IePT1i
+ KxRB0QotGvGxi6xV1I/o0cvAg/U+FQgYPebPKU8TJgPijz/zEM3/bjwiMZOMBffyc6oBelBgrLCy
+ FC+5YfXPatnPOkz3Pe1e03bc0h1rfPz2E3jaz/4r3Yc7RxFez0B2cvmYvs/Vycm3TBhgCA/mIO0c
+ Xgs+5teO0NxLPMk72j23hy54GEQpxOf75w==
headers:
Connection:
- keep-alive
Content-Encoding:
- - gzip
+ - br
Content-Type:
- application/json; charset=utf-8
Date:
- - Fri, 23 Apr 2021 06:24:52 GMT
+ - Tue, 31 Aug 2021 10:45:43 GMT
Location:
- - /api/v2/companies/242975/transactions/6001024164488
+ - /api/v2/companies/242975/transactions/6001347179019
Server:
- Kestrel
ServerDuration:
- - '00:00:00.0565630'
+ - '00:00:00.0759473'
Transfer-Encoding:
- chunked
Vary:
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_without_sku_total.yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_without_sku_total.yaml
new file mode 100644
index 0000000000..8dfdd34af7
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_order_line_without_sku_total.yaml
@@ -0,0 +1,87 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "30.000", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "UHJvZHVjdFZhcmlhbnQ6Mg", "description": "Test product"},
+ {"quantity": 1, "amount": "10.000", "taxCode": "FR020100", "taxIncluded": true,
+ "itemCode": "Shipping", "description": null}], "code": "40200b7a-932f-4b7a-9a31-54cc48a0e355",
+ "date": "2021-08-31", "customerCode": 0, "addresses": {"shipFrom": {"line1":
+ "Teczowa 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL",
+ "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2": "",
+ "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},
+ "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '795'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: !!binary |
+ iwsNAICqqqrq/3QNkLO5gaiqmbmZncrLI6PSCzzdvcI9MgEiIQ7qquLuGmmmaqkq6uFeCeE/bmjv
+ QwBrKes261+S9MtIZCQSGRmy9WZtZCVyckLJ3u5srtLHs0kFWW5HfvIPOAu9QBRt1bVd09VtASZY
+ gh4qlIjHuZ51Sp5m1T95rJWY1ZUxVauRVF3DCZwaJ+3vKwu9rGQ3rwuwm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9pXi
+ GHZTSKyH6xQZ9FCrmcAvwL59i4ex8stmscRuh+He19mTH8j8Hz70w9yG/pPm7GIwg/5Y18cGR2O4
+ 1xw+BEroq+kRcFFSGaJmi4iymqPCBmtk0lX0Fp+lPmp6aLfeqZaBB+t9KhAxetC/pTyOOhkQf/4Z
+ iHT87+YjGjPJWHSv72MNENkrzBVmluIlF6z+Xa27YYepPqjdc9rOW6pzjc9ffywJx+e/Un25cxbh
+ 9Qxkd4av6duknZx8zIQJhvJkDm7UroxRLxyhuJh4kleVe283XfDQY4n4+fY5
+ headers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Tue, 31 Aug 2021 10:45:43 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/1001849896958
+ Server:
+ - Kestrel
+ ServerDuration:
+ - '00:00:00.0870240'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 5f10b1b06f..39a5956f29 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -99,6 +99,71 @@ def test_calculate_checkout_line_total(
)
+ "with_discount, expected_net, expected_gross, taxes_in_prices",
+ [
+ (True, "12.20", "15.00", True),
+ (False, "24.39", "30.00", True),
+ (True, "15.00", "18.45", False),
+ (False, "30.00", "36.90", False),
+ ],
+)
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_checkout_line_without_sku_total(
+ with_discount,
+ expected_net,
+ expected_gross,
+ taxes_in_prices,
+ discount_info,
+ checkout_with_item,
+ address,
+ ship_to_pl_address,
+ site_settings,
+ monkeypatch,
+ shipping_zone,
+ plugin_configuration,
+):
+ monkeypatch.setattr(
+ "graphene.Node.to_global_id", lambda x, y: "UHJvZHVjdFZhcmlhbnQ6Mg"
+ )
+
+ plugin_configuration()
+ manager = get_plugins_manager()
+
+ checkout_with_item.shipping_address = ship_to_pl_address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save()
+ site_settings.company_address = address
+ site_settings.include_taxes_in_prices = taxes_in_prices
+ site_settings.save()
+ line = checkout_with_item.lines.first()
+ line.variant.sku = None
+ line.variant.save()
+ product = line.variant.product
+ product.metadata = {}
+ product.charge_taxes = True
+ product.save()
+ product.product_type.save()
+ discounts = [discount_info] if with_discount else None
+
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, discounts, manager)
+ checkout_line_info = lines[0]
+
+ total = manager.calculate_checkout_line_total(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ checkout_with_item.shipping_address,
+ discounts,
+ )
+ total = quantize_price(total, total.currency)
+ assert total == TaxedMoney(
+ net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
+ )
+
+
@pytest.mark.vcr()
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_order_line_total(
@@ -145,7 +210,62 @@ def test_calculate_order_line_total(
product,
)
total = quantize_price(total, total.currency)
- assert total == TaxedMoney(net=Money("30.00", "USD"), gross=Money("36.90", "USD"))
+ assert total == TaxedMoney(net=Money("24.39", "USD"), gross=Money("30.00", "USD"))
+
+
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_order_line_without_sku_total(
+ order_line,
+ address,
+ ship_to_pl_address,
+ shipping_zone,
+ site_settings,
+ monkeypatch,
+ plugin_configuration,
+):
+ monkeypatch.setattr(
+ "graphene.Node.to_global_id", lambda x, y: "UHJvZHVjdFZhcmlhbnQ6Mg"
+ )
+
+ plugin_configuration()
+ manager = get_plugins_manager()
+
+ site_settings.company_address = address
+ site_settings.save(update_fields=["company_address"])
+
+ order = order_line.order
+ order.shipping_address = ship_to_pl_address
+ order.shipping_method = shipping_zone.shipping_methods.get()
+ order.save(update_fields=["shipping_address", "shipping_method"])
+
+ variant = order_line.variant
+ variant.sku = None
+ variant.save()
+ product = variant.product
+ product.metadata = {}
+ product.charge_taxes = True
+ product.save()
+ product.product_type.save()
+
+ channel = order_line.order.channel
+ channel_listing = variant.channel_listings.get(channel=channel)
+
+ net = variant.get_price(product, [], channel, channel_listing)
+ unit_price = TaxedMoney(net=net, gross=net)
+ order_line.unit_price = unit_price
+ total_price = unit_price * order_line.quantity
+ order_line.total_price = total_price
+ order_line.save()
+
+ total = manager.calculate_order_line_total(
+ order_line.order,
+ order_line,
+ variant,
+ product,
+ )
+ total = quantize_price(total, total.currency)
+ assert total == TaxedMoney(net=Money("24.39", "USD"), gross=Money("30.00", "USD"))
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
diff --git a/saleor/product/migrations/0149_alter_productvariant_sku.py b/saleor/product/migrations/0149_alter_productvariant_sku.py
new file mode 100644
index 0000000000..8caae8eb53
--- /dev/null
+++ b/saleor/product/migrations/0149_alter_productvariant_sku.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.5 on 2021-07-13 15:08
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0148_producttype_type"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="productvariant",
+ name="sku",
+ field=models.CharField(blank=True, max_length=255, null=True, unique=True),
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 94eca323a4..0fbef41fe3 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -2,6 +2,7 @@ import datetime
from typing import TYPE_CHECKING, Iterable, Optional, Union
from uuid import uuid4
+import graphene
from django.conf import settings
from django.contrib.postgres.aggregates import StringAgg
from django.contrib.postgres.indexes import GinIndex
@@ -538,7 +539,7 @@ class ProductChannelListing(PublishableModel):
class ProductVariant(SortableModel, ModelWithMetadata):
- sku = models.CharField(max_length=255, unique=True)
+ sku = models.CharField(max_length=255, unique=True, null=True, blank=True)
name = models.CharField(max_length=255, blank=True)
product = models.ForeignKey(
Product, related_name="variants", on_delete=models.CASCADE
@@ -561,7 +562,10 @@ class ProductVariant(SortableModel, ModelWithMetadata):
app_label = "product"
def __str__(self) -> str:
- return self.name or self.sku
+ return self.name or self.sku or f"ID:{self.pk}"
+
+ def get_global_id(self):
+ return graphene.Node.to_global_id("ProductVariant", self.id)
def get_price(
self,
diff --git a/saleor/product/tests/test_generate_and_set_variant_name.py b/saleor/product/tests/test_generate_and_set_variant_name.py
index 7cea2cba72..2f187b157f 100644
--- a/saleor/product/tests/test_generate_and_set_variant_name.py
+++ b/saleor/product/tests/test_generate_and_set_variant_name.py
@@ -208,3 +208,17 @@ def test_update_variants_changed_does_nothing_with_no_attributes():
saved_attributes = []
# FIXME: This method no longer returns any value
assert _update_variants_names(product_type, saved_attributes) is None
+
+
+def test_only_not_variant_selection_attr_left_variant_name_change_to_global_id(product):
+ new_name = "test_name"
+ product_variant = product.variants.first()
+ assert not product_variant.name == new_name
+ product_variant.sku = None
+ product_variant.save()
+ attribute = product.product_type.variant_attributes.first()
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+ _update_variants_names(product.product_type, [attribute])
+ product_variant.refresh_from_db()
+ assert product_variant.name == product_variant.get_global_id()
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index 7baa0c19b3..7d00491740 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
from ...attribute import AttributeInputType, AttributeType
@@ -7,7 +7,7 @@ if TYPE_CHECKING:
from ..models import ProductVariant
-def generate_and_set_variant_name(variant: "ProductVariant", sku: str):
+def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str]):
"""Generate ProductVariant's name based on its attributes."""
attributes_display = []
@@ -25,7 +25,7 @@ def generate_and_set_variant_name(variant: "ProductVariant", sku: str):
name = " / ".join(sorted(attributes_display))
if not name:
- name = sku
+ name = sku or variant.get_global_id()
variant.name = name
variant.save(update_fields=["name"])
diff --git a/saleor/seo/schema/email.py b/saleor/seo/schema/email.py
index aca921cde2..85739548e2 100644
--- a/saleor/seo/schema/email.py
+++ b/saleor/seo/schema/email.py
@@ -26,7 +26,11 @@ def get_product_data(line: "OrderLine", organization: dict) -> dict:
)
product_data = {
"@type": "Offer",
- "itemOffered": {"@type": "Product", "name": line_name, "sku": line.product_sku},
+ "itemOffered": {
+ "@type": "Product",
+ "name": line_name,
+ "sku": line.product_sku or line.product_variant_id,
+ },
"price": gross_product_price.amount,
"priceCurrency": gross_product_price.currency,
"eligibleQuantity": {"@type": "QuantitativeValue", "value": line.quantity},
diff --git a/saleor/seo/tests/test_seo_schema.py b/saleor/seo/tests/test_seo_schema.py
index 941c570dc1..b492893907 100644
--- a/saleor/seo/tests/test_seo_schema.py
+++ b/saleor/seo/tests/test_seo_schema.py
@@ -27,6 +27,17 @@ def test_get_product_data_without_image(order_with_lines):
assert "image" not in result["itemOffered"]
+def test_get_product_data_without_sku(order_with_lines):
+ """Tested OrderLine Product has no image assigned."""
+ line = order_with_lines.lines.first()
+ line.product_sku = None
+ line.save()
+
+ organization = get_organization()
+ result = get_product_data(line, organization)
+ assert "image" not in result["itemOffered"]
+
+
def test_get_product_data_with_image(order_with_lines, product_with_image):
line = order_with_lines.lines.first()
variant = product_with_image.variants.first()
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index ea36da5711..f47a80f361 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2703,6 +2703,7 @@ def order_line(order, variant):
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -2796,6 +2797,7 @@ def order_line_with_allocation_in_many_stocks(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -2844,6 +2846,7 @@ def order_line_with_one_allocation(
product_name=str(product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -2978,6 +2981,7 @@ def order_with_lines(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -3027,6 +3031,7 @@ def order_with_lines(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -3179,6 +3184,7 @@ def order_with_lines_channel_PLN(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -3227,6 +3233,7 @@ def order_with_lines_channel_PLN(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -3278,6 +3285,7 @@ def order_with_line_without_inventory_tracking(
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
quantity=quantity,
@@ -4789,6 +4797,7 @@ def allocations(order_list, stock, channel_USD):
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=price,
@@ -4802,6 +4811,7 @@ def allocations(order_list, stock, channel_USD):
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=price,
@@ -4815,6 +4825,7 @@ def allocations(order_list, stock, channel_USD):
product_name=str(variant.product),
variant_name=str(variant),
product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
is_shipping_required=variant.is_shipping_required(),
is_gift_card=variant.is_gift_card(),
unit_price=price,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 6a8249ce44..8951592262 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -122,6 +122,7 @@ def generate_order_lines_payload(lines: Iterable[OrderLine]):
lines,
fields=line_fields,
extra_dict_data={
+ "product_variant_id": (lambda l: l.product_variant_id),
"total_price_net_amount": (lambda l: l.total_price.net.amount),
"total_price_gross_amount": (lambda l: l.total_price.gross.amount),
"allocations": (lambda l: prepare_order_lines_allocations_payload(l)),
@@ -437,13 +438,13 @@ def generate_product_payload(product: "Product"):
def generate_product_deleted_payload(product: "Product", variants_id):
serializer = PayloadSerializer()
product_fields = PRODUCT_FIELDS
- variant_global_ids = [
+ product_variant_ids = [
graphene.Node.to_global_id("ProductVariant", pk) for pk in variants_id
]
product_payload = serializer.serialize(
[product],
fields=product_fields,
- extra_dict_data={"variants": list(variant_global_ids)},
+ extra_dict_data={"variants": list(product_variant_ids)},
)
return product_payload
@@ -509,6 +510,7 @@ def generate_product_variant_payload(product_variants: Iterable["ProductVariant"
product_variants,
fields=PRODUCT_VARIANT_FIELDS,
extra_dict_data={
+ "id": lambda v: v.get_global_id(),
"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),
@@ -537,6 +539,7 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
"product_name": lambda fl: fl.order_line.product_name,
"variant_name": lambda fl: fl.order_line.variant_name,
"product_sku": lambda fl: fl.order_line.product_sku,
+ "product_variant_id": lambda fl: fl.order_line.product_variant_id,
"weight": (
lambda fl: fl.order_line.variant.get_weight().g
if fl.order_line.variant
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index a71e1dc713..d4129ca5ce 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -25,6 +25,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:
data.append(
{
"sku": variant.sku,
+ "variant_id": variant.get_global_id(),
"quantity": line_info.line.quantity,
"base_price": str(base_price.amount),
"currency": channel.currency_code,
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 3938cc8ae3..0941ce771a 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -65,6 +65,10 @@ def test_generate_order_payload(
name="Voucher",
)
+ line_without_sku = order_with_lines.lines.last()
+ line_without_sku.product_sku = None
+ line_without_sku.save()
+
assert fulfilled_order.fulfillments.count() == 1
fulfillment = fulfilled_order.fulfillments.first()
@@ -135,6 +139,7 @@ def test_generate_fulfillment_lines_payload(order_with_lines):
"product_name": line.product_name,
"variant_name": line.variant_name,
"product_sku": line.product_sku,
+ "product_variant_id": line.product_variant_id,
"id": graphene.Node.to_global_id("FulfillmentLine", fulfillment_line.id),
"product_type": "Default Type",
"quantity": fulfillment_line.quantity,
@@ -222,6 +227,7 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
"translated_product_name": line.translated_product_name,
"translated_variant_name": line.translated_variant_name,
"product_sku": line.product_sku,
+ "product_variant_id": line.product_variant_id,
"quantity": line.quantity,
"currency": line.currency,
"unit_discount_amount": str(unit_discount_amount),
@@ -251,6 +257,26 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
}
+def test_order_line_without_sku_still_has_id(order, order_line_with_one_allocation):
+ order.lines.add(order_line_with_one_allocation)
+ line = order_line_with_one_allocation
+ line.unit_discount_amount = Decimal("10.0")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
+ line.product_sku = None
+ line.save()
+
+ payload = json.loads(generate_order_payload(order))[0]
+ lines_payload = payload.get("lines")
+
+ assert len(lines_payload) == 1
+
+ line_payload = lines_payload[0]
+ assert line_payload["product_sku"] is None
+ assert line_payload["product_variant_id"] == line.product_variant_id
+
+
def test_generate_base_product_variant_payload(product_with_two_variants):
stocks_to_serialize = [
variant.stocks.first() for variant in product_with_two_variants.variants.all()
@@ -310,6 +336,7 @@ def test_generate_product_variant_payload(
assert payload.get(field) is not None
assert variant_id is not None
+ assert payload["id"] == variant_id
assert payload["sku"] == "prodVar1"
assert len(payload["attributes"]) == 2
assert len(payload["channel_listings"]) == 1
@@ -341,6 +368,7 @@ def test_generate_product_variant_with_external_media_payload(
assert payload.get(field) is not None
assert variant_id is not None
+ assert payload["id"] == variant_id
assert payload["sku"] == "prodVar1"
assert payload["media"] == [
{"alt": "video_1", "url": "https://www.youtube.com/watch?v=di8_dJ3Clyo"}
@@ -358,6 +386,37 @@ def test_generate_product_variant_with_external_media_payload(
assert len(payload.keys()) == len(payload_fields)
+def test_generate_product_variant_without_sku_payload(
+ product_with_variant_with_two_attributes, product_with_images, channel_USD
+):
+ variant = product_with_variant_with_two_attributes.variants.first()
+ variant.sku = None
+ variant.save()
+ 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"]
+ payload_fields = list(
+ chain(
+ ["id", "type"], PRODUCT_VARIANT_FIELDS, extra_dict_data, additional_fields
+ )
+ )
+ assert variant_id is not None
+ assert payload["id"] == variant_id
+ assert payload["sku"] is None
+ assert len(payload["attributes"]) == 2
+ assert len(payload["channel_listings"]) == 1
+ assert payload["channel_listings"][0] == {
+ "cost_price_amount": "1.000",
+ "currency": "USD",
+ "id": ANY,
+ "channel_slug": channel_USD.slug,
+ "price_amount": "10.000",
+ "type": "ProductVariantChannelListing",
+ }
+ assert len(payload.keys()) == len(payload_fields)
+
+
def test_generate_product_variant_deleted_payload(
product_with_variant_with_two_attributes,
):
@@ -380,6 +439,7 @@ def test_generate_product_variant_deleted_payload(
assert payload.get(field) is not None
assert payload_variant_id != "None"
+ assert payload["id"] == variant.get_global_id()
assert payload["sku"] == "prodVar1"
assert len(payload["attributes"]) == 2
assert len(payload["channel_listings"]) == 1
@@ -441,6 +501,16 @@ def test_generate_payment_payload(dummy_webhook_app_payment_data):
assert payload == json.dumps(expected_payload, cls=CustomJsonEncoder)
+def test_generate_checkout_lines_payload(checkout_with_single_item):
+ payload = json.loads(generate_checkout_payload(checkout_with_single_item))[0]
+ assert payload.get("lines")
+
+ variant = checkout_with_single_item.lines.first().variant
+ line = payload["lines"][0]
+ assert line["sku"] == variant.sku
+ assert line["variant_id"] == variant.get_global_id()
+
+
def test_generate_product_translation_payload(product_translation_fr):
payload = generate_translation_payload(product_translation_fr)
data = json.loads(payload)
diff --git a/templates/invoices/invoice_products_table.html b/templates/invoices/invoice_products_table.html
index 6dc222bc66..4adbf7fc0a 100644
--- a/templates/invoices/invoice_products_table.html
+++ b/templates/invoices/invoice_products_table.html
@@ -20,8 +20,10 @@
<td class="cell-product">
<span class="normal-text-table">
{{ product|truncatechars:46 }}
- <div class="padded-font-small"></div>
- <span class="header-category-small">SKU: {{ product.product_sku }}</span>
+ {% if product.product_sku %}
+ <div class="padded-font-small"></div>
+ <span class="header-category-small">SKU: {{ product.product_sku }}</span>
+ {% endif %}
</span>
</td>
<td class="cell-price">