Skip to content

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

feat: add per-channel availability toggle for product variants (#19795) (#19911)

Lukasz Ostrowski925b69959a97
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index fd673963cf..3ba7731c33 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -302,7 +302,7 @@ def update_undiscounted_unit_price_for_lines(lines: Iterable["CheckoutLineInfo"]
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:
+ if not line_info.channel_listing or not line_info.channel_listing.is_sellable:
continue
line_info.line.undiscounted_unit_price = line_info.undiscounted_unit_price
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index d94ce1ed75..92fd554961 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -312,7 +312,7 @@ def _is_variant_valid(
variant_channel_listing: Optional["ProductVariantChannelListing"],
product_channel_listing_mapping: dict,
):
- if not variant_channel_listing or variant_channel_listing.price is None:
+ if not variant_channel_listing or not variant_channel_listing.is_sellable:
return False
if not _product_channel_listing_is_valid(
diff --git a/saleor/checkout/problems.py b/saleor/checkout/problems.py
index 01ffc343cc..9cc4cf54cf 100644
--- a/saleor/checkout/problems.py
+++ b/saleor/checkout/problems.py
@@ -114,7 +114,7 @@ def line_is_not_available(
if not line.channel_listing:
return True
- if line.channel_listing.price_amount is None:
+ if not line.channel_listing.is_sellable:
return True
return False
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index ac9e516789..3d34a0dc7c 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -372,12 +372,13 @@ def _get_best_gift_reward(
return None, None
# check variant channel availability
- available_variant_listings = ProductVariantChannelListing.objects.using(
- database_connection_name
- ).filter(
- variant_id__in=available_variant_ids,
- channel_id=channel.id,
- price_amount__isnull=False,
+ available_variant_listings = (
+ ProductVariantChannelListing.objects.using(database_connection_name)
+ .sellable()
+ .filter(
+ variant_id__in=available_variant_ids,
+ channel_id=channel.id,
+ )
)
if not available_variant_listings:
return None, None
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 47bef52738..85338d6efd 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -56,6 +56,7 @@ from .common import (
ProductError,
ProductVariantBulkError,
ProductVariantBulkTranslateError,
+ ProductVariantChannelListingAvailabilityUpdateError,
ProductWithoutVariantError,
SecureGlobalID,
SendConfirmationEmailError,
@@ -139,6 +140,7 @@ __all__ = [
"PriceInput",
"PriceRangeInput",
"ProductChannelListingError",
+ "ProductVariantChannelListingAvailabilityUpdateError",
"ProductError",
"ProductBulkCreateError",
"ProductBulkTranslateError",
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index dae8bfb4bb..4067a4b25f 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -542,6 +542,22 @@ class ProductChannelListingError(ProductError):
doc_category = DOC_CATEGORY_PRODUCTS
+class ProductVariantChannelListingAvailabilityUpdateError(Error):
+ code = ProductErrorCode(description="The error code.", required=True)
+ channels = NonNullList(
+ graphene.ID,
+ description="List of channels IDs which causes the error.",
+ required=False,
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+ description = (
+ "Error of the `productVariantChannelListingAvailabilityUpdate` mutation."
+ + ADDED_IN_323
+ )
+
+
class CollectionChannelListingError(ProductError):
channels = NonNullList(
graphene.ID,
diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.py
index 94aee3283b..cf4df60746 100644
--- a/saleor/graphql/core/validators/__init__.py
+++ b/saleor/graphql/core/validators/__init__.py
@@ -144,10 +144,10 @@ def get_not_available_variants_in_channel(
) -> tuple[set[int], set[str]]:
available_variants = (
ProductVariantChannelListing.objects.using(database_connection_name)
+ .sellable()
.filter(
variant__id__in=variants_id,
channel_id=channel_id,
- price_amount__isnull=False,
)
.values_list("variant_id", flat=True)
)
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
index c8d5a7bad0..5e345d2efd 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_create.py
@@ -44,7 +44,10 @@ from ...core.validators import validate_price_precision
from ...meta.inputs import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
from ...shop.utils import get_track_inventory_by_default
-from ..mutations.channels import ProductVariantChannelListingAddInput
+from ..mutations.channels import (
+ ProductVariantChannelListingAddInput,
+ get_new_listing_availability,
+)
from ..mutations.product.product_create import StockInput
from ..mutations.product_variant.product_variant_create import ProductVariantInput
from ..types import ProductVariant
@@ -837,6 +840,7 @@ class ProductVariantBulkCreate(BaseMutation):
cost_price_amount=listing_data.get("cost_price"),
prior_price_amount=listing_data.get("prior_price"),
currency=listing_data["channel"].currency_code,
+ is_available_for_purchase=get_new_listing_availability(listing_data),
)
for listing_data in listings_input
]
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
index 59a56360ed..40100fc334 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_update.py
@@ -12,11 +12,13 @@ from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_a
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.error_codes import ProductErrorCode, ProductVariantBulkErrorCode
+from ....product.utils.product import mark_products_in_channels_as_dirty
from ....warehouse import models as warehouse_models
from ....warehouse.management import delete_stocks, stock_bulk_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...attribute.utils.attribute_assignment import AttributeAssignmentMixin
+from ...core.descriptions import ADDED_IN_323
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.enums import ErrorPolicyEnum
from ...core.mutations import BaseMutation, DeprecatedModelMutation
@@ -27,7 +29,10 @@ from ...meta.inputs import MetadataInput
from ...plugins.dataloaders import get_plugin_manager_promise
from ...utils import get_user_or_app_from_context
from ...webhook.subscription_payload import generate_pre_save_payloads
-from ..mutations.channels import ProductVariantChannelListingAddInput
+from ..mutations.channels import (
+ ProductVariantChannelListingAddInput,
+ get_new_listing_availability,
+)
from ..mutations.product.product_create import StockInput, StockUpdateInput
from ..utils import clean_variant_sku, get_used_variants_attribute_values
from .product_variant_bulk_create import (
@@ -66,6 +71,10 @@ class ChannelListingUpdateInput(BaseInputObjectType):
price = PositiveDecimal(description="Price of the particular variant in channel.")
cost_price = PositiveDecimal(description="Cost price of the variant in channel.")
prior_price = PositiveDecimal(description="Price of the variant before discount.")
+ is_available_for_purchase = graphene.Boolean(
+ description="Determines whether the variant can be bought in this channel. "
+ "When omitted, the current value is kept." + ADDED_IN_323
+ )
class Meta:
doc_category = DOC_CATEGORY_PRODUCTS
@@ -635,6 +644,9 @@ class ProductVariantBulkUpdate(BaseMutation):
cost_price_amount=listing_data.get("cost_price"),
prior_price_amount=listing_data.get("prior_price"),
currency=listing_data["channel"].currency_code,
+ is_available_for_purchase=get_new_listing_availability(
+ listing_data
+ ),
)
for listing_data in listings_data
]
@@ -651,6 +663,10 @@ class ProductVariantBulkUpdate(BaseMutation):
listing.cost_price_amount = listing_data["cost_price"]
if "prior_price" in listing_data:
listing.prior_price_amount = listing_data["prior_price"]
+ if listing_data.get("is_available_for_purchase") is not None:
+ listing.is_available_for_purchase = listing_data[
+ "is_available_for_purchase"
+ ]
listings_to_update.append(listing)
@classmethod
@@ -723,6 +739,7 @@ class ProductVariantBulkUpdate(BaseMutation):
"discounted_price_amount",
"cost_price_amount",
"prior_price_amount",
+ "is_available_for_purchase",
],
)
if stocks_to_remove:
@@ -751,6 +768,10 @@ class ProductVariantBulkUpdate(BaseMutation):
impacted_channel_ids,
):
if impacted_channel_ids:
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {channel_id: {product.pk} for channel_id in impacted_channel_ids},
+ )
cls.call_event(
mark_active_catalogue_promotion_rules_as_dirty, impacted_channel_ids
)
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index fb7cfae208..d54f338182 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -262,8 +262,10 @@ class AvailableProductVariantsByProductIdAndChannel(
context_key = "available_productvariant_by_product_and_channel"
def get_variants_filter(self, channel_id: int):
- variant_channel_listings = ProductVariantChannelListing.objects.filter(
- channel_id=channel_id, price_amount__isnull=False
+ variant_channel_listings = (
+ ProductVariantChannelListing.objects.sellable().filter(
+ channel_id=channel_id
+ )
)
return Q(Exists(variant_channel_listings.filter(variant_id=OuterRef("id"))))
@@ -394,10 +396,8 @@ class VariantChannelListingsByProductIdLoader(
variants_channel_listings = (
ProductVariantChannelListing.objects.all()
.using(self.database_connection_name)
- .filter(
- variant__product_id__in=keys,
- price_amount__isnull=False,
- )
+ .sellable()
+ .filter(variant__product_id__in=keys)
.annotate(product_id=F("variant__product_id"))
.order_by("pk")
)
@@ -446,10 +446,10 @@ class VariantsChannelListingByProductIdAndChannelSlugLoader(
variants_channel_listings = (
ProductVariantChannelListing.objects.all()
.using(self.database_connection_name)
+ .sellable()
.filter(
channel__slug=channel_slug,
variant__product_id__in=products_ids,
- price_amount__isnull=False,
)
.annotate(product_id=F("variant__product_id"))
.order_by("pk")
diff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.py
index baaead9484..fc548823d6 100644
--- a/saleor/graphql/product/filters/product_helpers.py
+++ b/saleor/graphql/product/filters/product_helpers.py
@@ -231,10 +231,8 @@ def filter_products_is_published(qs, _, value, channel_slug):
# Filter out product for which there is no variant with price
variant_channel_listings = (
ProductVariantChannelListing.objects.using(qs.db)
- .filter(
- Exists(channel.filter(pk=OuterRef("channel_id"))),
- price_amount__isnull=False,
- )
+ .sellable()
+ .filter(Exists(channel.filter(pk=OuterRef("channel_id"))))
.values("id")
)
variants = (
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index e761d32745..7e77622460 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -10,6 +10,9 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils.date_time import convert_to_utc_date_time
from ....permission.enums import ProductPermissions
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
+from ....product.lock_objects import (
+ product_variant_channel_listing_qs_select_for_update,
+)
from ....product.models import (
CollectionChannelListing,
ProductChannelListing,
@@ -22,7 +25,7 @@ from ...channel.mutations import BaseChannelListingMutation
from ...channel.types import Channel
from ...core import ResolveInfo
from ...core.context import ChannelContext
-from ...core.descriptions import DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.mutations import BaseMutation
from ...core.scalars import Date, DateTime, PositiveDecimal
@@ -31,6 +34,7 @@ from ...core.types import (
CollectionChannelListingError,
NonNullList,
ProductChannelListingError,
+ ProductVariantChannelListingAvailabilityUpdateError,
)
from ...core.utils import get_duplicated_values
from ...core.validators import (
@@ -48,6 +52,8 @@ if TYPE_CHECKING:
ErrorType = defaultdict[str, list[ValidationError]]
+AVAILABILITY_UPDATE_MAX_ITEMS = 100
+
class PublishableChannelListingInput(BaseInputObjectType):
channel_id = graphene.ID(required=True, description="ID of a channel.")
@@ -382,6 +388,21 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
)
+def get_new_listing_availability(listing_data: dict) -> bool:
+ """Resolve the availability flag for a listing that is about to be created.
+
+ The column is not nullable, so there is no way to store "unspecified". A listing
+ created without the flag — or with an explicit `null` — falls back to the model
+ default, which is available; that keeps `addVariants` and every pre-flag client
+ creating purchasable listings. Updates are the other case: they read the input
+ directly and leave the stored value alone when the field is omitted.
+ """
+ is_available_for_purchase = listing_data.get("is_available_for_purchase")
+ if is_available_for_purchase is None:
+ return True
+ return is_available_for_purchase
+
+
class ProductVariantChannelListingAddInput(BaseInputObjectType):
channel_id = graphene.ID(required=True, description="ID of a channel.")
price = PositiveDecimal(
@@ -393,12 +414,42 @@ class ProductVariantChannelListingAddInput(BaseInputObjectType):
"promotion information required by customer protection laws such as EU Omnibus "
"directive."
)
+ is_available_for_purchase = graphene.Boolean(
+ description="Determines whether the variant can be bought in this channel. "
+ "When omitted on an existing listing, the current value is kept." + ADDED_IN_323
+ )
class Meta:
doc_category = DOC_CATEGORY_PRODUCTS
-class ProductVariantChannelListingUpdate(BaseMutation):
+class VariantByIdOrSkuMixin:
+ """Resolve the product variant a channel listing mutation operates on."""
+
+ @classmethod
+ def get_variant_by_id_or_sku(
+ cls, info: ResolveInfo, id: str | None, sku: str | None
+ ) -> "ProductVariantModel":
+ validate_one_of_args_is_in_mutation("sku", sku, "id", id)
+
+ qs = ProductVariantModel.objects.all()
+ if id:
+ return cls.get_node_or_error( # type: ignore[attr-defined]
+ info, id, only_type=ProductVariant, field="id", qs=qs
+ )
+ variant = qs.filter(sku=sku).first()
+ if not variant:
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ f"Couldn't resolve to a node: {sku}", code="not_found"
+ )
+ }
+ )
+ return variant
+
+
+class ProductVariantChannelListingUpdate(VariantByIdOrSkuMixin, BaseMutation):
variant = graphene.Field(
ProductVariant, description="An updated product variant instance."
)
@@ -533,6 +584,10 @@ class ProductVariantChannelListingUpdate(BaseMutation):
defaults["prior_price_amount"] = channel_listing_data.get(
"prior_price", None
)
+ if channel_listing_data.get("is_available_for_purchase") is not None:
+ defaults["is_available_for_purchase"] = channel_listing_data[
+ "is_available_for_purchase"
+ ]
ProductVariantChannelListing.objects.update_or_create(
variant=variant,
channel=channel,
@@ -557,23 +612,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, id=None, input, sku=None
):
- validate_one_of_args_is_in_mutation("sku", sku, "id", id)
-
- qs = ProductVariantModel.objects.all()
- if id:
- variant = cls.get_node_or_error(
- info, id, only_type=ProductVariant, field="id", qs=qs
- )
- else:
- variant = qs.filter(sku=sku).first()
- if not variant:
- raise ValidationError(
- {
- "sku": ValidationError(
- f"Couldn't resolve to a node: {sku}", code="not_found"
- )
- }
- )
+ variant = cls.get_variant_by_id_or_sku(info, id, sku)
errors: defaultdict[str, list[ValidationError]] = defaultdict(list)
@@ -591,6 +630,166 @@ class ProductVariantChannelListingUpdate(BaseMutation):
)
+class ProductVariantChannelListingAvailabilityInput(BaseInputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ is_available_for_purchase = graphene.Boolean(
+ required=True,
+ description="Determines whether the variant can be bought in this channel.",
+ )
+
+ class Meta:
+ doc_category = DOC_CATEGORY_PRODUCTS
+ description = (
+ "Fields required to toggle a product variant's availability "
+ "in a channel." + ADDED_IN_323
+ )
+
+
+class ProductVariantChannelListingAvailabilityUpdate(
+ VariantByIdOrSkuMixin, BaseMutation
+):
+ variant = graphene.Field(
+ ProductVariant, description="An updated product variant instance."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ required=False, description="ID of a product variant to update."
+ )
+ sku = graphene.String(
+ required=False, description="SKU of a product variant to update."
+ )
+ input = NonNullList(
+ ProductVariantChannelListingAvailabilityInput,
+ required=True,
+ description=(
+ "List of channels to toggle the variant's availability in. "
+ f"Max {AVAILABILITY_UPDATE_MAX_ITEMS} items."
+ ),
+ )
+
+ class Meta:
+ description = (
+ "Toggle whether a product variant can be bought in the given channels, "
+ "without touching its prices. An unavailable variant is hidden from "
+ "customers and cannot be added to a checkout or an order." + ADDED_IN_323
+ )
+ doc_category = DOC_CATEGORY_PRODUCTS
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductVariantChannelListingAvailabilityUpdateError
+
+ @classmethod
+ def clean_channels(cls, input) -> dict[int, dict]:
+ """Map channel pk to its input, rejecting oversized and duplicated input."""
+ channel_ids = [channel_data["channel_id"] for channel_data in input]
+
+ if len(channel_ids) > AVAILABILITY_UPDATE_MAX_ITEMS:
+ raise ValidationError(
+ {
+ "input": ValidationError(
+ f"Cannot specify more than "
+ f"{AVAILABILITY_UPDATE_MAX_ITEMS} items.",
+ code=ProductErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ duplicates = get_duplicated_values(channel_ids)
+ if duplicates:
+ raise ValidationError(
+ {
+ "channel_id": ValidationError(
+ "Duplicated channel ID.",
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ params={"channels": list(duplicates)},
+ )
+ }
+ )
+
+ channels = cls.get_nodes_or_error(channel_ids, "channel_id", Channel)
+ return {
+ channel.pk: channel_data
+ for channel, channel_data in zip(channels, input, strict=True)
+ }
+
+ @classmethod
+ def get_listings_to_update(
+ cls, variant: "ProductVariantModel", channel_id_to_input: dict[int, dict]
+ ) -> list[ProductVariantChannelListing]:
+ """Return the listings whose flag actually changes.
+
+ Must run inside a transaction — the rows are locked so a concurrent toggle of
+ the same listing cannot be silently lost. Raises when the variant has no
+ listing in a requested channel; this mutation must not create price-less ones.
+ """
+ listings = list(
+ product_variant_channel_listing_qs_select_for_update().filter(
+ variant_id=variant.pk, channel_id__in=channel_id_to_input
+ )
+ )
+ missing_channel_ids = set(channel_id_to_input) - {
+ listing.channel_id for listing in listings
+ }
+ if missing_channel_ids:
+ raise ValidationError(
+ {
+ "channel_id": ValidationError(
+ "Variant has no channel listing in the given channels.",
+ code=ProductErrorCode.NOT_FOUND.value,
+ params={
+ "channels": [
+ channel_id_to_input[channel_id]["channel_id"]
+ for channel_id in missing_channel_ids
+ ]
+ },
+ )
+ }
+ )
+
+ listings_to_update = []
+ for listing in listings:
+ is_available = channel_id_to_input[listing.channel_id][
+ "is_available_for_purchase"
+ ]
+ if listing.is_available_for_purchase != is_available:
+ listing.is_available_for_purchase = is_available
+ listings_to_update.append(listing)
+ return listings_to_update
+
+ @classmethod
+ def post_save_actions(
+ cls,
+ info: ResolveInfo,
+ variant: "ProductVariantModel",
+ updated_listings: list[ProductVariantChannelListing],
+ ):
+ cls.call_event(
+ mark_products_in_channels_as_dirty,
+ {listing.channel_id: {variant.product_id} for listing in updated_listings},
+ )
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_variant_updated, variant)
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, id=None, input, sku=None
+ ):
+ variant = cls.get_variant_by_id_or_sku(info, id, sku)
+ channel_id_to_input = cls.clean_channels(input)
+
+ with traced_atomic_transaction():
+ listings_to_update = cls.get_listings_to_update(
+ variant, channel_id_to_input
+ )
+ if listings_to_update:
+ ProductVariantChannelListing.objects.bulk_update(
+ listings_to_update, ["is_available_for_purchase"]
+ )
+ cls.post_save_actions(info, variant, listings_to_update)
+
+ return cls(variant=ChannelContext(node=variant, channel_slug=None))
+
+
class CollectionChannelListingUpdateInput(BaseInputObjectType):
add_channels = NonNullList(
PublishableChannelListingInput,
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 2c56d7bdd4..d9f4b12daf 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -99,6 +99,7 @@ from .mutations.attributes import (
from .mutations.channels import (
CollectionChannelListingUpdate,
ProductChannelListingUpdate,
+ ProductVariantChannelListingAvailabilityUpdate,
ProductVariantChannelListingUpdate,
)
from .resolvers import (
@@ -720,6 +721,9 @@ class ProductMutations(graphene.ObjectType):
product_variant_translate = ProductVariantTranslate.Field()
product_variant_bulk_translate = ProductVariantBulkTranslate.Field()
product_variant_channel_listing_update = ProductVariantChannelListingUpdate.Field()
+ product_variant_channel_listing_availability_update = (
+ ProductVariantChannelListingAvailabilityUpdate.Field()
+ )
product_variant_reorder_attribute_values = (
ProductVariantReorderAttributeValues.Field()
)
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index 54cfde281a..78d3bbe1b2 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -17,6 +17,7 @@ from django.db.models import (
)
from django.db.models.functions import Coalesce
+from ...product.managers import sellable_listing_q
from ...product.models import (
Category,
CollectionChannelListing,
@@ -227,7 +228,7 @@ class ProductOrderField(BaseEnum):
min_variants_price_amount=Min(
"variants__channel_listings__price_amount",
filter=Q(variants__channel_listings__channel__slug=str(channel_slug))
- & Q(variants__channel_listings__price_amount__isnull=False),
+ & sellable_listing_q("variants__channel_listings__"),
)
)
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
index c90f94cfc0..37a483e65a 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from unittest import mock
from unittest.mock import patch
@@ -1484,3 +1485,137 @@ def test_product_variant_bulk_update_channel_listings_input_with_prior_price(
new_variant_listing.prior_price_amount
== not_existing_variant_listing_prior_price
)
+
+
+def test_product_variant_bulk_update_channel_listings_availability_only(
+ staff_api_client, variant, permission_manage_products, channel_USD
+):
+ """The flag must be updatable on its own, without resending the price."""
+ # given
+ listing = variant.channel_listings.get(channel=channel_USD)
+ price_amount = listing.price_amount
+ assert listing.is_available_for_purchase is True
+
+ variants = [
+ {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channelListings": {
+ "update": [
+ {
+ "channelListing": graphene.Node.to_global_id(
+ "ProductVariantChannelListing", listing.pk
+ ),
+ "isAvailableForPurchase": False,
+ }
+ ]
+ },
+ }
+ ]
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", variant.product_id),
+ "variants": variants,
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkUpdate"]
+ assert data["results"][0]["errors"] == []
+ assert data["count"] == 1
+
+ listing.refresh_from_db(fields=("is_available_for_purchase", "price_amount"))
+ assert listing.is_available_for_purchase is False
+ assert listing.price_amount == price_amount
+
+
+def test_product_variant_bulk_update_channel_listings_marks_product_price_dirty(
+ staff_api_client, variant, permission_manage_products, channel_USD
+):
+ """The stored product price range must be recalculated after a listing change."""
+ # given
+ listing = variant.channel_listings.get(channel=channel_USD)
+ product_listing = variant.product.channel_listings.get(channel=channel_USD)
+ product_listing.discounted_price_dirty = False
+ product_listing.save(update_fields=("discounted_price_dirty",))
+
+ variants = [
+ {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channelListings": {
+ "update": [
+ {
+ "channelListing": graphene.Node.to_global_id(
+ "ProductVariantChannelListing", listing.pk
+ ),
+ "isAvailableForPurchase": False,
+ }
+ ]
+ },
+ }
+ ]
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", variant.product_id),
+ "variants": variants,
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["productVariantBulkUpdate"]["results"][0]["errors"] == []
+
+ product_listing.refresh_from_db(fields=("discounted_price_dirty",))
+ assert product_listing.discounted_price_dirty is True
+
+
+def test_product_variant_bulk_update_channel_listings_create_with_availability(
+ staff_api_client, variant, permission_manage_products, channel_PLN
+):
+ # given
+ price = 20.0
+ product = variant.product
+ ProductChannelListing.objects.create(product=product, channel=channel_PLN)
+
+ variants = [
+ {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channelListings": {
+ "create": [
+ {
+ "channelId": graphene.Node.to_global_id(
+ "Channel", channel_PLN.pk
+ ),
+ "price": price,
+ "isAvailableForPurchase": False,
+ }
+ ]
+ },
+ }
+ ]
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product.pk),
+ "variants": variants,
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["productVariantBulkUpdate"]["results"][0]["errors"] == []
+
+ new_listing = variant.channel_listings.get(channel=channel_PLN)
+ assert new_listing.is_available_for_purchase is False
+ assert new_listing.price_amount == Decimal(str(price))
diff --git a/saleor/graphql/product/tests/mutations/test_variant_channel_listing_availability_update.py b/saleor/graphql/product/tests/mutations/test_variant_channel_listing_availability_update.py
new file mode 100644
index 0000000000..064f3b9310
--- /dev/null
+++ b/saleor/graphql/product/tests/mutations/test_variant_channel_listing_availability_update.py
@@ -0,0 +1,525 @@
+from unittest.mock import patch
+
+import graphene
+import pytest
+
+from .....product.error_codes import ProductErrorCode
+from .....product.models import ProductVariantChannelListing
+from ....product.mutations.channels import AVAILABILITY_UPDATE_MAX_ITEMS
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+
+PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION = """
+mutation UpdateAvailability(
+ $id: ID,
+ $sku: String,
+ $input: [ProductVariantChannelListingAvailabilityInput!]!
+) {
+ productVariantChannelListingAvailabilityUpdate(
+ id: $id, sku: $sku, input: $input
+ ) {
+ errors {
+ field
+ message
+ code
+ channels
+ }
+ variant {
+ id
+ channelListings {
+ channel {
+ slug
+ }
+ isAvailableForPurchase
+ price {
+ amount
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def variant_in_two_channels(product_available_in_many_channels):
+ return product_available_in_many_channels.variants.get()
+
+
+def test_marks_listing_as_unavailable_without_touching_prices(
+ staff_api_client, variant_in_two_channels, permission_manage_products, channel_USD
+):
+ # given
+ variant = variant_in_two_channels
+ listing = variant.channel_listings.get(channel=channel_USD)
+ price_amount = listing.price_amount
+ cost_price_amount = listing.cost_price_amount
+ assert listing.is_available_for_purchase is True
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+
+ listing.refresh_from_db(
+ fields=("is_available_for_purchase", "price_amount", "cost_price_amount")
+ )
+ assert listing.is_available_for_purchase is False
+ assert listing.price_amount == price_amount
+ assert listing.cost_price_amount == cost_price_amount
+
+
+def test_price_survives_a_full_unavailable_available_cycle(
+ staff_api_client, variant_in_two_channels, permission_manage_products, channel_USD
+):
+ """Reproduces the reported bug: the price must not be lost or reset to 0."""
+ # given
+ variant = variant_in_two_channels
+ listing = variant.channel_listings.get(channel=channel_USD)
+ listing_pk = listing.pk
+ price_amount = listing.price_amount
+ cost_price_amount = listing.cost_price_amount
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ for is_available in (False, True):
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables={
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_id, "isAvailableForPurchase": is_available}
+ ],
+ },
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+
+ # then
+ listing = ProductVariantChannelListing.objects.get(
+ variant=variant, channel=channel_USD
+ )
+ assert listing.pk == listing_pk
+ assert listing.is_available_for_purchase is True
+ assert listing.price_amount == price_amount
+ assert listing.cost_price_amount == cost_price_amount
+
+
+def test_other_channels_are_left_untouched(
+ staff_api_client,
+ variant_in_two_channels,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ variant = variant_in_two_channels
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+
+ availability_per_channel = {
+ listing["channel"]["slug"]: listing["isAvailableForPurchase"]
+ for listing in data["variant"]["channelListings"]
+ }
+ assert availability_per_channel == {
+ channel_USD.slug: False,
+ channel_PLN.slug: True,
+ }
+
+
+def test_resolves_the_variant_by_sku(
+ staff_api_client, variant_in_two_channels, permission_manage_products, channel_USD
+):
+ # given
+ variant = variant_in_two_channels
+ listing = variant.channel_listings.get(channel=channel_USD)
+ variables = {
+ "sku": variant.sku,
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+ assert data["variant"]["id"] == graphene.Node.to_global_id(
+ "ProductVariant", variant.pk
+ )
+
+ listing.refresh_from_db(fields=("is_available_for_purchase",))
+ assert listing.is_available_for_purchase is False
+
+
+def test_missing_listing_returns_not_found_and_creates_nothing(
+ staff_api_client, variant, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ assert variant.channel_listings.filter(channel=channel_PLN).exists() is False
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ },
+ {"channelId": channel_pln_id, "isAvailableForPurchase": False},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "channelId"
+ assert error["code"] == ProductErrorCode.NOT_FOUND.name
+ assert error["message"] == ("Variant has no channel listing in the given channels.")
+ assert error["channels"] == [channel_pln_id]
+
+ assert variant.channel_listings.filter(channel=channel_PLN).exists() is False
+ usd_listing = variant.channel_listings.get(channel=channel_USD)
+ assert usd_listing.is_available_for_purchase is True
+
+
+def test_duplicated_channel_is_rejected(
+ staff_api_client, variant, permission_manage_products, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {"channelId": channel_id, "isAvailableForPurchase": False},
+ {"channelId": channel_id, "isAvailableForPurchase": True},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "channelId"
+ assert error["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert error["message"] == "Duplicated channel ID."
+ assert error["channels"] == [channel_id]
+
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_unchanged_flag_emits_no_events(
+ mocked_variant_updated,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
+ product_listing = variant.product.channel_listings.get(channel=channel_USD)
+ product_listing.discounted_price_dirty = False
+ product_listing.save(update_fields=("discounted_price_dirty",))
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": True,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+ assert mocked_variant_updated.call_count == 0
+
+ product_listing.refresh_from_db(fields=("discounted_price_dirty",))
+ assert product_listing.discounted_price_dirty is False
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_changed_flag_marks_product_dirty_and_notifies(
+ mocked_variant_updated,
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product_listing = variant.product.channel_listings.get(channel=channel_USD)
+ product_listing.discounted_price_dirty = False
+ product_listing.save(update_fields=("discounted_price_dirty",))
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+ assert mocked_variant_updated.call_count == 1
+
+ product_listing.refresh_from_db(fields=("discounted_price_dirty",))
+ assert product_listing.discounted_price_dirty is True
+
+
+ ("_case", "client_fixture", "permission_fixture", "is_allowed"),
+ [
+ ("Unauthenticated user should be rejected", "api_client", None, False),
+ (
+ "Authenticated unprivileged user (non-staff) should be rejected",
+ "user_api_client",
+ None,
+ False,
+ ),
+ (
+ "Authenticated user w/o the permission should be rejected",
+ "staff_api_client",
+ None,
+ False,
+ ),
+ (
+ "Authenticated user w/o the relevant permission should be rejected",
+ "staff_api_client",
+ "permission_manage_orders",
+ False,
+ ),
+ (
+ "Authenticated user w/ the correct permission should be allowed",
+ "staff_api_client",
+ "permission_manage_products",
+ True,
+ ),
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+def test_authorization(
+ mocked_variant_updated,
+ _case,
+ client_fixture,
+ permission_fixture,
+ is_allowed,
+ request,
+ variant,
+ channel_USD,
+):
+ # given
+ client = request.getfixturevalue(client_fixture)
+ if permission_fixture:
+ permission = request.getfixturevalue(permission_fixture)
+ if client.app:
+ client.app.permissions.add(permission)
+ elif client.user:
+ client.user.user_permissions.add(permission)
+ else:
+ raise AssertionError("Couldn't add the permission")
+
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ )
+
+ # then
+ listing.refresh_from_db(fields=("is_available_for_purchase",))
+ if is_allowed:
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+ assert listing.is_available_for_purchase is False
+ assert mocked_variant_updated.call_count == 1
+ else:
+ assert_no_permission(response)
+ content = get_graphql_content_from_response(response)
+ assert content["data"]["productVariantChannelListingAvailabilityUpdate"] is None
+ assert listing.is_available_for_purchase is True
+ assert mocked_variant_updated.call_count == 0
+
+
+def test_locks_the_listing_rows_before_updating(
+ staff_api_client,
+ variant,
+ permission_manage_products,
+ channel_USD,
+ capture_queries,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ with capture_queries() as ctx:
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert data["errors"] == []
+
+ table = ProductVariantChannelListing._meta.db_table
+ listing_queries = [
+ query["sql"]
+ for query in ctx.captured_queries
+ if table in query["sql"]
+ and ("FOR UPDATE" in query["sql"] or query["sql"].startswith("UPDATE"))
+ ]
+ assert len(listing_queries) == 2, listing_queries
+ lock_query, update_query = listing_queries
+ assert "FOR UPDATE" in lock_query
+ assert "ORDER BY" in lock_query
+ assert update_query.startswith("UPDATE")
+
+
+def test_input_longer_than_the_limit_is_rejected(
+ staff_api_client, variant, permission_manage_products, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {"channelId": channel_id, "isAvailableForPurchase": False}
+ for _ in range(AVAILABILITY_UPDATE_MAX_ITEMS + 1)
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_AVAILABILITY_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingAvailabilityUpdate"]
+ assert len(data["errors"]) == 1
+ error = data["errors"][0]
+ assert error["field"] == "input"
+ assert error["code"] == ProductErrorCode.INVALID.name
+ assert error["message"] == (
+ f"Cannot specify more than {AVAILABILITY_UPDATE_MAX_ITEMS} items."
+ )
+
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
index 9d1dba639a..1349e5702b 100644
--- a/saleor/graphql/product/tests/test_variant_channel_listing_update.py
+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
@@ -584,3 +584,101 @@ def test_variant_channel_listing_update_with_prior_price(
assert variant_data["id"] == variant_id
assert variant_data["channelListings"][0]["priorPrice"]["currency"] == "USD"
assert variant_data["channelListings"][0]["priorPrice"]["amount"] == prior_price
+
+
+ ("_case", "initial_availability", "availability_input"),
+ [
+ ("omitted on an available listing", True, {}),
+ ("omitted on an unavailable listing", False, {}),
+ (
+ "explicit null on an available listing",
+ True,
+ {"isAvailableForPurchase": None},
+ ),
+ (
+ "explicit null on an unavailable listing",
+ False,
+ {"isAvailableForPurchase": None},
+ ),
+ ],
+)
+def test_variant_channel_listing_update_keeps_availability(
+ _case,
+ initial_availability,
+ availability_input,
+ staff_api_client,
+ product,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ new_price = 33
+ variant = product.variants.get()
+ listing = variant.channel_listings.get(channel=channel_USD)
+ listing.is_available_for_purchase = initial_availability
+ listing.save(update_fields=("is_available_for_purchase",))
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "price": new_price,
+ **availability_input,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingUpdate"]
+ assert data["errors"] == []
+
+ listing.refresh_from_db(fields=("is_available_for_purchase", "price_amount"))
+ assert listing.is_available_for_purchase is initial_availability
+ assert listing.price_amount == new_price
+
+
+def test_variant_channel_listing_update_sets_availability(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ new_price = 44
+ variant = product.variants.get()
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "input": [
+ {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "price": new_price,
+ "isAvailableForPurchase": False,
+ }
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingUpdate"]
+ assert data["errors"] == []
+
+ listing.refresh_from_db(fields=("is_available_for_purchase", "price_amount"))
+ assert listing.is_available_for_purchase is False
+ assert listing.price_amount == new_price
diff --git a/saleor/graphql/product/tests/test_variant_unavailable_for_purchase.py b/saleor/graphql/product/tests/test_variant_unavailable_for_purchase.py
new file mode 100644
index 0000000000..b72bad1747
--- /dev/null
+++ b/saleor/graphql/product/tests/test_variant_unavailable_for_purchase.py
@@ -0,0 +1,460 @@
+"""Behaviour of a variant channel listing with `is_available_for_purchase=False`.
+
+Such a listing must behave exactly like a variant with no listing in that channel:
+invisible to customers and impossible to buy, while its prices stay intact.
+"""
+
+from decimal import Decimal
+
+import graphene
+import pytest
+
+from ....checkout.error_codes import CheckoutErrorCode
+from ....checkout.models import Checkout
+from ....discount.utils.checkout import (
+ create_or_update_discount_objects_from_promotion_for_checkout,
+)
+from ....order.error_codes import OrderErrorCode
+from ....order.models import Order
+from ....product.models import Product, ProductVariantChannelListing
+from ....product.utils.variant_prices import update_discounted_prices_for_promotion
+from ...tests.utils import get_graphql_content
+
+PRODUCT_VARIANTS_QUERY = """
+query ProductVariants($slug: String!, $channel: String) {
+ product(slug: $slug, channel: $channel) {
+ variants {
+ id
+ }
+ }
+}
+"""
+
+PRODUCTS_QUERY = """
+query Products($channel: String!) {
+ products(first: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ pricing {
+ priceRange {
+ start {
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+MUTATION_CHECKOUT_LINES_ADD = """
+mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {
+ checkoutLinesAdd(id: $id, lines: $lines) {
+ checkout {
+ id
+ }
+ errors {
+ field
+ code
+ message
+ variants
+ }
+ }
+}
+"""
+
+DRAFT_ORDER_CREATE_MUTATION = """
+mutation DraftCreate($input: DraftOrderCreateInput!) {
+ draftOrderCreate(input: $input) {
+ errors {
+ field
+ code
+ message
+ variants
+ }
+ order {
+ id
+ }
+ }
+}
+"""
+
+
+def unavailable_variant(product, channel_USD):
+ variant = product.variants.get()
+ listing = variant.channel_listings.get(channel=channel_USD)
+ listing.is_available_for_purchase = False
+ listing.save(update_fields=("is_available_for_purchase",))
+ return variant
+
+
+def test_customer_cannot_see_the_variant(
+ api_client, product_with_two_variants, channel_USD
+):
+ # given
+ hidden_variant, visible_variant = product_with_two_variants.variants.order_by("pk")
+ listing = hidden_variant.channel_listings.get(channel=channel_USD)
+ listing.is_available_for_purchase = False
+ listing.save(update_fields=("is_available_for_purchase",))
+ variables = {
+ "slug": product_with_two_variants.slug,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["variants"] == [
+ {"id": graphene.Node.to_global_id("ProductVariant", visible_variant.pk)}
+ ]
+
+
+def test_staff_still_sees_the_variant_with_its_price(
+ staff_api_client, unavailable_variant, permission_manage_products, channel_USD
+):
+ """The whole point of the flag: staff must not lose the price."""
+ # given
+ query = """
+ query VariantListings($id: ID!) {
+ productVariant(id: $id) {
+ channelListings {
+ isAvailableForPurchase
+ price {
+ amount
+ }
+ }
+ }
+ }
+ """
+ listing = unavailable_variant.channel_listings.get(channel=channel_USD)
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", unavailable_variant.pk)
+ }
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ listings = content["data"]["productVariant"]["channelListings"]
+ assert len(listings) == 1
+ assert listings[0]["isAvailableForPurchase"] is False
+ assert listings[0]["price"]["amount"] == float(listing.price_amount)
+
+
+def test_product_without_any_available_variant_is_hidden(
+ api_client, unavailable_variant, channel_USD
+):
+ # given
+ variables = {"channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["products"]["edges"] == []
+
+
+def test_variant_stays_visible_in_a_channel_where_it_is_available(
+ api_client, product_available_in_many_channels, channel_USD, channel_PLN
+):
+ # given
+ variant = product_available_in_many_channels.variants.get()
+ listing = variant.channel_listings.get(channel=channel_USD)
+ listing.is_available_for_purchase = False
+ listing.save(update_fields=("is_available_for_purchase",))
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ slug = product_available_in_many_channels.slug
+
+ # when
+ usd_response = api_client.post_graphql(
+ PRODUCT_VARIANTS_QUERY, {"slug": slug, "channel": channel_USD.slug}
+ )
+ pln_response = api_client.post_graphql(
+ PRODUCT_VARIANTS_QUERY, {"slug": slug, "channel": channel_PLN.slug}
+ )
+
+ # then
+ assert get_graphql_content(usd_response)["data"]["product"] is None
+ assert get_graphql_content(pln_response)["data"]["product"]["variants"] == [
+ {"id": variant_id}
+ ]
+
+
+def test_checkout_lines_add_rejects_the_variant(
+ api_client, checkout, unavailable_variant
+):
+ # given
+ assert checkout.lines.exists() is False
+ variant_id = graphene.Node.to_global_id("ProductVariant", unavailable_variant.pk)
+ variables = {
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+
+ # when
+ response = api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["checkoutLinesAdd"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ assert errors[0]["variants"] == [variant_id]
+ assert checkout.lines.exists() is False
+
+
+def test_draft_order_create_rejects_the_variant(
+ staff_api_client,
+ unavailable_variant,
+ permission_group_manage_orders,
+ channel_USD,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variant_id = graphene.Node.to_global_id("ProductVariant", unavailable_variant.pk)
+ variables = {
+ "input": {
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["draftOrderCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert errors[0]["variants"] == [variant_id]
+ assert Order.objects.exists() is False
+
+
+def test_existing_checkout_line_reports_a_problem(
+ api_client, checkout_with_item, channel_USD
+):
+ # given
+ query = """
+ query CheckoutProblems($id: ID) {
+ checkout(id: $id) {
+ problems {
+ __typename
+ }
+ }
+ }
+ """
+ line = checkout_with_item.lines.get()
+ listing = line.variant.channel_listings.get(channel=channel_USD)
+ listing.is_available_for_purchase = False
+ listing.save(update_fields=("is_available_for_purchase",))
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout_with_item.pk)}
+
+ # when
+ response = api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ problems = content["data"]["checkout"]["problems"]
+ assert {problem["__typename"] for problem in problems} == {
+ "CheckoutLineProblemVariantNotAvailable"
+ }
+ assert Checkout.objects.get(pk=checkout_with_item.pk).lines.exists() is True
+
+
+def test_unavailable_variant_is_excluded_from_the_product_price_range(
+ api_client, product_with_two_variants, channel_USD
+):
+ # given
+ cheap_price = Decimal("10.00")
+ expensive_price = Decimal("20.00")
+ product = product_with_two_variants
+ cheap_variant, expensive_variant = product.variants.order_by("pk")
+
+ for variant, price in (
+ (cheap_variant, cheap_price),
+ (expensive_variant, expensive_price),
+ ):
+ variant.channel_listings.filter(channel=channel_USD).update(
+ price_amount=price, discounted_price_amount=price
+ )
+ cheap_variant.channel_listings.filter(channel=channel_USD).update(
+ is_available_for_purchase=False
+ )
+
+ update_discounted_prices_for_promotion(Product.objects.filter(pk=product.pk))
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_QUERY, {"channel": channel_USD.slug})
+
+ # then
+ content = get_graphql_content(response)
+ edges = content["data"]["products"]["edges"]
+ assert len(edges) == 1
+ price_range = edges[0]["node"]["pricing"]["priceRange"]
+ assert price_range["start"]["gross"]["amount"] == float(expensive_price)
+
+ product.refresh_from_db(fields=("id",))
+ product_listing = product.channel_listings.get(channel=channel_USD)
+ assert product_listing.discounted_price_amount == expensive_price
+
+
+def test_new_listing_defaults_to_available(product_with_two_variants, channel_PLN):
+ """A listing created without the flag — as `addVariants` does — is available."""
+ # given
+ variant = product_with_two_variants.variants.order_by("pk").first()
+ assert variant.channel_listings.filter(channel=channel_PLN).exists() is False
+
+ # when
+ listing = ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ price_amount=None,
+ currency=channel_PLN.currency_code,
+ )
+
+ # then
+ assert listing.is_available_for_purchase is True
+ assert listing.is_sellable is False
+
+
+def test_price_less_listing_stays_unsellable_despite_the_default(
+ api_client, product_with_two_variants, channel_USD
+):
+ # given
+ variant = product_with_two_variants.variants.order_by("pk").first()
+ variant.channel_listings.filter(channel=channel_USD).update(
+ price_amount=None, discounted_price_amount=None
+ )
+ listing = variant.channel_listings.get(channel=channel_USD)
+ assert listing.is_available_for_purchase is True
+
+ variables = {
+ "slug": product_with_two_variants.slug,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCT_VARIANTS_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ returned_ids = {node["id"] for node in content["data"]["product"]["variants"]}
+ assert graphene.Node.to_global_id("ProductVariant", variant.pk) not in returned_ids
+
+
+def test_checkout_complete_rejects_the_variant(api_client, checkout_with_item):
+ # given
+ mutation = """
+ mutation CheckoutComplete($id: ID) {
+ checkoutComplete(id: $id) {
+ order {
+ id
+ }
+ errors {
+ field
+ code
+ message
+ variants
+ }
+ }
+ }
+ """
+ line = checkout_with_item.lines.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ listing = line.variant.channel_listings.get(channel=checkout_with_item.channel)
+ listing.is_available_for_purchase = False
+ listing.save(update_fields=("is_available_for_purchase",))
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout_with_item.pk)}
+
+ # when
+ response = api_client.post_graphql(mutation, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["order"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "lines"
+ assert (
+ data["errors"][0]["code"]
+ == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name
+ )
+ assert data["errors"][0]["variants"] == [variant_id]
+ assert Order.objects.exists() is False
+
+
+def test_order_lines_create_rejects_the_variant(
+ staff_api_client, draft_order, unavailable_variant, permission_group_manage_orders
+):
+ # given
+ mutation = """
+ mutation OrderLinesCreate($id: ID!, $input: [OrderLineCreateInput!]!) {
+ orderLinesCreate(id: $id, input: $input) {
+ errors {
+ field
+ code
+ message
+ variants
+ }
+ orderLines {
+ id
+ }
+ }
+ }
+ """
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ lines_count = draft_order.lines.count()
+ variant_id = graphene.Node.to_global_id("ProductVariant", unavailable_variant.pk)
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": [{"variantId": variant_id, "quantity": 1}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(mutation, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"] is None
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "input"
+ assert data["errors"][0]["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert data["errors"][0]["variants"] == [variant_id]
+ assert draft_order.lines.count() == lines_count
+
+
+def test_unavailable_gift_is_not_added_to_the_checkout(
+ checkout_info, checkout_lines_info, gift_promotion_rule, channel_USD
+):
+ # given
+ ProductVariantChannelListing.objects.filter(
+ variant__in=gift_promotion_rule.gifts.all(), channel=channel_USD
+ ).update(is_available_for_purchase=False)
+ lines_count = len(checkout_lines_info)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ checkout = checkout_info.checkout
+ assert checkout.lines.filter(is_gift=True).exists() is False
+ assert checkout.lines.count() == lines_count
+ assert len(checkout_lines_info) == lines_count
diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.py
index 5931dfdb15..954566379c 100644
--- a/saleor/graphql/product/types/channels.py
+++ b/saleor/graphql/product/types/channels.py
@@ -21,6 +21,7 @@ from ....tax.utils import (
from ...account import types as account_types
from ...channel.dataloaders.by_self import ChannelByIdLoader
from ...channel.types import Channel
+from ...core.descriptions import ADDED_IN_323
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
from ...core.fields import PermissionsField
from ...core.scalars import Date, DateTime
@@ -308,6 +309,13 @@ class ProductVariantChannelListing(
"promotion information required by customer protection laws such as EU Omnibus "
"directive.\n\n Warning: This field is not updated automatically. Use Channel Listings mutation to update it manually.",
)
+ is_available_for_purchase = graphene.Boolean(
+ required=True,
+ description="Determines whether the variant can be bought in this channel. "
+ "When set to `false`, the variant behaves as if it had no listing in this "
+ "channel: it is hidden from customers and cannot be added to a checkout or "
+ "an order. Its prices are preserved." + ADDED_IN_323,
+ )
margin = PermissionsField(
graphene.Int,
description="Gross margin percentage value.",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 2da31712c5..f03c997a04 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -7552,6 +7552,13 @@ type ProductVariantChannelListing implements Node @doc(category: "Products") {
"""
priorPrice: Money
+ """
+ Determines whether the variant can be bought in this channel. When set to `false`, the variant behaves as if it had no listing in this channel: it is hidden from customers and cannot be added to a checkout or an order. Its prices are preserved.
+
+ Added in Saleor 3.23.
+ """
+ isAvailableForPurchase: Boolean!
+
"""
Gross margin percentage value.
@@ -19280,6 +19287,26 @@ type Mutation {
sku: String
): ProductVariantChannelListingUpdate @doc(category: "Products")
+ """
+ Toggle whether a product variant can be bought in the given channels, without touching its prices. An unavailable variant is hidden from customers and cannot be added to a checkout or an order.
+
+ Added in Saleor 3.23.
+
+ Requires one of the following permissions: MANAGE_PRODUCTS.
+ """
+ productVariantChannelListingAvailabilityUpdate(
+ """ID of a product variant to update."""
+ id: ID
+
+ """
+ List of channels to toggle the variant's availability in. Max 100 items.
+ """
+ input: [ProductVariantChannelListingAvailabilityInput!]!
+
+ """SKU of a product variant to update."""
+ sku: String
+ ): ProductVariantChannelListingAvailabilityUpdate @doc(category: "Products")
+
"""
Reorder product variant attribute values.
@@ -25540,6 +25567,13 @@ input ProductVariantChannelListingAddInput @doc(category: "Products") {
Previous price of the variant in channel. Useful for providing promotion information required by customer protection laws such as EU Omnibus directive.
"""
priorPrice: PositiveDecimal
+
+ """
+ Determines whether the variant can be bought in this channel. When omitted on an existing listing, the current value is kept.
+
+ Added in Saleor 3.23.
+ """
+ isAvailableForPurchase: Boolean
}
"""
@@ -26318,6 +26352,13 @@ input ChannelListingUpdateInput @doc(category: "Products") {
"""Price of the variant before discount."""
priorPrice: PositiveDecimal
+
+ """
+ Determines whether the variant can be bought in this channel. When omitted, the current value is kept.
+
+ Added in Saleor 3.23.
+ """
+ isAvailableForPurchase: Boolean
}
"""
@@ -26597,6 +26638,53 @@ type ProductVariantChannelListingUpdate @doc(category: "Products") {
errors: [ProductChannelListingError!]!
}
+"""
+Toggle whether a product variant can be bought in the given channels, without touching its prices. An unavailable variant is hidden from customers and cannot be added to a checkout or an order.
+
+Added in Saleor 3.23.
+
+Requires one of the following permissions: MANAGE_PRODUCTS.
+"""
+type ProductVariantChannelListingAvailabilityUpdate @doc(category: "Products") {
+ """An updated product variant instance."""
+ variant: ProductVariant
+ errors: [ProductVariantChannelListingAvailabilityUpdateError!]!
+}
+
+"""
+Error of the `productVariantChannelListingAvailabilityUpdate` mutation.
+
+Added in Saleor 3.23.
+"""
+type ProductVariantChannelListingAvailabilityUpdateError @doc(category: "Products") {
+ """
+ Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field.
+ """
+ field: String
+
+ """The error message."""
+ message: String
+
+ """The error code."""
+ code: ProductErrorCode!
+
+ """List of channels IDs which causes the error."""
+ channels: [ID!]
+}
+
+"""
+Fields required to toggle a product variant's availability in a channel.
+
+Added in Saleor 3.23.
+"""
+input ProductVariantChannelListingAvailabilityInput @doc(category: "Products") {
+ """ID of a channel."""
+ channelId: ID!
+
+ """Determines whether the variant can be bought in this channel."""
+ isAvailableForPurchase: Boolean!
+}
+
"""
Reorder product variant attribute values.
diff --git a/saleor/product/lock_objects.py b/saleor/product/lock_objects.py
index e82644ee7d..3fdb17e995 100644
--- a/saleor/product/lock_objects.py
+++ b/saleor/product/lock_objects.py
@@ -1,13 +1,21 @@
from django.db.models import QuerySet
from ..core.db.locks import AdvisoryLock, acquire_advisory_xact_lock
-from .models import Category, Product
+from .models import Category, Product, ProductVariantChannelListing
def product_qs_select_for_update() -> QuerySet[Product]:
return Product.objects.order_by("pk").select_for_update(of=(["self"]))
+def product_variant_channel_listing_qs_select_for_update() -> QuerySet[
+ ProductVariantChannelListing
+]:
+ return ProductVariantChannelListing.objects.order_by("pk").select_for_update(
+ of=["self"]
+ )
+
+
def category_qs_select_for_update() -> QuerySet[Category]:
return Category.objects.order_by("pk").select_for_update(of=["self"])
diff --git a/saleor/product/managers.py b/saleor/product/managers.py
index c692a32ccc..a7f814c290 100644
--- a/saleor/product/managers.py
+++ b/saleor/product/managers.py
@@ -60,10 +60,8 @@ class ProductsQueryset(models.QuerySet):
return self.none()
variant_channel_listings = (
ProductVariantChannelListing.objects.using(self.db)
- .filter(
- channel_id=channel.id,
- price_amount__isnull=False,
- )
+ .sellable()
+ .filter(channel_id=channel.id)
.values("id")
)
variants = ProductVariant.objects.using(self.db).filter(
@@ -268,6 +266,20 @@ class ProductsQueryset(models.QuerySet):
ProductManager = models.Manager.from_queryset(ProductsQueryset)
+def sellable_listing_q(prefix: str = "") -> Q:
+ """Q matching a variant channel listing a customer can actually buy.
+
+ `prefix` is the lookup path to the listing, e.g. `"channel_listings__"`, so the
+ same definition can be applied from a related model.
+ """
+ return Q(
+ **{
+ f"{prefix}price_amount__isnull": False,
+ f"{prefix}is_available_for_purchase": True,
+ }
+ )
+
+
class ProductVariantQueryset(models.QuerySet):
def annotate_quantities(self):
"""Annotate the queryset with quantity-related fields.
@@ -314,7 +326,8 @@ class ProductVariantQueryset(models.QuerySet):
return self.none()
channel_listings = (
ProductVariantChannelListing.objects.using(self.db)
- .filter(price_amount__isnull=False, channel_id=channel.id)
+ .sellable()
+ .filter(channel_id=channel.id)
.values("id")
)
return self.filter(Exists(channel_listings.filter(variant_id=OuterRef("pk"))))
@@ -354,8 +367,8 @@ class ProductVariantQueryset(models.QuerySet):
# - have a product channel listing for this channel and the product is published
# and visible in listings
variants = self.filter(
+ sellable_listing_q("channel_listings__"),
channel_listings__channel_id=channel.id,
- channel_listings__price_amount__isnull=False,
)
today = datetime.datetime.now(tz=datetime.UTC)
@@ -373,6 +386,9 @@ ProductVariantManager = models.Manager.from_queryset(ProductVariantQueryset)
class ProductVariantChannelListingQuerySet(models.QuerySet):
+ def sellable(self):
+ return self.filter(sellable_listing_q())
+
def annotate_preorder_quantity_allocated(self):
return self.annotate(
preorder_quantity_allocated=Coalesce(
diff --git a/saleor/product/migrations/0215_productvariantchannellisting_is_available_for_purchase.py b/saleor/product/migrations/0215_productvariantchannellisting_is_available_for_purchase.py
new file mode 100644
index 0000000000..4e4ee2f0dd
--- /dev/null
+++ b/saleor/product/migrations/0215_productvariantchannellisting_is_available_for_purchase.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0214_collection_translation_full_description"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="productvariantchannellisting",
+ name="is_available_for_purchase",
+ field=models.BooleanField(db_default=True, default=True),
+ ),
+ ]
diff --git a/saleor/product/migrations/0216_merge_20261014_0742.py b/saleor/product/migrations/0216_merge_20261014_0742.py
new file mode 100644
index 0000000000..1e6d9987a5
--- /dev/null
+++ b/saleor/product/migrations/0216_merge_20261014_0742.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.16 on 2026-10-14 07:42
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0215_merge_20261010_1621"),
+ ("product", "0215_productvariantchannellisting_is_available_for_purchase"),
+ ]
+
+ operations = []
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 30945cf2aa..083d798ec0 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -550,6 +550,8 @@ class ProductVariantChannelListing(models.Model):
# TODO remove after 3.24: preorder API was removed in 3.24
preorder_quantity_threshold = models.IntegerField(blank=True, null=True)
+ is_available_for_purchase = models.BooleanField(default=True, db_default=True)
+
objects = managers.ProductVariantChannelListingManager()
class Meta:
@@ -559,6 +561,14 @@ class ProductVariantChannelListing(models.Model):
GinIndex(fields=["price_amount", "channel_id"]),
]
+ @property
+ def is_sellable(self) -> bool:
+ """Whether the variant can be bought in this channel.
+
+ In-Python twin of `managers.sellable_listing_q`; keep the two in sync.
+ """
+ return self.price_amount is not None and self.is_available_for_purchase
+
class VariantChannelListingPromotionRule(models.Model):
variant_channel_listing = models.ForeignKey(
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 5769cfe219..6afa5e34d8 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -183,7 +183,7 @@ def get_variant_availability(
tax_calculation_strategy: str,
tax_rate: Decimal,
) -> VariantAvailability | None:
- if variant_channel_listing.price is None:
+ if not variant_channel_listing.is_sellable:
return None
discounted_price_taxed = _calculate_product_price_with_taxes(
variant_channel_listing.discounted_price,
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 7d6a57de5f..a85241d7ea 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -199,8 +199,8 @@ def _create_variant_listing_promotion_rule(variant_listing_promotion_rule_to_cre
def _get_product_to_variant_channel_listings_per_channel_map(
variants: ProductVariantQueryset,
):
- variant_channel_listings = ProductVariantChannelListing.objects.filter(
- Exists(variants.filter(id=OuterRef("variant_id"))), price_amount__isnull=False
+ variant_channel_listings = ProductVariantChannelListing.objects.sellable().filter(
+ Exists(variants.filter(id=OuterRef("variant_id")))
)
variant_to_product_id = dict(
variants.values_list("id", "product_id").iterator(chunk_size=1000)
@@ -235,8 +235,8 @@ def _get_variant_listings_to_listing_rule_per_rule_id_map(
variant_listing_rule_data: dict[
int, dict[UUID, VariantChannelListingPromotionRule]
] = defaultdict(dict)
- variant_channel_listings = ProductVariantChannelListing.objects.filter(
- Exists(variants.filter(id=OuterRef("variant_id"))), price_amount__isnull=False
+ variant_channel_listings = ProductVariantChannelListing.objects.sellable().filter(
+ Exists(variants.filter(id=OuterRef("variant_id")))
)
variant_listing_promotion_rules = VariantChannelListingPromotionRule.objects.filter(
Exists(