Skip to content

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

Fix crash on checkout resolver when variant listing is not present (#16942)

Maciej Korycinski8d08f65fbf18
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 4efa82825a..c670509eef 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -49,10 +49,7 @@ def calculate_base_line_total_price(
"""
from ..discount.utils.voucher import calculate_line_discount_amount_from_voucher
- variant = line_info.variant
- variant_price = variant.get_base_price(
- line_info.channel_listing, line_info.line.price_override
- )
+ variant_price = line_info.undiscounted_unit_price
total_price = variant_price * line_info.line.quantity
@@ -86,10 +83,7 @@ def calculate_undiscounted_base_line_unit_price(
channel: "Channel",
):
"""Calculate line unit price without discounts and vouchers."""
- variant = line_info.variant
- variant_price = variant.get_base_price(
- line_info.channel_listing, line_info.line.price_override
- )
+ variant_price = line_info.undiscounted_unit_price
return quantize_price(variant_price, variant_price.currency)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index c8e60da060..83c52ff13c 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -254,6 +254,18 @@ def checkout_line_tax_rate(
return checkout_line_info.line.tax_rate
+def update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]):
+ """Update line undiscounted unit price amount.
+
+ Undiscounted unit price stores the denormalized price of the variant.
+ """
+ for line_info in lines:
+ if not line_info.channel_listing or line_info.channel_listing.price is None:
+ continue
+
+ line_info.line.undiscounted_unit_price = line_info.undiscounted_unit_price
+
+
def _fetch_checkout_prices_if_expired(
checkout_info: "CheckoutInfo",
manager: "PluginsManager",
@@ -295,6 +307,8 @@ def _fetch_checkout_prices_if_expired(
)
lines = cast(list, lines)
+ update_undiscounted_unit_price_for_lines(lines)
+
create_or_update_discount_objects_from_promotion_for_checkout(
checkout_info, lines, database_connection_name
)
@@ -389,6 +403,7 @@ def _fetch_checkout_prices_if_expired(
"total_price_net_amount",
"total_price_gross_amount",
"tax_rate",
+ "undiscounted_unit_price_amount",
],
)
return checkout_info, lines
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 5972fa9c08..83badea256 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -2,18 +2,16 @@ import itertools
from collections.abc import Iterable
from dataclasses import dataclass, field
from functools import cached_property, singledispatch
-from typing import (
- TYPE_CHECKING,
- Any,
- Optional,
- Union,
-)
+from typing import TYPE_CHECKING, Any, Optional, Union
from uuid import UUID
from django.conf import settings
+from prices import Money
from ..core.db.connection import allow_writer
+from ..core.prices import quantize_price
from ..core.pricing.interface import LineInfo
+from ..core.taxes import zero_money
from ..discount import VoucherType
from ..discount.interface import fetch_variant_rules_info, fetch_voucher_info
from ..shipping.interface import ShippingMethodData
@@ -56,6 +54,41 @@ class CheckoutLineInfo(LineInfo):
discounts: list["CheckoutLineDiscount"]
tax_class: Optional["TaxClass"] = None
+ @cached_property
+ def variant_discounted_price(self) -> Money:
+ """Return the discounted variant price.
+
+ `variant_discounted_price` means price with the most beneficial applicable
+ catalogue promotion.
+ If listing is present return the discounted price from the listing,
+ if listing is not present, calculate current unit price based on
+ `undiscounted_unit_price` and catalogue promotion discounts.
+ """
+ if self.channel_listing and self.channel_listing.discounted_price is not None:
+ return self.channel_listing.discounted_price
+ catalogue_discounts = self.get_catalogue_discounts()
+ total_price = self.undiscounted_unit_price * self.line.quantity
+ for discount in catalogue_discounts:
+ total_price -= discount.amount
+
+ unit_price = max(
+ total_price / self.line.quantity, zero_money(self.line.currency)
+ )
+ return quantize_price(unit_price, self.line.currency)
+
+ @cached_property
+ def undiscounted_unit_price(self) -> Money:
+ """Provide undiscounted unit price.
+
+ Return the undiscounted variant price when listing is present. If variant
+ doesn't have listing, use denormalized price.
+ """
+ if self.channel_listing and self.channel_listing.price is not None:
+ return self.variant.get_base_price(
+ self.channel_listing, self.line.price_override
+ )
+ return self.line.undiscounted_unit_price
+
@dataclass
class CheckoutInfo:
@@ -346,7 +379,20 @@ def fetch_checkout_lines(
checkout, product, variant_channel_listing, product_channel_listing_mapping
):
unavailable_variant_pks.append(variant.pk)
- if not skip_lines_with_unavailable_variants:
+ if (
+ not skip_lines_with_unavailable_variants
+ # variant price is denormalized on checkout line object. We have enough
+ # information to include the variant without listing in the
+ # calculations. This will allow to display a proper prices but we won't
+ # allow to finalize the checkout without removing `unavailable_variant`
+ # from the checkout.
+ or _only_variant_listing_is_missing(
+ checkout,
+ product,
+ variant_channel_listing,
+ product_channel_listing_mapping,
+ )
+ ):
lines_info.append(
CheckoutLineInfo(
line=line,
@@ -400,7 +446,9 @@ def fetch_checkout_lines(
return lines_info, unavailable_variant_pks
-def get_variant_channel_listing(variant: "ProductVariant", channel_id: int):
+def get_variant_channel_listing(
+ variant: "ProductVariant", channel_id: int
+) -> Optional["ProductVariantChannelListing"]:
variant_channel_listing = None
for channel_listing in variant.channel_listings.all():
if channel_listing.channel_id == channel_id:
@@ -408,29 +456,58 @@ def get_variant_channel_listing(variant: "ProductVariant", channel_id: int):
return variant_channel_listing
-def _is_variant_valid(
+def _product_channel_listing_is_valid(
checkout: "Checkout",
product: "Product",
- variant_channel_listing: "ProductVariantChannelListing",
product_channel_listing_mapping: dict,
):
- if not variant_channel_listing or variant_channel_listing.price is None:
- return False
-
product_channel_listing = _get_product_channel_listing(
product_channel_listing_mapping, checkout.channel_id, product
)
-
if (
not product_channel_listing
or product_channel_listing.is_available_for_purchase() is False
or not product_channel_listing.is_visible
):
return False
+ return True
+
+
+def _is_variant_valid(
+ checkout: "Checkout",
+ product: "Product",
+ variant_channel_listing: Optional["ProductVariantChannelListing"],
+ product_channel_listing_mapping: dict,
+):
+ if not variant_channel_listing or variant_channel_listing.price is None:
+ return False
+ if not _product_channel_listing_is_valid(
+ checkout,
+ product,
+ product_channel_listing_mapping,
+ ):
+ return False
return True
+def _only_variant_listing_is_missing(
+ checkout: "Checkout",
+ product: "Product",
+ variant_channel_listing: Optional["ProductVariantChannelListing"],
+ product_channel_listing_mapping: dict,
+):
+ if not _product_channel_listing_is_valid(
+ checkout,
+ product,
+ product_channel_listing_mapping,
+ ):
+ return False
+ if not variant_channel_listing or variant_channel_listing.price is None:
+ return True
+ return False
+
+
def _get_product_channel_listing(
product_channel_listing_mapping: dict, channel_id: int, product: "Product"
):
diff --git a/saleor/checkout/migrations/0070_checkoutline_undiscounted_unit_price_amount.py b/saleor/checkout/migrations/0070_checkoutline_undiscounted_unit_price_amount.py
new file mode 100644
index 0000000000..c9e99b5f1e
--- /dev/null
+++ b/saleor/checkout/migrations/0070_checkoutline_undiscounted_unit_price_amount.py
@@ -0,0 +1,19 @@
+# Generated by Django 4.2.15 on 2024-10-23 11:43
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0069_merge_20240514_1008"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkoutline",
+ name="undiscounted_unit_price_amount",
+ field=models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0071_propagate_line_unidscounted_unit_price.py b/saleor/checkout/migrations/0071_propagate_line_unidscounted_unit_price.py
new file mode 100644
index 0000000000..caf8371494
--- /dev/null
+++ b/saleor/checkout/migrations/0071_propagate_line_unidscounted_unit_price.py
@@ -0,0 +1,98 @@
+# Generated by Django 4.2.15 on 2024-10-23 11:43
+from decimal import Decimal
+
+from babel.numbers import get_currency_precision
+from django.db import migrations
+from django.db.models import OuterRef
+from prices import Money
+
+# It takes 1.42 seconds to process batch when having over 5 mln records to process.
+
+BATCH_SIZE = 2000
+
+
+def queryset_in_batches(queryset):
+ """Slice a queryset into batches.
+
+ Input queryset should be sorted be pk.
+ """
+ start_pk = 0
+
+ while True:
+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]
+ pks = list(qs.values_list("pk", flat=True))
+ if not pks:
+ break
+ yield pks
+ start_pk = pks[-1]
+
+
+def quantize_price(price: Money, currency: str) -> Money:
+ precision = get_currency_precision(currency)
+ number_places = Decimal(10) ** -precision
+ return price.quantize(number_places)
+
+
+def propagate_lines_undiscounted_unit_price(apps, _schema_editor):
+ CheckoutLine = apps.get_model("checkout", "CheckoutLine")
+ TaxConfiguration = apps.get_model("tax", "TaxConfiguration")
+ ProductVariantChannelListing = apps.get_model(
+ "product", "ProductVariantChannelListing"
+ )
+ checkout_lines = CheckoutLine.objects.filter(
+ undiscounted_unit_price_amount__isnull=True
+ ).order_by("pk")
+ for pks in queryset_in_batches(checkout_lines):
+ lines = (
+ CheckoutLine.objects.select_related("checkout")
+ .annotate(
+ listing_price_amount=ProductVariantChannelListing.objects.filter(
+ variant_id=OuterRef("variant_id"),
+ channel_id=OuterRef("checkout__channel_id"),
+ ).values_list("price_amount", flat=True)
+ )
+ .filter(pk__in=pks, undiscounted_unit_price_amount__isnull=True)
+ )
+ channel_ids = {line.checkout.channel_id for line in lines}
+ tax_configurations = TaxConfiguration.objects.filter(
+ channel_id__in=channel_ids
+ ).values_list("channel_id", "prices_entered_with_tax")
+ channel_id_to_prices_with_tax_map = dict(tax_configurations)
+
+ for line in lines:
+ if line.price_override is not None:
+ line.undiscounted_unit_price_amount = line.price_override
+ continue
+
+ if line.listing_price_amount is not None:
+ line.undiscounted_unit_price_amount = line.listing_price_amount
+ continue
+
+ channel_id = line.checkout.channel_id
+ if channel_id_to_prices_with_tax_map.get(channel_id):
+ base_total_price = line.total_price_gross_amount
+ else:
+ base_total_price = line.total_price_net_amount
+
+ if base_total_price is Decimal(0) or line.quantity == 0:
+ line.undiscounted_unit_price_amount = Decimal(0)
+ else:
+ line.undiscounted_unit_price_amount = quantize_price(
+ base_total_price / line.quantity, line.currency
+ )
+ CheckoutLine.objects.bulk_update(lines, ["undiscounted_unit_price_amount"])
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tax", "0008_auto_20240122_1353"),
+ ("product", "0194_auto_20240620_1404"),
+ ("checkout", "0070_checkoutline_undiscounted_unit_price_amount"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ propagate_lines_undiscounted_unit_price,
+ reverse_code=migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0072_alter_checkoutline_undiscounted_unit_price_amount.py b/saleor/checkout/migrations/0072_alter_checkoutline_undiscounted_unit_price_amount.py
new file mode 100644
index 0000000000..ca7385c6e8
--- /dev/null
+++ b/saleor/checkout/migrations/0072_alter_checkoutline_undiscounted_unit_price_amount.py
@@ -0,0 +1,43 @@
+# Generated by Django 4.2.15 on 2024-10-29 11:02
+
+from decimal import Decimal
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0071_propagate_line_unidscounted_unit_price"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterField(
+ model_name="checkoutline",
+ name="undiscounted_unit_price_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkoutline
+ ALTER COLUMN undiscounted_unit_price_amount
+ SET DEFAULT 0;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE checkout_checkoutline
+ ALTER COLUMN undiscounted_unit_price_amount
+ SET NOT NULL;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ],
+ )
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 8c620ecb77..57eb29aef2 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -302,6 +302,17 @@ class CheckoutLine(ModelWithMetadata):
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
)
+ undiscounted_unit_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+
+ undiscounted_unit_price = MoneyField(
+ amount_field="undiscounted_unit_price_amount",
+ currency_field="currency",
+ )
+
total_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
diff --git a/saleor/checkout/tests/fixtures/checkout.py b/saleor/checkout/tests/fixtures/checkout.py
index 777421109a..e631951a25 100644
--- a/saleor/checkout/tests/fixtures/checkout.py
+++ b/saleor/checkout/tests/fixtures/checkout.py
@@ -5,6 +5,7 @@ import pytest
from django.utils import timezone
from ....plugins.manager import get_plugins_manager
+from ....product.models import ProductVariantChannelListing
from ...fetch import fetch_checkout_info, fetch_checkout_lines
from ...models import Checkout, CheckoutLine, CheckoutMetadata
from ...utils import add_variant_to_checkout
@@ -275,6 +276,15 @@ def checkout_with_billing_address(checkout_with_shipping_method, address):
def checkout_with_variants_for_cc(
checkout, stocks_for_cc, product_variant_list, product_with_two_variants
):
+ channel_listings_map = {
+ listing.variant_id: listing
+ for listing in ProductVariantChannelListing.objects.filter(
+ channel_id=checkout.channel_id,
+ variant__in=product_variant_list
+ + [product_with_two_variants.variants.last()],
+ )
+ }
+
CheckoutLine.objects.bulk_create(
[
CheckoutLine(
@@ -282,18 +292,27 @@ def checkout_with_variants_for_cc(
variant=product_variant_list[0],
quantity=3,
currency="USD",
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[0].id
+ ).price_amount,
),
CheckoutLine(
checkout=checkout,
variant=product_variant_list[1],
quantity=10,
currency="USD",
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[0].id
+ ).price_amount,
),
CheckoutLine(
checkout=checkout,
variant=product_with_two_variants.variants.last(),
quantity=5,
currency="USD",
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[0].id
+ ).price_amount,
),
]
)
@@ -568,17 +587,38 @@ def checkout_for_cc(channel_USD, customer_user):
@pytest.fixture
def checkout_with_item_for_cc(checkout_for_cc, product_variant_list):
+ listing = product_variant_list[0].channel_listings.get(
+ channel_id=checkout_for_cc.channel_id
+ )
CheckoutLine.objects.create(
checkout=checkout_for_cc,
variant=product_variant_list[0],
quantity=1,
currency=checkout_for_cc.currency,
+ undiscounted_unit_price_amount=listing.price_amount,
)
return checkout_for_cc
@pytest.fixture
def checkout_with_items_for_cc(checkout_for_cc, product_variant_list):
+ (
+ ProductVariantChannelListing.objects.create(
+ variant=product_variant_list[2],
+ channel=checkout_for_cc.channel,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ discounted_price_amount=Decimal(10),
+ currency=checkout_for_cc.channel.currency_code,
+ ),
+ )
+ channel_listings_map = {
+ listing.variant_id: listing
+ for listing in ProductVariantChannelListing.objects.filter(
+ channel_id=checkout_for_cc.channel_id, variant__in=product_variant_list
+ )
+ }
+
CheckoutLine.objects.bulk_create(
[
CheckoutLine(
@@ -586,21 +626,41 @@ def checkout_with_items_for_cc(checkout_for_cc, product_variant_list):
variant=product_variant_list[0],
quantity=1,
currency=checkout_for_cc.currency,
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[0].id
+ ).price_amount,
),
CheckoutLine(
checkout=checkout_for_cc,
variant=product_variant_list[1],
quantity=1,
currency=checkout_for_cc.currency,
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[1].id
+ ).price_amount,
),
CheckoutLine(
checkout=checkout_for_cc,
variant=product_variant_list[2],
quantity=1,
currency=checkout_for_cc.currency,
+ undiscounted_unit_price_amount=channel_listings_map.get(
+ product_variant_list[2].id
+ ).price_amount,
),
]
)
checkout_for_cc.set_country("US", commit=True)
return checkout_for_cc
+
+
+def checkout_with_line_without_listing(checkout_with_items):
+ line = checkout_with_items.lines.first()
+ line.quantity = 2
+ line.save()
+ line.variant.channel_listings.filter(
+ channel_id=checkout_with_items.channel_id
+ ).delete()
+ return checkout_with_items, line
diff --git a/saleor/checkout/tests/fixtures/checkout_line.py b/saleor/checkout/tests/fixtures/checkout_line.py
index 9559366cbb..e275b14b90 100644
--- a/saleor/checkout/tests/fixtures/checkout_line.py
+++ b/saleor/checkout/tests/fixtures/checkout_line.py
@@ -28,6 +28,9 @@ def checkout_line_with_reservation_in_many_stocks(
checkout_line = checkout.lines.create(
variant=variant,
quantity=3,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price_amount,
)
reserved_until = timezone.now() + datetime.timedelta(minutes=5)
@@ -61,6 +64,9 @@ def checkout_line_with_one_reservation(
checkout_line = checkout.lines.create(
variant=variant,
quantity=2,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price_amount,
)
reserved_until = timezone.now() + datetime.timedelta(minutes=5)
diff --git a/saleor/checkout/tests/fixtures/checkout_with_discount.py b/saleor/checkout/tests/fixtures/checkout_with_discount.py
index 4e66127432..8467b9abb2 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_discount.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_discount.py
@@ -131,6 +131,9 @@ def checkout_with_item_and_gift_promotion(checkout_with_item, gift_promotion_rul
top_price, variant_id = max(
variant_listings.values_list("discounted_price_amount", "variant")
)
+ variant_listing = [
+ listing for listing in variant_listings if listing.variant_id == variant_id
+ ][0]
line = CheckoutLine.objects.create(
checkout=checkout_with_item,
@@ -138,6 +141,7 @@ def checkout_with_item_and_gift_promotion(checkout_with_item, gift_promotion_rul
variant_id=variant_id,
is_gift=True,
currency="USD",
+ undiscounted_unit_price_amount=variant_listing.price_amount,
)
CheckoutLineDiscount.objects.create(
diff --git a/saleor/checkout/tests/test_fetch.py b/saleor/checkout/tests/test_fetch.py
new file mode 100644
index 0000000000..a143859d92
--- /dev/null
+++ b/saleor/checkout/tests/test_fetch.py
@@ -0,0 +1,297 @@
+from ..fetch import CheckoutLineInfo, fetch_checkout_lines
+
+
+def test_checkout_line_info_undiscounted_unit_price(checkout_with_item_on_promotion):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ expected_variant_price = variant_channel_listing.price
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert checkout_line_info.undiscounted_unit_price == expected_variant_price
+
+
+def test_checkout_line_info_undiscounted_unit_price_without_listing(
+ checkout_with_item_on_promotion,
+):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ expected_variant_price = variant_channel_listing.price
+
+ variant.channel_listings.all().delete()
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=None,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert checkout_line_info.undiscounted_unit_price == expected_variant_price
+
+
+def test_checkout_line_info_undiscounted_unit_price_when_listing_without_price(
+ checkout_with_item_on_promotion,
+):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ expected_variant_price = variant_channel_listing.price
+
+ variant_channel_listing.price_amount = None
+ variant_channel_listing.save(update_fields=["price_amount"])
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=None,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert checkout_line_info.undiscounted_unit_price == expected_variant_price
+
+
+def test_checkout_line_info_variant_discounted_price(checkout_with_item_on_promotion):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert (
+ checkout_line_info.variant_discounted_price == expected_discounted_variant_price
+ )
+
+
+def test_checkout_line_info_variant_discounted_price_without_listing(
+ checkout_with_item_on_promotion,
+):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ variant.channel_listings.all().delete()
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=None,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert (
+ checkout_line_info.variant_discounted_price == expected_discounted_variant_price
+ )
+
+
+def test_checkout_line_info_variant_discounted_price_when_listing_without_price(
+ checkout_with_item_on_promotion,
+):
+ # given
+ checkout_line = checkout_with_item_on_promotion.lines.first()
+ channel = checkout_with_item_on_promotion.channel
+ variant = checkout_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = checkout_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ variant_channel_listing.discounted_price_amount = None
+ variant_channel_listing.save(update_fields=["discounted_price_amount"])
+
+ # when
+ checkout_line_info = CheckoutLineInfo(
+ line=checkout_line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ tax_class=product.tax_class or product_type.tax_class,
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert (
+ checkout_line_info.variant_discounted_price == expected_discounted_variant_price
+ )
+
+
+def test_fetch_checkout_lines_info(checkout_with_item_on_promotion):
+ # given
+ lines = list(checkout_with_item_on_promotion.lines.all())
+
+ # when
+ line_infos, unavailable_variants = fetch_checkout_lines(
+ checkout_with_item_on_promotion
+ )
+
+ # then
+ assert len(line_infos) == len(lines) == 1
+ line_info = line_infos[0]
+ line = lines[0]
+ assert line_info.line.pk == line.pk
+ assert not unavailable_variants
+
+
+def test_fetch_checkout_lines_info_when_product_not_available(
+ checkout_with_item_on_promotion,
+):
+ # given
+ lines = list(checkout_with_item_on_promotion.lines.all())
+ line = lines[0]
+ line.variant.product.channel_listings.update(is_published=False)
+
+ # when
+ line_infos, unavailable_variants = fetch_checkout_lines(
+ checkout_with_item_on_promotion
+ )
+
+ # then
+ assert len(line_infos) == 0
+ assert unavailable_variants == [line.variant_id]
+
+
+def test_fetch_checkout_lines_info_when_variant_without_channel_listing(
+ checkout_with_item_on_promotion,
+):
+ # given
+ lines = list(checkout_with_item_on_promotion.lines.all())
+ line = lines[0]
+ line.variant.channel_listings.all().delete()
+
+ # when
+ line_infos, unavailable_variants = fetch_checkout_lines(
+ checkout_with_item_on_promotion
+ )
+
+ # then
+ assert len(line_infos) == len(lines) == 1
+ line_info = line_infos[0]
+ line = lines[0]
+ assert line_info.line.pk == line.pk
+ assert unavailable_variants == [line.variant_id]
+
+
+def test_fetch_checkout_lines_info_when_variant_channel_listing_without_price(
+ checkout_with_item_on_promotion,
+):
+ # given
+ lines = list(checkout_with_item_on_promotion.lines.all())
+ line = lines[0]
+
+ variant_channel_listing = line.variant.channel_listings.get(
+ channel_id=checkout_with_item_on_promotion.channel_id
+ )
+
+ variant_channel_listing.price_amount = None
+ variant_channel_listing.save(update_fields=["price_amount"])
+
+ # when
+ line_infos, unavailable_variants = fetch_checkout_lines(
+ checkout_with_item_on_promotion
+ )
+
+ # then
+ assert len(line_infos) == len(lines) == 1
+ line_info = line_infos[0]
+ line = lines[0]
+ assert line_info.line.pk == line.pk
+ assert unavailable_variants == [line.variant_id]
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
index c83860d7fb..ca4ba64493 100644
--- a/saleor/checkout/tests/test_tasks.py
+++ b/saleor/checkout/tests/test_tasks.py
@@ -10,7 +10,7 @@ from django.utils import timezone
from ...order import OrderEvents
from ...order.models import Order
-from ..models import Checkout
+from ..models import Checkout, CheckoutLine
from ..tasks import (
automatic_checkout_completion_task,
delete_expired_checkouts,
@@ -23,13 +23,26 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
now = timezone.now()
checkout_count = Checkout.objects.count()
+ variant_listings_map = {
+ listing.channel_id: listing.price_amount
+ for listing in variant.channel_listings.all()
+ }
+ lines_to_create = []
+
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
expired_anonymous_checkout.user = None
expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
- expired_anonymous_checkout.lines.create(
- checkout=expired_anonymous_checkout, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_anonymous_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_anonymous_checkout.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_1 = checkouts_list[1]
@@ -37,8 +50,15 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_1.user = None
not_expired_checkout_1.created_at = now - datetime.timedelta(days=35)
not_expired_checkout_1.last_change = now - datetime.timedelta(days=29)
- not_expired_checkout_1.lines.create(
- checkout=not_expired_checkout_1, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_1,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_1.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_2 = checkouts_list[2]
@@ -46,8 +66,15 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_2.user = customer_user
not_expired_checkout_2.created_at = now - datetime.timedelta(days=45)
not_expired_checkout_2.last_change = now - datetime.timedelta(days=40)
- not_expired_checkout_2.lines.create(
- checkout=not_expired_checkout_2, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_2,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_2.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_3 = checkouts_list[3]
@@ -55,14 +82,23 @@ def test_delete_expired_anonymous_checkouts(checkouts_list, variant, customer_us
not_expired_checkout_3.user = None
not_expired_checkout_3.created_at = now - datetime.timedelta(days=45)
not_expired_checkout_3.last_change = now - datetime.timedelta(days=40)
- not_expired_checkout_3.lines.create(
- checkout=not_expired_checkout_3, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_3,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_3.channel_id, Decimal("11")
+ ),
+ )
)
empty_checkout = checkouts_list[4]
empty_checkout.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout.lines.count() == 0
+ CheckoutLine.objects.bulk_create(lines_to_create)
+
Checkout.objects.bulk_update(
[
expired_anonymous_checkout,
@@ -87,13 +123,26 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
now = timezone.now()
checkout_count = Checkout.objects.count()
+ variant_listings_map = {
+ listing.channel_id: listing.price_amount
+ for listing in variant.channel_listings.all()
+ }
+ lines_to_create = []
+
expired_user_checkout_1 = checkouts_list[0]
expired_user_checkout_1.email = None
expired_user_checkout_1.user = customer_user
expired_user_checkout_1.created_at = now - datetime.timedelta(days=100)
expired_user_checkout_1.last_change = now - datetime.timedelta(days=98)
- expired_user_checkout_1.lines.create(
- checkout=expired_user_checkout_1, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_user_checkout_1,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_user_checkout_1.channel_id, Decimal("11")
+ ),
+ )
)
expired_user_checkout_2 = checkouts_list[1]
@@ -101,8 +150,15 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
expired_user_checkout_2.user = None
expired_user_checkout_2.created_at = now - datetime.timedelta(days=100)
expired_user_checkout_2.last_change = now - datetime.timedelta(days=91)
- expired_user_checkout_2.lines.create(
- checkout=expired_user_checkout_2, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_user_checkout_2,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_user_checkout_2.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_1 = checkouts_list[2]
@@ -110,8 +166,15 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_1.user = None
not_expired_checkout_1.created_at = now - datetime.timedelta(days=35)
not_expired_checkout_1.last_change = now - datetime.timedelta(days=29)
- not_expired_checkout_1.lines.create(
- checkout=not_expired_checkout_1, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_1,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_1.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_2 = checkouts_list[3]
@@ -119,8 +182,15 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_2.user = None
not_expired_checkout_2.created_at = now - datetime.timedelta(days=100)
not_expired_checkout_2.last_change = now - datetime.timedelta(days=60)
- not_expired_checkout_2.lines.create(
- checkout=not_expired_checkout_2, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_2,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_2.channel_id, Decimal("11")
+ ),
+ )
)
not_expired_checkout_3 = checkouts_list[4]
@@ -128,10 +198,17 @@ def test_delete_expired_user_checkouts(checkouts_list, variant, customer_user):
not_expired_checkout_3.user = customer_user
not_expired_checkout_3.created_at = now - datetime.timedelta(days=100)
not_expired_checkout_3.last_change = now - datetime.timedelta(days=89)
- not_expired_checkout_3.lines.create(
- checkout=not_expired_checkout_3, variant=variant, quantity=1
- )
-
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=not_expired_checkout_3,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ not_expired_checkout_3.channel_id, Decimal("11")
+ ),
+ )
+ )
+ CheckoutLine.objects.bulk_create(lines_to_create)
Checkout.objects.bulk_update(
[
expired_user_checkout_1,
@@ -175,7 +252,12 @@ def test_delete_empty_checkouts(checkouts_list, customer_user, variant):
not_empty_checkout = checkouts_list[3]
not_empty_checkout.last_change = now - datetime.timedelta(days=2)
not_empty_checkout.lines.create(
- checkout=not_empty_checkout, variant=variant, quantity=1
+ checkout=not_empty_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=not_empty_checkout.channel_id
+ ).price_amount,
)
Checkout.objects.bulk_update(
@@ -198,26 +280,47 @@ def test_delete_expired_checkouts(checkouts_list, customer_user, variant):
now = timezone.now()
checkout_count = Checkout.objects.count()
+ lines_to_create = []
+ variant_listings_map = {
+ listing.channel_id: listing.price_amount
+ for listing in variant.channel_listings.all()
+ }
+
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
- expired_anonymous_checkout.lines.create(
- checkout=expired_anonymous_checkout, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_anonymous_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_anonymous_checkout.channel_id, Decimal("11")
+ ),
+ )
)
expired_user_checkout = checkouts_list[2]
expired_user_checkout.user = customer_user
expired_user_checkout.created_at = now - datetime.timedelta(days=100)
expired_user_checkout.last_change = now - datetime.timedelta(days=95)
- expired_user_checkout.lines.create(
- checkout=expired_user_checkout, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_user_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_user_checkout.channel_id, Decimal("11")
+ ),
+ )
)
empty_checkout = checkouts_list[4]
empty_checkout.last_change = now - datetime.timedelta(hours=8)
assert empty_checkout.lines.count() == 0
+ CheckoutLine.objects.bulk_create(lines_to_create)
Checkout.objects.bulk_update(
[expired_anonymous_checkout, expired_user_checkout, empty_checkout],
["created_at", "last_change", "email", "user"],
@@ -277,12 +380,25 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
# given
now = timezone.now()
+ lines_to_create = []
+ variant_listings_map = {
+ listing.channel_id: listing.price_amount
+ for listing in variant.channel_listings.all()
+ }
+
expired_anonymous_checkout = checkouts_list[0]
expired_anonymous_checkout.email = None
expired_anonymous_checkout.created_at = now - datetime.timedelta(days=40)
expired_anonymous_checkout.last_change = now - datetime.timedelta(days=35)
- expired_anonymous_checkout.lines.create(
- checkout=expired_anonymous_checkout, variant=variant, quantity=1
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_anonymous_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_anonymous_checkout.channel_id, Decimal("11")
+ ),
+ )
)
expired_anonymous_checkout.payment_transactions.create(
authorized_value=Decimal(authorized),
@@ -314,7 +430,16 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
expired_user_checkout.user = customer_user
expired_user_checkout.created_at = now - datetime.timedelta(days=100)
expired_user_checkout.last_change = now - datetime.timedelta(days=98)
- expired_user_checkout.lines.create(variant=variant, quantity=1)
+ lines_to_create.append(
+ CheckoutLine(
+ checkout=expired_user_checkout,
+ variant=variant,
+ quantity=1,
+ undiscounted_unit_price_amount=variant_listings_map.get(
+ expired_user_checkout.channel_id, Decimal("11")
+ ),
+ )
+ )
expired_user_checkout.payment_transactions.create(
authorized_value=Decimal(authorized),
authorize_pending_value=Decimal(auth_pending),
@@ -326,6 +451,7 @@ def test_delete_expired_checkouts_doesnt_delete_when_transaction_amount_exists(
cancel_pending_value=Decimal(cancel_pending),
)
+ CheckoutLine.objects.bulk_create(lines_to_create)
Checkout.objects.bulk_update(
[expired_anonymous_checkout, expired_user_checkout, empty_checkout],
["created_at", "last_change", "email", "user"],
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 8e0b35fa7d..039eb6b5a9 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -26,19 +26,12 @@ from ..core.utils.translations import get_translation
from ..core.weight import zero_weight
from ..discount import DiscountType, VoucherType
from ..discount.interface import fetch_voucher_info
-from ..discount.models import (
- CheckoutDiscount,
- NotApplicable,
- Voucher,
- VoucherCode,
-)
+from ..discount.models import CheckoutDiscount, NotApplicable, Voucher, VoucherCode
from ..discount.utils.checkout import (
create_checkout_discount_objects_for_order_promotions,
create_checkout_line_discount_objects_for_catalogue_promotions,
)
-from ..discount.utils.promotion import (
- delete_gift_line,
-)
+from ..discount.utils.promotion import delete_gift_line
from ..discount.utils.shared import discount_info_for_logs
from ..discount.utils.voucher import (
get_discounted_lines,
@@ -192,6 +185,13 @@ def add_variant_to_checkout(
if not product_channel_listing or not product_channel_listing.is_published:
raise ProductNotPublished()
+ variant_channel_listing = product_models.ProductVariantChannelListing.objects.get(
+ channel_id=checkout.channel_id, variant_id=variant.id
+ )
+ variant_price_amount = variant.get_base_price(
+ variant_channel_listing, price_override
+ ).amount
+
new_quantity, line = check_variant_in_stock(
checkout,
variant,
@@ -206,6 +206,7 @@ def add_variant_to_checkout(
variant=variant,
quantity=quantity,
price_override=price_override,
+ undiscounted_unit_price_amount=variant_price_amount,
)
return checkout
@@ -221,6 +222,7 @@ def add_variant_to_checkout(
quantity=new_quantity,
currency=checkout.currency,
price_override=price_override,
+ undiscounted_unit_price_amount=variant_price_amount,
)
elif new_quantity > 0:
line.quantity = new_quantity
@@ -253,10 +255,21 @@ def add_variants_to_checkout(
country_code = checkout.get_country()
checkout_lines = checkout.lines.select_related("variant")
-
lines_by_id = {str(line.pk): line for line in checkout_lines}
variants_map = {str(variant.pk): variant for variant in variants}
+ new_variant_ids = set()
+ for line_data in checkout_lines_data:
+ if not line_data.line_id and line_data.variant_id:
+ new_variant_ids.add(line_data.variant_id)
+
+ new_variant_listing_map = {
+ listing.variant_id: listing
+ for listing in product_models.ProductVariantChannelListing.objects.filter(
+ channel_id=channel.id, variant_id__in=new_variant_ids
+ )
+ }
+
to_create: list[CheckoutLine] = []
to_update: list[CheckoutLine] = []
to_delete: list[CheckoutLine] = []
@@ -268,7 +281,9 @@ def add_variants_to_checkout(
_append_line_to_delete(to_delete, line_data, line)
else:
variant = variants_map[line_data.variant_id]
- _append_line_to_create(to_create, checkout, variant, line_data, line)
+ _append_line_to_create(
+ to_create, checkout, variant, line_data, line, new_variant_listing_map
+ )
if to_delete:
CheckoutLine.objects.filter(pk__in=[line.pk for line in to_delete]).delete()
@@ -336,15 +351,26 @@ def _append_line_to_delete(to_delete, line_data, line):
to_delete.append(line)
-def _append_line_to_create(to_create, checkout, variant, line_data, line):
+def _append_line_to_create(
+ to_create,
+ checkout,
+ variant,
+ line_data,
+ line,
+ new_variant_listing_map: dict[int, "product_models.ProductVariantChannelListing"],
+):
if line is None:
if line_data.quantity > 0:
+ variant_price_amount = variant.get_base_price(
+ new_variant_listing_map.get(variant.id), line_data.custom_price
+ ).amount
checkout_line = CheckoutLine(
checkout=checkout,
variant=variant,
quantity=line_data.quantity,
currency=checkout.currency,
price_override=line_data.custom_price,
+ undiscounted_unit_price_amount=variant_price_amount,
)
if line_data.metadata_list:
checkout_line.store_value_in_metadata(
@@ -479,7 +505,7 @@ def get_base_lines_prices(
):
"""Get base total price of checkout lines without voucher discount applied."""
return [
- line_info.channel_listing.discounted_price
+ line_info.variant_discounted_price
for line_info in lines
for i in range(line_info.line.quantity)
]
@@ -1120,14 +1146,31 @@ def checkout_info_for_logs(
"price_override": line_info.line.price_override,
"total_price_net_amount": line_info.line.total_price_net_amount,
"total_price_gross_amount": line_info.line.total_price_gross_amount,
- "variant_listing_price": line_info.channel_listing.price_amount,
- "variant_listing_discounted_price": line_info.channel_listing.discounted_price_amount,
- "product_listing_discounted_price": line_info.product.channel_listings.get(
- channel=channel
- ).discounted_price_amount,
- "product_discounted_price_dirty": line_info.product.channel_listings.get(
- channel=channel
- ).discounted_price_dirty,
+ "variant_listing_price": (
+ line_info.channel_listing.price_amount
+ if line_info.channel_listing
+ else None
+ ),
+ "variant_listing_discounted_price": (
+ line_info.channel_listing.discounted_price_amount
+ if line_info.channel_listing
+ else None
+ ),
+ "undiscounted_unit_price_amount": line_info.line.undiscounted_unit_price_amount,
+ "product_listing_discounted_price": (
+ line_info.product.channel_listings.get(
+ channel=channel
+ ).discounted_price_amount
+ if line_info.product.channel_listings
+ else None
+ ),
+ "product_discounted_price_dirty": (
+ line_info.product.channel_listings.get(
+ channel=channel
+ ).discounted_price_dirty
+ if line_info.product.channel_listings
+ else None
+ ),
"discounts": discount_info_for_logs(line_info.discounts),
}
for line_info in checkout_lines_info
diff --git a/saleor/core/pricing/interface.py b/saleor/core/pricing/interface.py
index 3718e01d38..5b32023e7c 100644
--- a/saleor/core/pricing/interface.py
+++ b/saleor/core/pricing/interface.py
@@ -26,13 +26,17 @@ class LineInfo:
product: Optional["Product"]
product_type: Optional["ProductType"]
collections: list["Collection"]
- channel_listing: "ProductVariantChannelListing"
+ channel_listing: Optional["ProductVariantChannelListing"]
channel: "Channel"
discounts: Iterable[Union["OrderLineDiscount", "CheckoutLineDiscount"]]
rules_info: list["VariantPromotionRuleInfo"]
voucher: Optional["Voucher"]
voucher_code: Optional[str]
+ @property
+ def variant_discounted_price(self):
+ raise NotImplementedError
+
def get_promotion_discounts(
self,
):
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index 4cfed03862..f9b293f3df 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -55,7 +55,7 @@ class VariantPromotionRuleInfo(NamedTuple):
def fetch_variant_rules_info(
- variant_channel_listing: "ProductVariantChannelListing",
+ variant_channel_listing: Optional["ProductVariantChannelListing"],
translation_language_code: str,
) -> list[VariantPromotionRuleInfo]:
listings_rules = (
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 107adf1170..36f145b9b8 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -183,6 +183,12 @@ def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
for line_info in lines_info:
line = line_info.line
+ # if channel_listing is not present, we can't close the checkout. User needs to
+ # remove the line for the checkout first. Until that moment, we return the same
+ # price as we did when listing was present - including line discount.
+ if isinstance(line_info, CheckoutLineInfo) and not line_info.channel_listing:
+ continue
+
# get the existing catalogue discount for the line
discount_to_update = None
if discounts_to_update := line_info.get_catalogue_discounts():
@@ -517,8 +523,11 @@ def delete_gift_line(
lines_info.remove(gift_line_info) # type: ignore[arg-type]
-def create_gift_line(order_or_checkout: Union[Checkout, Order], variant_id: int):
- defaults = _get_defaults_for_gift_line(order_or_checkout, variant_id)
+def create_gift_line(
+ order_or_checkout: Union[Checkout, Order],
+ gift_listing: "ProductVariantChannelListing",
+):
+ defaults = _get_defaults_for_gift_line(order_or_checkout, gift_listing)
line, created = order_or_checkout.lines.get_or_create(
is_gift=True, defaults=defaults
)
@@ -535,13 +544,16 @@ def create_gift_line(order_or_checkout: Union[Checkout, Order], variant_id: int)
def _get_defaults_for_gift_line(
- order_or_checkout: Union[Checkout, Order], variant_id: int
+ order_or_checkout: Union[Checkout, Order],
+ gift_listing: "ProductVariantChannelListing",
):
+ variant_id = gift_listing.variant_id
if isinstance(order_or_checkout, Checkout):
return {
"variant_id": variant_id,
"quantity": 1,
"currency": order_or_checkout.currency,
+ "undiscounted_unit_price_amount": gift_listing.price_amount,
}
variant = (
ProductVariant.objects.filter(id=variant_id)
@@ -884,9 +896,7 @@ def _handle_gift_reward(
else OrderLineDiscount
)
with transaction.atomic():
- line, line_created = create_gift_line(
- order_or_checkout, gift_listing.variant_id
- )
+ line, line_created = create_gift_line(order_or_checkout, gift_listing)
(
line_discount,
discount_created,
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index d8dc1fa419..78de39601a 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -11,10 +11,7 @@ from ...core.db.connection import allow_writer
from ...core.taxes import zero_money
from ...core.utils.promo_code import InvalidPromoCode
from ...order.models import Order
-from .. import (
- DiscountType,
- VoucherType,
-)
+from .. import DiscountType, VoucherType
from ..models import (
DiscountValueType,
NotApplicable,
@@ -230,9 +227,7 @@ def _get_the_cheapest_line(
) -> Optional["LineInfo"]:
if not lines_info:
return None
- return min(
- lines_info, key=lambda line_info: line_info.channel_listing.discounted_price
- )
+ return min(lines_info, key=lambda line_info: line_info.variant_discounted_price)
def validate_voucher_for_checkout(
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 0294dafd7a..55823b1666 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -4,13 +4,7 @@ from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass
from decimal import Decimal
-from typing import (
- TYPE_CHECKING,
- Any,
- Optional,
- Union,
- cast,
-)
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
import graphene
from django.conf import settings
@@ -569,7 +563,7 @@ def apply_gift_reward_if_applicable_on_checkout_creation(
return
with transaction.atomic():
- line, _line_created = create_gift_line(checkout, gift_listing.variant_id)
+ line, _line_created = create_gift_line(checkout, gift_listing)
CheckoutLineDiscount.objects.create(
type=DiscountType.ORDER_PROMOTION,
line=line,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 683c2b7f2a..65aaeef960 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -417,7 +417,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(74):
+ with django_assert_num_queries(75):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -435,7 +435,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(74):
+ with django_assert_num_queries(75):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -567,7 +567,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(79):
+ with django_assert_num_queries(80):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -1083,7 +1083,7 @@ def test_add_checkout_lines_with_reservations(
user_api_client.ensure_access_token()
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(94):
+ with django_assert_num_queries(95):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1096,7 +1096,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(94):
+ with django_assert_num_queries(95):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1147,7 +1147,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(86):
+ with django_assert_num_queries(87):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1233,7 +1233,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(86):
+ with django_assert_num_queries(87):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1269,7 +1269,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(89):
+ with django_assert_num_queries(90):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1304,7 +1304,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(115):
+ with django_assert_num_queries(116):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
index 578094c895..88cafe6e82 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
@@ -72,6 +72,42 @@ def test_checkout_billing_address_update_by_id(
assert checkout.billing_address.validation_skipped is False
+def test_checkout_billing_address_update_when_variant_without_listing(
+ user_api_client, checkout_with_item, graphql_address_data
+):
+ checkout = checkout_with_item
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+ assert checkout.shipping_address is None
+
+ query = MUTATION_CHECKOUT_BILLING_ADDRESS_UPDATE
+ billing_address = graphql_address_data
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "billingAddress": billing_address,
+ }
+
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutBillingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.billing_address is not None
+ assert checkout.billing_address.first_name == billing_address["firstName"]
+ assert checkout.billing_address.last_name == billing_address["lastName"]
+ assert (
+ checkout.billing_address.street_address_1 == billing_address["streetAddress1"]
+ )
+ assert (
+ checkout.billing_address.street_address_2 == billing_address["streetAddress2"]
+ )
+ assert checkout.billing_address.postal_code == billing_address["postalCode"]
+ assert checkout.billing_address.country == billing_address["country"]
+ assert checkout.billing_address.city == billing_address["city"].upper()
+ assert checkout.billing_address.validation_skipped is False
+
+
def test_checkout_billing_address_update_by_id_without_required_fields(
user_api_client, checkout_with_item, graphql_address_data
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index e9eea36359..9f7518712a 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -811,6 +811,39 @@ def test_checkout_complete_with_variant_without_price(
assert not checkout.completing_started_at
+def test_checkout_complete_with_variant_without_channel_listing(
+ 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.channel_listings.filter(channel=checkout.channel).delete()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", checkout_line_variant.pk)
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ content = get_graphql_content(response)
+ errors = content["data"]["checkoutComplete"]["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [variant_id]
+ checkout.refresh_from_db()
+ assert not checkout.completing_started_at
+
+
@patch("saleor.order.calculations._recalculate_with_plugins")
@patch("saleor.plugins.manager.PluginsManager.order_confirmed")
def test_checkout_complete_requires_confirmation(
@@ -3010,6 +3043,9 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
other_checkout_line = other_checkout.lines.create(
variant=checkout_line.variant,
quantity=quantity_available,
+ undiscounted_unit_price_amount=checkout_line.variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 72bdc044e5..e162c89c31 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -1145,6 +1145,45 @@ def test_checkout_with_variant_without_price(
assert errors[0]["variants"] == [variant_id]
+def test_checkout_with_variant_without_channel_listing(
+ site_settings,
+ user_api_client,
+ checkout_with_item,
+ gift_card,
+ address,
+ shipping_method,
+ transaction_events_generator,
+ transaction_item_generator,
+):
+ # given
+ checkout = prepare_checkout_for_test(
+ checkout_with_item,
+ address,
+ address,
+ shipping_method,
+ transaction_item_generator,
+ transaction_events_generator,
+ )
+
+ checkout_line = checkout.lines.first()
+ checkout_line_variant = checkout_line.variant
+ checkout_line_variant.channel_listings.filter(channel=checkout.channel).delete()
+
+ variant_id = to_global_id_or_none(checkout_line_variant)
+ redirect_url = "https://www.example.com"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["checkoutComplete"]["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [variant_id]
+
+
def test_checkout_complete_with_inactive_channel(
user_api_client,
checkout_with_gift_card,
@@ -3271,6 +3310,9 @@ def test_checkout_complete_insufficient_stock_reserved_by_other_user(
other_checkout_line = other_checkout.lines.create(
variant=checkout_line.variant,
quantity=quantity_available,
+ undiscounted_unit_price_amount=checkout_line.variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 147358a680..0e6732dbe8 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -205,6 +205,32 @@ def test_checkout_create_with_unavailable_variant(
assert error["variants"] == [variant_id]
+def test_checkout_create_with_variant_without_channel_listing(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ variant = stock.product_variant
+ variant.channel_listings.filter(channel=channel_USD).delete()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["errors"][0]
+
+ assert error["field"] == "lines"
+ assert error["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert error["variants"] == [variant_id]
+
+
def test_checkout_create_with_malicious_variant_id(
api_client, stock, graphql_address_data, channel_USD
):
@@ -1756,6 +1782,9 @@ def test_checkout_create_check_lines_quantity_against_reservations(
checkout_line = checkout.lines.create(
variant=variant,
quantity=3,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=checkout_line,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
index 780ad6da9f..79f83beb70 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py
@@ -314,6 +314,58 @@ def test_checkout_create_from_order_variant_not_found(
assert unavailable_variant["variantId"] == first_line.product_variant_id
+def test_checkout_create_from_order_variant_without_channel_listing(
+ user_api_client, order_with_lines
+):
+ # given
+ order_with_lines.user = user_api_client.user
+ order_with_lines.save()
+ Stock.objects.update(quantity=10)
+ first_line = order_with_lines.lines.first()
+ first_line.variant.channel_listings.all().delete()
+
+ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables
+ )
+
+ # then
+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCreateFromOrder"]
+ checkout = Checkout.objects.get()
+ checkout_lines = checkout.lines.all()
+ assert checkout.user == order_with_lines.user
+ assert checkout.email == order_with_lines.user_email
+ checkout_lines_from_response = data["checkout"]["lines"]
+ assert (
+ len(checkout_lines_from_response)
+ == checkout_lines.count()
+ == len(order_lines_map) - 1
+ )
+ checkout_lines_from_response_map = {
+ line["variant"]["id"]: line for line in checkout_lines_from_response
+ }
+
+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)
+ _assert_checkout_lines(
+ order_lines_map, checkout_lines, checkout_lines_from_response_map
+ )
+
+ error_codes = CheckoutCreateFromOrderUnavailableVariantErrorCode
+ assert len(data["unavailableVariants"]) == 1
+ unavailable_variant = data["unavailableVariants"][0]
+ assert (
+ unavailable_variant["code"] == error_codes.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert unavailable_variant["lineId"] == graphene.Node.to_global_id(
+ "OrderLine", first_line.pk
+ )
+ assert unavailable_variant["variantId"] == first_line.product_variant_id
+
+
def test_checkout_create_from_order_variant_not_available_in_channel(
user_api_client, order_with_lines
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
index fc6b928f7d..a45ba34c4b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py
@@ -53,6 +53,40 @@ def test_checkout_customer_attach(
assert checkout.last_change != previous_last_change
+def test_checkout_customer_attach_when_variant_without_channel_listing(
+ user_api_client, checkout_with_item, customer_user2, permission_impersonate_user
+):
+ # given
+ checkout = checkout_with_item
+ checkout.email = "[email protected]"
+ checkout.save()
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ assert checkout.user is None
+ previous_last_change = checkout.last_change
+
+ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH
+ customer_id = graphene.Node.to_global_id("User", customer_user2.pk)
+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}
+
+ # when
+ response = user_api_client.post_graphql(
+ query, variables, permissions=[permission_impersonate_user]
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutCustomerAttach"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.user == customer_user2
+ assert checkout.email == customer_user2.email
+ assert checkout.last_change != previous_last_change
+
+
def test_checkout_customer_attach_with_customer_id_same_as_in_request(
user_api_client, checkout_with_item, customer_user, permission_impersonate_user
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
index 903bcef6d2..bcee710a83 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
@@ -53,6 +53,44 @@ def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_
assert_no_permission(response)
+def test_checkout_customer_detach_when_variant_without_listing(
+ user_api_client, checkout_with_item, customer_user
+):
+ # given
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.save(update_fields=["user"])
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ previous_last_change = checkout.last_change
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCustomerDetach"]
+
+ # then
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.user is None
+ assert checkout.last_change != previous_last_change
+
+ # Mutation should fail when user calling it doesn't own the checkout.
+ other_user = User.objects.create_user("[email protected]", "password")
+ checkout.user = other_user
+ checkout.save()
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables
+ )
+ assert_no_permission(response)
+
+
def test_checkout_customer_detach_by_app(
app_api_client, checkout_with_item, customer_user, permission_impersonate_user
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
index 151b1e52ea..3bcbc5854d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_note_update.py
@@ -56,6 +56,36 @@ def test_checkout_customer_note_update(user_api_client, checkout_with_item):
assert checkout.last_change != previous_last_change
+def test_checkout_customer_note_update_when_variant_without_listing(
+ user_api_client, checkout_with_item
+):
+ # given
+ checkout = checkout_with_item
+ checkout.note = ""
+ checkout.save(update_fields=["note"])
+ previous_last_change = checkout.last_change
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ customer_note = "New customer note value"
+ variables = {"id": to_global_id_or_none(checkout), "customerNote": customer_note}
+
+ # when
+ response = user_api_client.post_graphql(
+ CHECKOUT_CUSTOMER_NOTE_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCustomerNoteUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.note == customer_note
+ assert data["checkout"]["customerNote"] == data["checkout"]["note"] == customer_note
+ assert checkout.last_change != previous_last_change
+
+
def test_with_active_problems_flow(api_client, checkout_with_problems):
# given
channel = checkout_with_problems.channel
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index 98100a915c..4b31434c77 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -136,6 +136,43 @@ def test_checkout_delivery_method_update(
assert checkout.collection_point is None
+ ("delivery_method", "node_name", "attribute_name"),
+ [
+ ("warehouse", "Warehouse", "collection_point"),
+ ("shipping_method", "ShippingMethod", "shipping_method"),
+ ],
+ indirect=("delivery_method",),
+)
+def test_checkout_delivery_method_update_when_variant_without_channel_listing(
+ api_client,
+ delivery_method,
+ node_name,
+ attribute_name,
+ checkout_with_item_for_cc,
+):
+ # given
+ line = checkout_with_item_for_cc.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ checkout = checkout_with_item_for_cc
+
+ query = MUTATION_UPDATE_DELIVERY_METHOD
+
+ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)
+
+ response = api_client.post_graphql(
+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}
+ )
+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]
+
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert checkout.shipping_method is None
+
+
@pytest.mark.parametrize("is_valid_delivery_method", [True, False])
@pytest.mark.parametrize(
("delivery_method", "node_name", "attribute_name"),
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
index de5c64a716..ff89cfce48 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py
@@ -48,6 +48,33 @@ def test_checkout_email_update(user_api_client, checkout_with_item):
assert checkout.last_change != previous_last_change
+def test_checkout_email_update_when_variant_without_channel_listing(
+ user_api_client, checkout_with_item
+):
+ # given
+ checkout = checkout_with_item
+ checkout.email = None
+ checkout.save(update_fields=["email"])
+ previous_last_change = checkout.last_change
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ email = "[email protected]"
+ variables = {"id": to_global_id_or_none(checkout), "email": email}
+
+ # when
+ response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutEmailUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.email == email
+ assert checkout.last_change != previous_last_change
+
+
def test_checkout_email_update_validation(user_api_client, checkout_with_item):
variables = {"id": to_global_id_or_none(checkout_with_item), "email": ""}
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
index 49e20a51d2..140940ccc2 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_language_code_update.py
@@ -48,6 +48,36 @@ def test_checkout_update_language_code(
assert checkout.last_change != previous_last_change
+def test_checkout_update_language_code_when_variant_without_channel_listing(
+ user_api_client,
+ checkout_with_gift_card,
+):
+ # given
+ language_code = "PL"
+ checkout = checkout_with_gift_card
+ previous_last_change = checkout.last_change
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ variables = {"id": to_global_id_or_none(checkout), "languageCode": language_code}
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLanguageCodeUpdate"]
+ assert not data["errors"]
+
+ assert data["checkout"]["languageCode"] == language_code
+ checkout.refresh_from_db()
+ assert checkout.language_code == language_code.lower()
+ assert checkout.last_change != previous_last_change
+
+
def test_with_active_problems_flow(api_client, checkout_with_problems):
# given
channel = checkout_with_problems.channel
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index 23e87fb974..2172d89a11 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -88,6 +88,103 @@ def test_checkout_line_delete(
assert mocked_invalidate_checkout.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_line_delete."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_line_delete_when_variant_without_channel_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_line_with_reservation_in_many_stocks,
+):
+ # given
+ assert Reservation.objects.count() == 2
+ checkout = checkout_line_with_reservation_in_many_stocks.checkout
+ previous_last_change = checkout.last_change
+ lines, _ = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+ assert line.quantity == 3
+
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+
+ variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLineDelete"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 0
+ assert calculate_checkout_quantity(lines) == 0
+ assert Reservation.objects.count() == 0
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
+ "saleor.graphql.checkout.mutations.checkout_line_delete."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_line_delete_when_checkout_has_variant_without_channel_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ previous_last_change = checkout.last_change
+
+ lines, _ = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 4
+ assert checkout.lines.count() == 4
+ line_without_listing = checkout.lines.last()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ line = checkout.lines.first()
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+
+ variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLineDelete"]
+ assert not data["errors"]
+
+ assert checkout.lines.count() == 3
+ checkout.refresh_from_db()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
def test_checkout_lines_delete_with_not_applicable_voucher(
user_api_client, checkout_with_item, voucher, channel_USD
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index ab0f2f8858..0c0b719e4f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -131,6 +131,63 @@ def test_checkout_lines_add(
assert mocked_invalidate_checkout.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_lines_add_when_checkout_has_line_without_variant_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_item,
+ stock,
+):
+ # given
+ variant = stock.product_variant
+ checkout = checkout_with_item
+
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ lines, _ = fetch_checkout_lines(checkout)
+ assert calculate_checkout_quantity(lines) == 3
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ previous_last_change = checkout.last_change
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ line = checkout.lines.last()
+ assert line.variant == variant
+ assert line.quantity == 1
+ assert calculate_checkout_quantity(lines) == 4
+ assert not Reservation.objects.exists()
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
"update_checkout_shipping_method_if_invalid",
@@ -1352,6 +1409,34 @@ def test_checkout_lines_add_with_unavailable_variant(
assert errors[0]["variants"] == [variant_id]
+def test_checkout_lines_add_variant_without_channel_listing(
+ user_api_client, checkout_with_item, stock
+):
+ # given
+ variant = stock.product_variant
+ variant.channel_listings.filter(channel=checkout_with_item.channel).delete()
+ checkout = checkout_with_item
+ line = checkout.lines.first()
+ assert line.quantity == 3
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["checkoutLinesAdd"]["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [variant_id]
+
+
def test_checkout_lines_add_with_insufficient_stock(
user_api_client, checkout_with_item, stock
):
@@ -1387,6 +1472,9 @@ def test_checkout_lines_add_with_reserved_insufficient_stock(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=quantity_available - 1,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
index 461c2eef90..8b56ebb120 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
@@ -84,6 +84,109 @@ def test_checkout_lines_delete(
assert mocked_invalidate_checkout.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_lines_delete."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_lines_delete_when_variant_without_channel_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout_lines_count = checkout.lines.count()
+ previous_last_change = checkout.last_change
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+ second_line = checkout.lines.last()
+
+ first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ second_line_id = graphene.Node.to_global_id("CheckoutLine", second_line.pk)
+ lines_list = [first_line_id, second_line_id]
+
+ variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesDelete"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() + len(lines_list) == checkout_lines_count
+ remaining_lines = data["checkout"]["lines"]
+ lines_ids = [line["id"] for line in remaining_lines]
+ assert lines_list not in lines_ids
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
+ "saleor.graphql.checkout.mutations.checkout_lines_delete."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_lines_delete_when_checkout_has_variant_without_channel_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ checkout_lines_count = checkout.lines.count()
+ previous_last_change = checkout.last_change
+
+ line = checkout.lines.first()
+
+ line_without_listing = checkout.lines.last()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ lines_list = [
+ first_line_id,
+ ]
+
+ variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesDelete"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() + len(lines_list) == checkout_lines_count
+ remaining_lines = data["checkout"]["lines"]
+ lines_ids = [line["id"] for line in remaining_lines]
+ assert lines_list not in lines_ids
+ manager = get_plugins_manager(allow_replica=False)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
def test_checkout_lines_delete_invalid_checkout_id(
user_api_client, checkout_with_items
):
@@ -184,6 +287,9 @@ def test_checkout_lines_delete_not_associated_with_checkout(
checkout=wrong_checkout,
variant=variant,
quantity=1,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price_amount,
)
line_id = to_global_id_or_none(line)
variables = {"id": to_global_id_or_none(checkout), "linesIds": [line_id]}
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index c672a99e7b..dd542b4b25 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -124,6 +124,67 @@ def test_checkout_lines_update(
assert mocked_invalidate_checkout.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_lines_update_when_checkout_has_variant_without_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_items,
+):
+ # given
+ checkout = checkout_with_items
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 4
+ assert calculate_checkout_quantity(lines) == 4
+
+ line = checkout.lines.first()
+ variant = line.variant
+ assert line.quantity == 1
+
+ line_without_listing = checkout.lines.last()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ previous_last_change = checkout.last_change
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 3}],
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 4
+ line = checkout.lines.first()
+ assert line.variant == variant
+ assert line.quantity == 3
+ assert calculate_checkout_quantity(lines) == 6
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_lines_add."
"update_checkout_shipping_method_if_invalid",
@@ -469,6 +530,9 @@ def test_checkout_lines_update_against_reserved_stock(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=7,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
reservation = Reservation.objects.create(
checkout_line=other_checkout_line,
@@ -1019,6 +1083,34 @@ def test_checkout_lines_update_with_unavailable_variant(
assert checkout.last_change == previous_last_change
+def test_checkout_lines_update_with_variant_without_channel_listing(
+ user_api_client, checkout_with_item
+):
+ checkout = checkout_with_item
+ previous_last_change = checkout.last_change
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ variant = line.variant
+ variant.channel_listings.filter(channel=checkout_with_item.channel).delete()
+ assert line.quantity == 3
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ errors = content["data"]["checkoutLinesUpdate"]["errors"]
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["variants"] == [variant_id]
+ checkout.refresh_from_db()
+ assert checkout.last_change == previous_last_change
+
+
def test_checkout_lines_update_channel_without_shipping_zones(
user_api_client, checkout_with_item
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index bd19dc261f..4934ef9214 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -91,6 +91,37 @@ def test_checkout_remove_voucher_code(
)
+@patch("saleor.plugins.manager.PluginsManager.checkout_updated")
+def test_checkout_remove_voucher_code_when_variant_without_listing(
+ checkout_updated_webhook_mock, api_client, checkout_with_voucher
+):
+ # given
+ line = checkout_with_voucher.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ assert checkout_with_voucher.voucher_code is not None
+ previous_checkout_last_change = checkout_with_voucher.last_change
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_voucher),
+ "promoCode": checkout_with_voucher.voucher_code,
+ }
+
+ # when
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ # then
+ checkout_with_voucher.refresh_from_db()
+ assert not data["errors"]
+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)
+ assert data["checkout"]["voucherCode"] is None
+ assert checkout_with_voucher.voucher_code is None
+ assert checkout_with_voucher.last_change != previous_checkout_last_change
+ checkout_updated_webhook_mock.assert_called_once_with(
+ checkout_with_voucher, webhooks=set()
+ )
+
+
@patch("saleor.plugins.manager.PluginsManager.checkout_updated")
def test_checkout_remove_voucher_code_from_voucher_with_multiple_codes(
checkout_updated_webhook_mock,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
index d732d78883..2b36626df8 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
@@ -145,6 +145,70 @@ def test_checkout_shipping_address_with_metadata_update(
assert mocked_invalidate_checkout.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_shipping_address_update."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+ "saleor.graphql.checkout.mutations.checkout_shipping_address_update."
+ "invalidate_checkout",
+ wraps=invalidate_checkout,
+)
+def test_checkout_shipping_address_when_variant_without_listing(
+ mocked_invalidate_checkout,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
+):
+ # given
+ checkout = checkout_with_item
+ line = checkout.lines.first()
+ line.variant.channel_listings.all().delete()
+
+ assert checkout.shipping_address is None
+ previous_last_change = checkout.last_change
+
+ shipping_address = graphql_address_data
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "shippingAddress": shipping_address,
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_WITH_METADATA_UPDATE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ assert checkout.shipping_address.metadata == {"public": "public_value"}
+
+ assert checkout.shipping_address is not None
+ assert checkout.shipping_address.first_name == shipping_address["firstName"]
+ assert checkout.shipping_address.last_name == shipping_address["lastName"]
+ assert (
+ checkout.shipping_address.street_address_1 == shipping_address["streetAddress1"]
+ )
+ assert (
+ checkout.shipping_address.street_address_2 == shipping_address["streetAddress2"]
+ )
+ assert checkout.shipping_address.postal_code == shipping_address["postalCode"]
+ assert checkout.shipping_address.country == shipping_address["country"]
+ assert checkout.shipping_address.city == shipping_address["city"].upper()
+ assert checkout.shipping_address.validation_skipped is False
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout.call_count == 1
+
+
@mock.patch(
"saleor.graphql.checkout.mutations.checkout_shipping_address_update."
"update_checkout_shipping_method_if_invalid",
@@ -329,6 +393,9 @@ def test_checkout_shipping_address_update_with_reserved_stocks(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=1,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
@@ -386,6 +453,9 @@ def test_checkout_shipping_address_update_against_reserved_stocks(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=3,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 75dcb160a5..5da19ba2cc 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -1408,6 +1408,9 @@ def test_order_from_checkout_on_catalogue_and_gift_promotion(
top_price, variant_id = max(
variant_listings.values_list("discounted_price_amount", "variant")
)
+ variant_listing = [
+ listing for listing in variant_listings if listing.variant_id == variant_id
+ ][0]
# add gift reward
gift_line = CheckoutLine.objects.create(
@@ -1416,6 +1419,7 @@ def test_order_from_checkout_on_catalogue_and_gift_promotion(
variant_id=variant_id,
is_gift=True,
currency="USD",
+ undiscounted_unit_price_amount=variant_listing.price_amount,
)
CheckoutLineDiscount.objects.create(
line=gift_line,
@@ -1621,6 +1625,9 @@ def test_order_from_checkout_insufficient_stock_reserved_by_other_user(
other_checkout_line = other_checkout.lines.create(
variant=checkout_line.variant,
quantity=quantity_available,
+ undiscounted_unit_price_amount=checkout_line.variant.channel_listings.get(
+ channel_id=channel_USD
+ ).price_amount,
)
Reservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 282ed203be..a700320f89 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -20,7 +20,8 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import add_voucher_to_checkout
from ....core.prices import quantize_price
-from ....discount import DiscountValueType, VoucherType
+from ....discount import DiscountType, DiscountValueType, VoucherType
+from ....discount.models import CheckoutLineDiscount
from ....payment import TransactionAction
from ....payment.interface import (
ListStoredPaymentMethodsRequestData,
@@ -1729,55 +1730,134 @@ def test_fetch_checkout_invalid_token(user_api_client, channel_USD, checkout):
QUERY_CHECKOUT_PRICES = """
- query getCheckout($id: ID) {
- checkout(id: $id) {
- displayGrossPrices
- token
- discount {
- amount
- }
- totalPrice {
- currency
- gross {
- amount
- }
- }
- subtotalPrice {
- currency
- gross {
- amount
- }
+query getCheckout($id: ID) {
+ checkout(id: $id) {
+ displayGrossPrices
+ token
+ discount {
+ amount
+ }
+ totalPrice {
+ currency
+ gross {
+ amount
+ }
+ }
+ subtotalPrice {
+ currency
+ gross {
+ amount
+ }
+ }
+ problems {
+ ... on CheckoutLineProblemVariantNotAvailable {
+ __typename
+ line {
+ id
+ }
+ }
+ }
+ lines {
+ id
+ isGift
+ variant {
+ id
+ pricing {
+ onSale
+ price {
+ gross {
+ amount
}
- lines {
- isGift
- variant {
- id
- }
- unitPrice {
- gross {
- amount
- }
- }
- undiscountedUnitPrice {
- amount
- currency
- }
- totalPrice {
- currency
- gross {
- amount
- }
- }
- undiscountedTotalPrice {
- amount
- currency
- }
- }
+ }
+ }
+ }
+ unitPrice {
+ gross {
+ amount
+ }
+ }
+ undiscountedUnitPrice {
+ amount
+ currency
+ }
+ totalPrice {
+ currency
+ gross {
+ amount
}
+ }
+ undiscountedTotalPrice {
+ amount
+ currency
+ }
+ problems {
+ ... on CheckoutLineProblemVariantNotAvailable {
+ __typename
+ }
+ }
}
+ }
+}
"""
+def test_checkout_prices_when_variant_without_listing(
+ user_api_client, checkout_with_line_without_listing
+):
+ # given
+ checkout, line_without_listing = checkout_with_line_without_listing
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert (
+ response_api_line_without_listing["unitPrice"]["gross"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ * line_without_listing.quantity
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ * line_without_listing.quantity
+ )
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices(user_api_client, checkout_with_item):
# given
query = QUERY_CHECKOUT_PRICES
@@ -1892,6 +1972,67 @@ def test_checkout_prices_checkout_with_custom_prices(
)
+def test_checkout_prices_checkout_with_custom_prices_when_variant_without_listing(
+ user_api_client, checkout_with_line_without_listing
+):
+ # given
+ checkout, line_without_listing = checkout_with_line_without_listing
+ price_override = Decimal("20.00")
+ line_without_listing.price_override = price_override
+ line_without_listing.undiscounted_unit_price_amount = price_override
+ line_without_listing.save(
+ update_fields=["price_override", "undiscounted_unit_price_amount"]
+ )
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert (
+ response_api_line_without_listing["unitPrice"]["gross"]["amount"]
+ == price_override
+ )
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == price_override
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == price_override * line_without_listing.quantity
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == price_override * line_without_listing.quantity
+ )
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_sales(user_api_client, checkout_with_item_on_sale):
# given
query = QUERY_CHECKOUT_PRICES
@@ -1959,6 +2100,124 @@ def test_checkout_prices_with_sales(user_api_client, checkout_with_item_on_sale)
assert line_total_price.gross.amount < undiscounted_total_price
+def test_checkout_prices_with_sales_when_variant_without_listing(
+ user_api_client, checkout_with_item, promotion_converted_from_sale
+):
+ # given
+ checkout = checkout_with_item
+
+ line_without_listing = checkout_with_item.lines.first()
+
+ channel = checkout_with_item.channel
+ discount_amount = Decimal("5.0")
+ variant = line_without_listing.variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ predicate = {"variantPredicate": {"ids": [variant_id]}}
+
+ rule = promotion_converted_from_sale.rules.first()
+ rule.catalogue_predicate = predicate
+ rule.reward_value = discount_amount
+ rule.save(update_fields=["catalogue_predicate", "reward_value"])
+ rule.channels.add(channel)
+
+ channel_listing = variant.channel_listings.get(channel=channel)
+ channel_listing.discounted_price_amount = (
+ channel_listing.price_amount - discount_amount
+ )
+ channel_listing.save(update_fields=["discounted_price_amount"])
+
+ CheckoutLineDiscount.objects.create(
+ line=line_without_listing,
+ promotion_rule=rule,
+ type=DiscountType.PROMOTION,
+ value_type=rule.reward_value_type,
+ value=discount_amount,
+ amount_value=discount_amount * line_without_listing.quantity,
+ currency=channel.currency_code,
+ )
+
+ checkout.price_expiration = timezone.now()
+ checkout.save()
+
+ checkout = checkout_with_item
+
+ line_without_listing.variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).delete()
+
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout_with_item)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ line_info = [line for line in lines if line.line.pk == line_without_listing.pk][0]
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ line_unit_price = calculations.checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert (
+ response_api_line_without_listing["unitPrice"]["gross"]["amount"]
+ == line_unit_price.gross.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ * line_without_listing.quantity
+ )
+ assert line_unit_price.gross < line_without_listing.undiscounted_unit_price
+ assert (
+ line_total_price.gross
+ < line_without_listing.undiscounted_unit_price * line_without_listing.quantity
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_promotion(
user_api_client, checkout_with_item_on_promotion
):
@@ -2028,6 +2287,91 @@ def test_checkout_prices_with_promotion(
assert line_total_price.gross.amount < undiscounted_total_price
+def test_checkout_prices_with_promotion_when_variant_without_listing(
+ user_api_client, checkout_with_item_on_promotion
+):
+ # given
+ query = QUERY_CHECKOUT_PRICES
+
+ checkout = checkout_with_item_on_promotion
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).delete()
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ line_info = [line for line in lines if line.line.pk == line_without_listing.pk][0]
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ line_unit_price = calculations.checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert (
+ response_api_line_without_listing["unitPrice"]["gross"]["amount"]
+ == line_unit_price.gross.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ * line_without_listing.quantity
+ )
+ assert line_unit_price.gross < line_without_listing.undiscounted_unit_price
+ assert (
+ line_total_price.gross
+ < line_without_listing.undiscounted_unit_price * line_without_listing.quantity
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_order_promotion(
user_api_client, checkout_with_item_and_order_discount
):
@@ -2079,23 +2423,21 @@ def test_checkout_prices_with_order_promotion(
assert data["lines"][0]["undiscountedTotalPrice"]["amount"] == subtotal_price.amount
-def test_checkout_prices_with_gift_promotion(
- user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule
+def test_checkout_prices_with_order_promotion_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_order_discount
):
# given
query = QUERY_CHECKOUT_PRICES
- checkout = checkout_with_item_and_gift_promotion
- variants = gift_promotion_rule.gifts.all()
- variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
- top_price, variant_id = max(
- variant_listings.values_list("discounted_price_amount", "variant")
- )
-
+ checkout = checkout_with_item_and_order_discount
variables = {"id": to_global_id_or_none(checkout)}
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).delete()
+
+ checkout.price_expiration = timezone.now()
+ checkout.save()
# when
response = user_api_client.post_graphql(query, variables)
@@ -2103,15 +2445,102 @@ def test_checkout_prices_with_gift_promotion(
data = content["data"]["checkout"]
# then
- assert data["token"] == str(checkout.token)
- assert len(data["lines"]) == checkout.lines.count()
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
- line = checkout.lines.get(is_gift=False)
- variant = line.variant
- variant_listing = variant.channel_listings.get(channel=checkout.channel)
- unit_price = variant.get_price(variant_listing)
- subtotal_price = unit_price * line.quantity
- shipping_price = base_calculations.base_checkout_delivery_price(
+ line_info = [line for line in lines if line.line.pk == line_without_listing.pk][0]
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ line_unit_price = calculations.checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert str(
+ response_api_line_without_listing["unitPrice"]["gross"]["amount"]
+ ) == str(round(line_unit_price.gross.amount, 2))
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == line_without_listing.undiscounted_unit_price_amount
+ * line_without_listing.quantity
+ )
+ assert line_unit_price.gross < line_without_listing.undiscounted_unit_price
+ assert (
+ line_total_price.gross
+ < line_without_listing.undiscounted_unit_price * line_without_listing.quantity
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
+def test_checkout_prices_with_gift_promotion(
+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule
+):
+ # given
+ query = QUERY_CHECKOUT_PRICES
+ checkout = checkout_with_item_and_gift_promotion
+ variants = gift_promotion_rule.gifts.all()
+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
+ top_price, variant_id = max(
+ variant_listings.values_list("discounted_price_amount", "variant")
+ )
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+
+ line = checkout.lines.get(is_gift=False)
+ variant = line.variant
+ variant_listing = variant.channel_listings.get(channel=checkout.channel)
+ unit_price = variant.get_price(variant_listing)
+ subtotal_price = unit_price * line.quantity
+ shipping_price = base_calculations.base_checkout_delivery_price(
checkout_info, lines
)
total_price = subtotal_price + shipping_price
@@ -2141,6 +2570,77 @@ def test_checkout_prices_with_gift_promotion(
)
+def test_checkout_prices_with_gift_promotion_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule
+):
+ # given
+ query = QUERY_CHECKOUT_PRICES
+ checkout = checkout_with_item_and_gift_promotion
+ line_without_listing = checkout.lines.get(is_gift=True)
+
+ variants = gift_promotion_rule.gifts.all()
+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
+ top_price, variant_id = max(
+ variant_listings.values_list("discounted_price_amount", "variant")
+ )
+
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ line_info = [line for line in lines if line.line.pk == line_without_listing.pk][0]
+
+ # Calculate the prices based on the existing gift line
+ calculations.checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+
+ variant_listings.delete()
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ assert response_api_line_without_listing["variant"]["pricing"] is None
+ assert response_api_line_without_listing["unitPrice"]["gross"]["amount"] == 0
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == top_price
+ )
+ assert response_api_line_without_listing["totalPrice"]["gross"]["amount"] == 0
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == top_price
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_display_gross_prices_use_default(user_api_client, checkout_with_item):
# given
variables = {"id": to_global_id_or_none(checkout_with_item)}
@@ -2241,6 +2741,88 @@ def test_checkout_prices_with_specific_voucher(
)
+def test_checkout_prices_with_specific_voucher_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_voucher_specific_products
+):
+ # given
+ checkout = checkout_with_item_and_voucher_specific_products
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.all().delete()
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+
+ total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["totalPrice"]["gross"]["amount"] == total.gross.amount
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == subtotal.gross.amount
+ line_info = lines[0]
+ assert line_info.line.quantity > 0
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ assert response_api_line_without_listing["unitPrice"]["gross"]["amount"] == round(
+ line_total_price.gross.amount / line_info.line.quantity, 2
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ undiscounted_unit_price = line_info.undiscounted_unit_price
+ undiscounted_line_total = undiscounted_unit_price * line_info.line.quantity
+ assert line_total_price.gross < undiscounted_line_total
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == undiscounted_unit_price.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == undiscounted_line_total.amount
+ )
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_voucher_once_per_order(
user_api_client, checkout_with_item_and_voucher_once_per_order
):
@@ -2305,6 +2887,95 @@ def test_checkout_prices_with_voucher_once_per_order(
)
+def test_checkout_prices_with_voucher_once_per_order_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_voucher_once_per_order
+):
+ # given
+ checkout = checkout_with_item_and_voucher_once_per_order
+
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
+ line_info = lines[0]
+ assert line_info.line.quantity > 0
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ assert response_api_line_without_listing["unitPrice"]["gross"]["amount"] == float(
+ quantize_price(
+ line_total_price.gross.amount / line_info.line.quantity, checkout.currency
+ )
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ undiscounted_unit_price = line_info.undiscounted_unit_price
+ undiscounted_line_total = undiscounted_unit_price * line_info.line.quantity
+ assert line_total_price.gross < undiscounted_line_total
+
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == undiscounted_unit_price.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == undiscounted_unit_price.amount * line_info.line.quantity
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_voucher(user_api_client, checkout_with_item_and_voucher):
# given
checkout = checkout_with_item_and_voucher
@@ -2367,6 +3038,95 @@ def test_checkout_prices_with_voucher(user_api_client, checkout_with_item_and_vo
)
+def test_checkout_prices_with_voucher_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_voucher
+):
+ # given
+ checkout = checkout_with_item_and_voucher
+
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["totalPrice"]["gross"]["amount"] == total.gross.amount
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == subtotal.gross.amount
+ line_info = lines[0]
+ assert line_info.line.quantity > 0
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ assert response_api_line_without_listing["unitPrice"]["gross"]["amount"] == float(
+ quantize_price(
+ line_total_price.gross.amount / line_info.line.quantity, checkout.currency
+ )
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ undiscounted_unit_price = line_info.undiscounted_unit_price
+ undiscounted_line_total = undiscounted_unit_price * line_info.line.quantity
+
+ assert line_total_price.gross < undiscounted_line_total
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == undiscounted_unit_price.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == undiscounted_unit_price.amount * line_info.line.quantity
+ )
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
def test_checkout_prices_with_voucher_code_that_doesnt_exist(
user_api_client, checkout_with_item_and_voucher, voucher
):
@@ -2432,6 +3192,95 @@ def test_checkout_prices_with_voucher_code_that_doesnt_exist(
)
+def test_checkout_prices_voucher_code_that_doesnt_exist_when_variant_without_listing(
+ user_api_client, checkout_with_item_and_voucher, voucher
+):
+ # given
+ checkout = checkout_with_item_and_voucher
+
+ line_without_listing = checkout.lines.first()
+ line_without_listing.variant.channel_listings.all().delete()
+
+ query = QUERY_CHECKOUT_PRICES
+ variables = {"id": to_global_id_or_none(checkout)}
+ voucher.delete()
+
+ # when
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ # then
+ assert data["token"] == str(checkout.token)
+ assert len(data["lines"]) == checkout.lines.count()
+
+ response_api_line_without_listing = [
+ line_data
+ for line_data in data["lines"]
+ if line_data["id"] == to_global_id_or_none(line_without_listing)
+ ][0]
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ total = calculations.checkout_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["totalPrice"]["gross"]["amount"] == (total.gross.amount)
+ subtotal = calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=checkout_info.shipping_address,
+ )
+ assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
+ line_info = lines[0]
+ assert line_info.line.quantity > 0
+ line_total_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ )
+ assert response_api_line_without_listing["unitPrice"]["gross"]["amount"] == float(
+ quantize_price(
+ line_total_price.gross.amount / line_info.line.quantity, checkout.currency
+ )
+ )
+ assert (
+ response_api_line_without_listing["totalPrice"]["gross"]["amount"]
+ == line_total_price.gross.amount
+ )
+ undiscounted_unit_price = line_info.undiscounted_unit_price
+
+ assert (
+ response_api_line_without_listing["undiscountedUnitPrice"]["amount"]
+ == undiscounted_unit_price.amount
+ )
+ assert (
+ response_api_line_without_listing["undiscountedTotalPrice"]["amount"]
+ == undiscounted_unit_price.amount * line_info.line.quantity
+ )
+ assert undiscounted_unit_price * line_info.line.quantity == line_total_price.gross
+
+ checkout_problems = data["problems"]
+ assert len(checkout_problems) == 1
+ assert (
+ checkout_problems[0]["__typename"] == "CheckoutLineProblemVariantNotAvailable"
+ )
+ assert checkout_problems[0]["line"]["id"] == to_global_id_or_none(
+ line_without_listing
+ )
+ assert len(response_api_line_without_listing["problems"]) == 1
+ assert (
+ response_api_line_without_listing["problems"][0]["__typename"]
+ == "CheckoutLineProblemVariantNotAvailable"
+ )
+
+
CHECKOUTS_QUERY = """
{
checkouts(first: 20) {
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index 2f484a020a..b68a0da01b 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -318,8 +318,6 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
).exists():
product_channel_listing.delete()
- cls.perform_checkout_lines_delete(variants, [channel.id])
-
@classmethod
def perform_checkout_lines_delete(cls, variants, channel_id):
lines_id_and_checkout_id = list(
diff --git a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
index 228c3b7e22..607f6c054c 100644
--- a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
@@ -1292,7 +1292,7 @@ def test_product_channel_listing_remove_variant_is_None_as_app(
assert len(variant.channel_listings.all()) == 2
-def test_product_channel_listing_remove_variant_removes_checkout_lines(
+def test_product_channel_listing_remove_variant_do_not_removes_checkout_lines(
staff_api_client,
product,
permission_manage_products,
@@ -1338,7 +1338,7 @@ def test_product_channel_listing_remove_variant_removes_checkout_lines(
assert len(variant.channel_listings.all()) == 1
- assert not checkout.lines.all().exists()
+ assert checkout.lines.all().exists()
def test_product_channel_listing_add_variant_duplicated_ids_in_add_and_remove(
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 891129d6e5..dfc0d4db1e 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -1,5 +1,6 @@
from collections.abc import Iterable
from dataclasses import dataclass
+from functools import cached_property
from typing import Optional
from uuid import UUID
@@ -7,14 +8,14 @@ from django.db.models import prefetch_related_objects
from ..channel.models import Channel
from ..core.db.connection import allow_writer
+from ..core.prices import quantize_price
from ..core.pricing.interface import LineInfo
+from ..core.taxes import zero_money
from ..discount import DiscountType, VoucherType
-from ..discount.interface import (
- fetch_variant_rules_info,
- fetch_voucher_info,
-)
+from ..discount.interface import fetch_variant_rules_info, fetch_voucher_info
from ..discount.models import OrderLineDiscount
from ..discount.utils.voucher import apply_voucher_to_line
+from ..graphql.core.types import Money
from ..payment.models import Payment
from ..product.models import (
DigitalContent,
@@ -83,6 +84,27 @@ class EditableOrderLineInfo(LineInfo):
line: "OrderLine"
discounts: list["OrderLineDiscount"]
+ @cached_property
+ def variant_discounted_price(self) -> Money:
+ """Return the discounted variant price.
+
+ If listing is present return the discounted price from the listing.
+ if listing is not present, calculate current unit price based on the details
+ assigned to the line. We want to show the same prices as they were
+ before removing listing.
+ """
+ if self.channel_listing and self.channel_listing.discounted_price is not None:
+ return self.channel_listing.discounted_price
+
+ catalogue_discounts = self.get_catalogue_discounts()
+ total_price = self.line.undiscounted_base_unit_price * self.line.quantity
+ for discount in catalogue_discounts:
+ total_price -= discount.amount
+ unit_price = max(
+ total_price / self.line.quantity, zero_money(self.line.currency)
+ )
+ return quantize_price(unit_price, self.line.currency)
+
def get_manual_line_discount(
self,
) -> Optional["OrderLineDiscount"]:
diff --git a/saleor/order/tests/test_fetch.py b/saleor/order/tests/test_fetch.py
index 74ac9b38cf..889bb1dba3 100644
--- a/saleor/order/tests/test_fetch.py
+++ b/saleor/order/tests/test_fetch.py
@@ -3,7 +3,7 @@ from decimal import Decimal
import pytest
from ...product.models import ProductVariantChannelListing
-from ..fetch import fetch_draft_order_lines_info
+from ..fetch import EditableOrderLineInfo, fetch_draft_order_lines_info
@pytest.mark.django_db
@@ -71,3 +71,110 @@ def test_fetch_draft_order_lines_info(
assert rule_info_2.promotion == rule_catalogue.promotion
assert rule_info_2.promotion_translation.name == promotion_translation
assert rule_info_2.rule_translation.name == rule_translation
+
+
+def test_editable_order_line_info_variant_discounted_price(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order_line = order_with_lines_and_catalogue_promotion.lines.get(quantity=3)
+ order = order_with_lines_and_catalogue_promotion
+ channel = order.channel
+ variant = order_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = order_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ # when
+ order_line_info = EditableOrderLineInfo(
+ line=order_line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert order_line_info.variant_discounted_price == expected_discounted_variant_price
+
+
+def test_editable_order_line_info_variant_discounted_price_without_listing(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order_line = order_with_lines_and_catalogue_promotion.lines.get(quantity=3)
+ order = order_with_lines_and_catalogue_promotion
+ channel = order.channel
+ variant = order_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = order_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ variant.channel_listings.all().delete()
+
+ # when
+ order_line_info = EditableOrderLineInfo(
+ line=order_line,
+ variant=variant,
+ channel_listing=None,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert order_line_info.variant_discounted_price == expected_discounted_variant_price
+
+
+def test_editable_order_line_info_variant_discounted_price_when_listing_without_price(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order_line = order_with_lines_and_catalogue_promotion.lines.get(quantity=3)
+ order = order_with_lines_and_catalogue_promotion
+ channel = order.channel
+ variant = order_line.variant
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
+ product = variant.product
+ product_type = product.product_type
+ discounts = order_line.discounts.all()
+
+ expected_discounted_variant_price = variant_channel_listing.discounted_price
+ assert variant_channel_listing.discounted_price != variant_channel_listing.price
+
+ variant_channel_listing.discounted_price_amount = None
+ variant_channel_listing.save(update_fields=["discounted_price_amount"])
+
+ # when
+ order_line_info = EditableOrderLineInfo(
+ line=order_line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=[],
+ discounts=discounts,
+ rules_info=[],
+ channel=channel,
+ voucher=None,
+ voucher_code=None,
+ )
+ # then
+ assert order_line_info.variant_discounted_price == expected_discounted_variant_price
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index ebec05f8e6..8bb7975365 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1267,8 +1267,16 @@ def order_info_for_logs(order: Order, lines: Iterable[OrderLine]):
"total_price_net_amount": line_info.line.total_price_net_amount,
"total_price_gross_amount": line_info.line.total_price_gross_amount,
"has_voucher_code": bool(line_info.line.voucher_code),
- "variant_listing_price": line_info.channel_listing.price_amount,
- "variant_listing_discounted_price": line_info.channel_listing.discounted_price_amount,
+ "variant_listing_price": (
+ line_info.channel_listing.price_amount
+ if line_info.channel_listing
+ else None
+ ),
+ "variant_listing_discounted_price": (
+ line_info.channel_listing.discounted_price_amount
+ if line_info.channel_listing
+ else None
+ ),
"unit_discount_amount": line_info.line.unit_discount_amount,
"unit_discount_type": line_info.line.unit_discount_type,
"unit_discount_reason": line_info.line.unit_discount_reason,
diff --git a/saleor/warehouse/tests/test_preorder_reservations_management.py b/saleor/warehouse/tests/test_preorder_reservations_management.py
index 238396b180..656cb373a5 100644
--- a/saleor/warehouse/tests/test_preorder_reservations_management.py
+++ b/saleor/warehouse/tests/test_preorder_reservations_management.py
@@ -154,6 +154,9 @@ def test_preorder_reservation_fails_if_channel_threshold_was_reserved(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=3,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=other_checkout.channel_id
+ ).price_amount,
)
product_variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
PreorderReservation.objects.create(
@@ -241,6 +244,9 @@ def test_preorder_reservation_fails_if_global_threshold_was_reserved(
other_checkout_line = other_checkout.lines.create(
variant=variant,
quantity=3,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=other_checkout.channel_id
+ ).price_amount,
)
PreorderReservation.objects.create(
checkout_line=other_checkout_line,
diff --git a/saleor/warehouse/tests/test_stock_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.py
index 497613aaba..2081348db1 100644
--- a/saleor/warehouse/tests/test_stock_reservations_management.py
+++ b/saleor/warehouse/tests/test_stock_reservations_management.py
@@ -251,6 +251,9 @@ def test_stock_reservation_accounts_for_order_allocations(
checkout_line = checkout.lines.create(
quantity=4,
variant=variant,
+ undiscounted_unit_price_amount=variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price_amount,
)
with pytest.raises(InsufficientStock):
@@ -273,9 +276,13 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations(
currency=channel_USD.currency_code, channel=channel_USD
)
other_checkout.set_country("US", commit=True)
+ undiscounted_unit_price_amount = variant.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price_amount
other_checkout_line = checkout.lines.create(
quantity=2,
variant=variant,
+ undiscounted_unit_price_amount=undiscounted_unit_price_amount,
)
Reservation.objects.create(
@@ -288,6 +295,7 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations(
checkout_line = checkout.lines.create(
quantity=2,
variant=variant,
+ undiscounted_unit_price_amount=undiscounted_unit_price_amount,
)
with pytest.raises(InsufficientStock):
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 9cd3961b13..cf8ba04ea0 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -27,12 +27,8 @@ def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:
lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
for line_info in lines:
variant = line_info.variant
- channel_listing = line_info.channel_listing
product = variant.product
- base_price = variant.get_base_price(
- channel_listing, line_info.line.price_override
- )
- total_discount_amount_for_line = Decimal("0")
+ base_price = line_info.undiscounted_unit_price
total_discount_amount_for_line = sum(
[discount.amount_value for discount in line_info.get_promotion_discounts()],
Decimal("0"),
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 7cfa023ffc..23e5917398 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -1385,6 +1385,24 @@ def test_generate_checkout_lines_payload(checkout_with_single_item):
assert line["variant_id"] == variant.get_global_id()
+def test_generate_checkout_lines_payload_when_variant_without_listing(
+ checkout_with_single_item,
+):
+ line_without_listing = checkout_with_single_item.lines.first()
+ line_without_listing.variant.channel_listings.all().delete()
+ 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()
+ assert (
+ Decimal(line["base_price"])
+ == line_without_listing.undiscounted_unit_price.amount
+ )
+
+
def test_generate_checkout_lines_payload_custom_price(checkout_with_single_item):
line = checkout_with_single_item.lines.first()
price_override = Decimal("11.11")
@@ -2192,6 +2210,9 @@ def test_generate_checkout_payload_for_tax_calculation_gift_promotion(
top_price, variant_id = max(
variant_listings.values_list("discounted_price_amount", "variant")
)
+ variant_listing = [
+ listing for listing in variant_listings if listing.variant_id == variant_id
+ ][0]
line = CheckoutLine.objects.create(
checkout=checkout,
@@ -2199,6 +2220,7 @@ def test_generate_checkout_payload_for_tax_calculation_gift_promotion(
variant_id=variant_id,
is_gift=True,
currency="USD",
+ undiscounted_unit_price_amount=variant_listing.price_amount,
)
CheckoutLineDiscount.objects.create(