Skip to content

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

Add is_available_for_purchase product method

IKarbowiak7f841e468194
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 7ec5ab39e4..7da1ca9632 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -1,4 +1,3 @@
-import datetime
from typing import List, Optional, Tuple
import graphene
@@ -142,8 +141,7 @@ def validate_variants_available_for_purchase(variants):
not_available_variants = [
variant.pk
for variant in variants
- if not variant.product.available_for_purchase
- or datetime.date.today() < variant.product.available_for_purchase
+ if not variant.product.is_available_for_purchase()
]
if not_available_variants:
variant_ids = [
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 6e7dfb4f66..fccaeeede3 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,5 +1,3 @@
-import datetime
-
from django.core.exceptions import ValidationError
from ...core.exceptions import InsufficientStock
@@ -78,10 +76,7 @@ def validate_product_is_published(order):
def validate_product_is_available_for_purchase(order):
for line in order:
- if (
- not line.variant.product.available_for_purchase
- or datetime.date.today() < line.variant.product.available_for_purchase
- ):
+ if not line.variant.product.is_available_for_purchase():
raise ValidationError(
{
"lines": ValidationError(
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 2469623b2d..5557b10151 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -1,4 +1,3 @@
-import datetime
from dataclasses import asdict
from typing import List, Union
@@ -637,9 +636,7 @@ class Product(CountableDjangoObjectType):
@staticmethod
def resolve_is_available_for_purchase(root: models.Product, _info):
- if root.available_for_purchase is None:
- return False
- return datetime.date.today() >= root.available_for_purchase
+ return root.is_available_for_purchase()
@key(fields="id")
diff --git a/saleor/product/models.py b/saleor/product/models.py
index c4312a57bb..f253253da4 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -1,3 +1,4 @@
+import datetime
from typing import TYPE_CHECKING, Iterable, Optional, Union
from uuid import uuid4
@@ -304,6 +305,12 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):
def sort_by_attribute_fields() -> list:
return ["concatenated_values_order", "concatenated_values", "name"]
+ def is_available_for_purchase(self):
+ return (
+ self.available_for_purchase is not None
+ and datetime.date.today() >= self.available_for_purchase
+ )
+
class ProductTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)