Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Update "minimal_variant_price"
Mateusz Dereniowskidc6f56e7802a
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.pyindex 36c802a291..5a598b30af 100644--- a/saleor/dashboard/discount/forms.py+++ b/saleor/dashboard/discount/forms.py@@ -11,6 +11,9 @@ from ...core.utils.promo_code import generate_promo_codefrom ...discount import DiscountValueTypefrom ...discount.models import Sale, Voucherfrom ...product.models import Category, Product+from ...product.utils.variant_prices import (+ update_products_minimal_variant_prices_of_discount,+)from ..forms import AjaxSelect2MultipleChoiceFieldMinAmountSpent = MoneyField(@@ -76,6 +79,11 @@ class SaleForm(forms.ModelForm):)return cleaned_data+ def save(self, commit=True):+ instance = super().save(commit=commit)+ update_products_minimal_variant_prices_of_discount(instance)+ return instance+class VoucherForm(forms.ModelForm):class Meta:diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 98f3c7a88a..6480d5bd4b 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -26,6 +26,7 @@ from ...product.models import (from ...product.tasks import update_variants_namesfrom ...product.thumbnails import create_product_thumbnailsfrom ...product.utils.attributes import get_name_from_attributes+from ...product.utils.variant_prices import update_product_minimal_variant_pricefrom ..forms import ModelChoiceOrCreationField, OrderedModelMultipleChoiceFieldfrom ..seo.fields import SeoDescriptionField, SeoTitleFieldfrom ..seo.utils import prepare_seo_description@@ -256,7 +257,13 @@ class ProductForm(forms.ModelForm, AttributesMixin):class Meta:model = Product- exclude = ["attributes", "product_type", "updated_at", "description_json"]+ exclude = [+ "attributes",+ "product_type",+ "updated_at",+ "description_json",+ "minimal_variant_price",+ ]labels = {"name": pgettext_lazy("Item name", "Name"),"price": pgettext_lazy("Currency amount", "Price"),@@ -327,6 +334,7 @@ class ProductForm(forms.ModelForm, AttributesMixin):instance.collections.clear()for collection in self.cleaned_data["collections"]:instance.collections.add(collection)+ update_product_minimal_variant_price(instance)return instance@@ -411,7 +419,9 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):"values__translations")self.instance.name = get_name_from_attributes(self.instance, attrs)- return super().save(commit=commit)+ instance = super().save(commit=commit)+ update_product_minimal_variant_price(instance.product)+ return instanceclass CachingModelChoiceIterator(ModelChoiceIterator):diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 2dbce15d79..c485650cdb 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -19,6 +19,7 @@ from ...product.models import ()from ...product.utils.availability import get_product_availabilityfrom ...product.utils.costs import get_margin_for_variant, get_product_costs_data+from ...product.utils.variant_prices import update_product_minimal_variant_pricefrom ..views import staff_member_requiredfrom . import formsfrom .filters import AttributeFilter, ProductFilter, ProductTypeFilter@@ -372,6 +373,7 @@ def variant_delete(request, product_pk, variant_pk):variant = get_object_or_404(product.variants, pk=variant_pk)if request.method == "POST":variant.delete()+ update_product_minimal_variant_price(variant.product)msg = pgettext_lazy("Dashboard message", "Removed variant %s") % (variant.name,)messages.success(request, msg)return redirect("dashboard:product-details", pk=product.pk)diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex d9573460c3..442d2cc8db 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -169,3 +169,7 @@ def fetch_discounts(date: datetime.date):)for sale in sales]+++def fetch_active_discounts():+ return fetch_discounts(datetime.date.today())diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex de128e8b54..9a76a6ac2e 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -489,6 +489,8 @@ class ProductCreate(ModelMutation):price = data.get("base_price", data.get("price"))if price is not None:cleaned_input["price"] = price+ # Set the default "minimal_variant_price" to the "price"+ cleaned_input["minimal_variant_price"] = price# FIXME tax_rate logic should be dropped after we remove tax_rate from inputtax_rate = cleaned_input.pop("tax_rate", "")diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 4c92fb6b3b..0836dcd7e1 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -408,6 +408,9 @@ class Product(CountableDjangoObjectType, MetadataObjectType):description="The product's default base price.",deprecation_reason=("Has been replaced by 'basePrice'"),)+ minimal_variant_price = graphene.Field(+ Money, description="The price of the cheapest variant (including discounts)."+ )tax_rate = TaxRateType(description="A type of tax rate.",deprecation_reason=(diff --git a/saleor/product/models.py b/saleor/product/models.pyindex c730bdfe03..dd835bb5f9 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -141,6 +141,30 @@ class ProductType(ModelWithMetadata):class ProductsQueryset(PublishedQuerySet):+ def create(self, **kwargs):+ """+ Create a product.++ In the case of absent "minimal_variant_price" make it default to the "price"+ """+ if "minimal_variant_price" not in kwargs:+ kwargs["minimal_variant_price"] = kwargs.get("price")+ return super().create(**kwargs)++ def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):+ """+ Insert each of the product instances into the database.++ Make sure every product has "minimal_variant_price" set. Otherwise+ make it default to the "price".+ """+ for obj in objs:+ if obj.minimal_variant_price is None:+ obj.minimal_variant_price = obj.price+ return super().bulk_create(+ objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts+ )+def collection_sorted(self, user):qs = self.visible_to_user(user).prefetch_related("collections__products__collectionproduct"@@ -212,6 +236,14 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):def __str__(self):return self.name+ def save(+ self, force_insert=False, force_update=False, using=None, update_fields=None+ ):+ # Make sure the "minimal_variant_price" is set+ if self.minimal_variant_price is None:+ self.minimal_variant_price = self.price+ return super().save(force_insert, force_update, using, update_fields)+@propertydef plain_text_description(self):if settings.USE_JSON_CONTENT:@@ -272,6 +304,39 @@ class ProductTranslation(SeoModelTranslation):)+class ProductVariantQueryset(models.QuerySet):+ def create(self, **kwargs):+ """+ Create a product's variant.++ After the creation update the "minimal_variant_price" of the product.+ """+ variant = super().create(**kwargs)+ from .utils.variant_prices import update_product_minimal_variant_price++ update_product_minimal_variant_price(variant.product)+ return variant++ def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):+ """+ Insert each of the product's variant instances into the database.++ After the creation update the "minimal_variant_price" of all the products.+ """+ variants = super().bulk_create(+ objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts+ )+ products_map = {}+ for obj in objs:+ product = obj.product+ products_map[product.pk] = product+ products = products_map.values()+ from .utils.variant_prices import update_products_minimal_variant_prices++ update_products_minimal_variant_prices(products)+ return variants++class ProductVariant(ModelWithMetadata):sku = models.CharField(max_length=32, unique=True)name = models.CharField(max_length=255, blank=True)@@ -306,6 +371,8 @@ class ProductVariant(ModelWithMetadata):weight = MeasurementField(measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True)++ objects = ProductVariantQueryset.as_manager()translated = TranslationProxy()class Meta:diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex df0c2143b7..5b23c246ef 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -1,6 +1,11 @@from ..celeryconf import app+from ..discount.models import Salefrom .models import Attribute, ProductType, ProductVariantfrom .utils.attributes import get_name_from_attributes+from .utils.variant_prices import (+ update_products_minimal_variant_prices,+ update_products_minimal_variant_prices_of_discount,+)def _update_variants_names(instance, saved_attributes):@@ -31,3 +36,14 @@ def update_variants_names(product_type_pk, saved_attributes_ids):instance = ProductType.objects.get(pk=product_type_pk)saved_attributes = Attribute.objects.filter(pk__in=saved_attributes_ids)return _update_variants_names(instance, saved_attributes)+++def update_all_products_minimal_variant_prices_task():+ update_products_minimal_variant_prices()+++def update_products_minimal_variant_prices_of_discount_task(discount_pk):+ discount = Sale.objects.get(pk=discount_pk)+ update_products_minimal_variant_prices_of_discount(discount)diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pynew file mode 100644index 0000000000..9b10e8b4d2--- /dev/null+++ b/saleor/product/utils/variant_prices.py@@ -0,0 +1,47 @@+from prices.taxed_money import TaxedMoney++from ...discount.utils import fetch_active_discounts+from ..models import Product+++def _get_product_minimal_variant_price(product, discounts):+ # Start with the product's price as the minimal one+ minimal_variant_price = product.price+ for variant in product.variants.all():+ variant_price = variant.get_price(discounts=discounts)+ if isinstance(variant_price, TaxedMoney):+ # The "variant.get_price" method may return "TaxedMoney" instance but+ # because we haven't provided it with "taxes" kwarg we can ignore it+ # and "cast" it to just "Money" by taking net/gross (we take gross+ # just in case)+ variant_price = variant_price.gross+ minimal_variant_price = min(minimal_variant_price, variant_price)+ return minimal_variant_price+++def update_product_minimal_variant_price(product, discounts=None):+ if discounts is None:+ discounts = fetch_active_discounts()+ minimal_variant_price = _get_product_minimal_variant_price(product, discounts)+ if product.minimal_variant_price != minimal_variant_price:+ product.minimal_variant_price = minimal_variant_price+ product.save(update_fields=["minimal_variant_price"])+ return product+++def update_products_minimal_variant_prices(products=None, discounts=None):+ if products is None:+ products = Product.objects.prefetch_related("variants").iterator()+ if discounts is None:+ discounts = fetch_active_discounts()+ for product in products:+ update_product_minimal_variant_price(product, discounts)+++def update_products_minimal_variant_prices_of_discount(discount):+ all_discounts = fetch_active_discounts()+ update_products_minimal_variant_prices(discount.products.all(), all_discounts)+ for category in discount.categories.all():+ update_products_minimal_variant_prices(category.products.all(), all_discounts)+ for collection in discount.collections.all():+ update_products_minimal_variant_prices(collection.products.all(), all_discounts)