Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove price field from product/Create price field for product variant
Damian W42b375ce77c4
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex 13df6d9960..35c9a73f8c 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -298,9 +298,6 @@ class ProductFilter(django_filters.FilterSet):collections = GlobalIDMultipleChoiceFilter(method=filter_collections)categories = GlobalIDMultipleChoiceFilter(method=filter_categories)has_category = django_filters.BooleanFilter(method=filter_has_category)- price = ObjectTypeFilter(- input_class=PriceRangeInput, method=filter_price, field_name="price_amount"- )minimal_price = ObjectTypeFilter(input_class=PriceRangeInput,method=filter_minimal_price,@@ -324,7 +321,6 @@ class ProductFilter(django_filters.FilterSet):"collections","categories","has_category",- "price","attributes","stock_availability","product_type",diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 28c3f0817c..230025bd86 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -516,7 +516,6 @@ class ProductInput(graphene.InputObjectType):)name = graphene.String(description="Product name.")slug = graphene.String(description="Product slug.")- base_price = Decimal(description="Product price.")tax_code = graphene.String(description="Tax rate for enabled tax gateway.")seo = SeoInput(description="Search engine optimization fields.")weight = WeightScalar(description="Weight of the Product.", required=False)@@ -831,23 +830,6 @@ class ProductCreate(ModelMutation):except ValidationError as error:error.code = ProductErrorCode.REQUIRED.valueraise ValidationError({"slug": error})- # Try to get price from "basePrice" or "price" field. Once "price" is removed- # from the schema, only "basePrice" should be used here.- price = data.get("base_price", data.get("price"))- if price is not None:- if price < 0:- raise ValidationError(- {- "basePrice": ValidationError(- "Product base price cannot be lower than 0.",- code=ProductErrorCode.INVALID,- )- }- )- cleaned_input["price_amount"] = price- if instance.minimal_variant_price_amount is None:- # Set the default "minimal_variant_price" to the "price"- cleaned_input["minimal_variant_price_amount"] = price# FIXME tax_rate logic should be dropped after we remove tax_rate from inputtax_rate = cleaned_input.pop("tax_rate", "")@@ -1097,7 +1079,7 @@ class ProductVariantInput(graphene.InputObjectType):description="List of attributes specific to this variant.",)cost_price = Decimal(description="Cost price of the variant.")- price_override = Decimal(description="Special price of the particular variant.")+ price = Decimal(description="Price of the particular variant.")sku = graphene.String(description="Stock keeping unit.")track_inventory = graphene.Boolean(description=(@@ -1194,18 +1176,17 @@ class ProductVariantCreate(ModelMutation):)cleaned_input["cost_price_amount"] = cost_price- if "price_override" in cleaned_input:- price_override = cleaned_input.pop("price_override")- if price_override and price_override < 0:- raise ValidationError(- {- "priceOverride": ValidationError(- "Product price cannot be lower than 0.",- code=ProductErrorCode.INVALID.value,- )- }- )- cleaned_input["price_override_amount"] = price_override+ price = cleaned_input.pop("price")+ if price < 0:+ raise ValidationError(+ {+ "price": ValidationError(+ "Product price cannot be lower than 0.",+ code=ProductErrorCode.INVALID.value,+ )+ }+ )+ cleaned_input["price_amount"] = pricestocks = cleaned_input.get("stocks")if stocks:diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.pyindex 05f8ad8efb..4aad41af93 100644--- a/saleor/graphql/product/sorters.py+++ b/saleor/graphql/product/sorters.py@@ -131,7 +131,6 @@ class CollectionSortingInput(SortInputObjectType):class ProductOrderField(graphene.Enum):NAME = ["name", "slug"]- PRICE = ["price_amount", "name", "slug"]MINIMAL_PRICE = ["minimal_variant_price_amount", "name", "slug"]DATE = ["updated_at", "name", "slug"]TYPE = ["product_type__name", "name", "slug"]@@ -142,7 +141,6 @@ class ProductOrderField(graphene.Enum):# pylint: disable=no-memberdescriptions = {ProductOrderField.NAME.name: "name",- ProductOrderField.PRICE.name: "price",ProductOrderField.TYPE.name: "type",ProductOrderField.MINIMAL_PRICE.name: ("a minimal price of a product's variant"diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex b2f5b22b11..a168cb4598 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -192,13 +192,7 @@ class ProductVariant(CountableDjangoObjectType):"This field will be removed after 2020-07-31."),)- price_override = graphene.Field(- Money,- description=(- "Override the base price of a product if necessary. A value of `null` "- "indicates that the default product price is used."- ),- )+ price = graphene.Field(Money, description=("Base price of a product variant."),)pricing = graphene.Field(VariantPricingInfo,description=(@@ -308,7 +302,7 @@ class ProductVariant(CountableDjangoObjectType):@staticmethoddef resolve_price(root: models.ProductVariant, *_args):- return root.base_price+ return root.price@staticmethoddef resolve_pricing(root: models.ProductVariant, info):@@ -349,11 +343,6 @@ class ProductVariant(CountableDjangoObjectType):country = info.context.countryreturn is_variant_in_stock(root, country)- @staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)- def resolve_price_override(root: models.ProductVariant, *_args):- return root.price_override-@staticmethod@permission_required(ProductPermissions.MANAGE_PRODUCTS)def resolve_quantity(root: models.ProductVariant, info):@@ -427,7 +416,6 @@ class Product(CountableDjangoObjectType):is_available = graphene.Boolean(description="Whether the product is in stock and visible or not.")- base_price = graphene.Field(Money, description="The product's default base price.")minimal_variant_price = graphene.Field(Money, description="The price of the cheapest variant (including discounts).")@@ -547,28 +535,6 @@ class Product(CountableDjangoObjectType):in_stock = is_product_in_stock(root, country)return root.is_visible and in_stock- @staticmethod- @permission_required(ProductPermissions.MANAGE_PRODUCTS)- def resolve_base_price(root: models.Product, _info):- return root.price-- @staticmethod- def resolve_price(root: models.Product, info):- context = info.context-- def calculate_price(discounts):- price_range = root.get_price_range(discounts)- price = info.context.plugins.apply_taxes_to_product(- root, price_range.start, info.context.country- )- return price.net-- return (- DiscountsByDateTimeLoader(context)- .load(info.context.request_time)- .then(calculate_price)- )-@staticmethoddef resolve_attributes(root: models.Product, info):return SelectedAttributesByProductIdLoader(info.context).load(root.id)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3d88863652..7b4763a1f7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3319,7 +3319,6 @@ type Product implements Node & ObjectWithMetadata {thumbnail(size: Int): Imagepricing: ProductPricingInfoisAvailable: Boolean- basePrice: MoneyminimalVariantPrice: MoneytaxType: TaxTypeattributes: [SelectedAttribute!]!@@ -3391,7 +3390,6 @@ input ProductCreateInput {isPublished: Booleanname: Stringslug: String- basePrice: DecimaltaxCode: Stringseo: SeoInputweight: WeightScalar@@ -3433,7 +3431,6 @@ input ProductFilterInput {collections: [ID]categories: [ID]hasCategory: Boolean- price: PriceRangeInputattributes: [AttributeInput]stockAvailability: StockAvailabilityproductType: ID@@ -3505,7 +3502,6 @@ input ProductInput {isPublished: Booleanname: Stringslug: String- basePrice: DecimaltaxCode: Stringseo: SeoInputweight: WeightScalar@@ -3521,7 +3517,6 @@ input ProductOrder {enum ProductOrderField {NAME- PRICEMINIMAL_PRICEDATETYPE@@ -3726,7 +3721,7 @@ type ProductVariant implements Node & ObjectWithMetadata {quantity: Int! @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")quantityAllocated: Int @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")stockQuantity: Int! @deprecated(reason: "Use the quantityAvailable field instead. This field will be removed after 2020-07-31.")- priceOverride: Money+ price: Moneypricing: VariantPricingInfoisAvailable: Boolean @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")attributes: [SelectedAttribute!]!@@ -3751,7 +3746,7 @@ type ProductVariantBulkCreate {input ProductVariantBulkCreateInput {attributes: [AttributeValueInput]!costPrice: Decimal- priceOverride: Decimal+ price: Decimalsku: String!trackInventory: Booleanweight: WeightScalar@@ -3796,7 +3791,7 @@ type ProductVariantCreate {input ProductVariantCreateInput {attributes: [AttributeValueInput]!costPrice: Decimal- priceOverride: Decimal+ price: Decimalsku: StringtrackInventory: Booleanweight: WeightScalar@@ -3813,7 +3808,7 @@ type ProductVariantDelete {input ProductVariantInput {attributes: [AttributeValueInput]costPrice: Decimal- priceOverride: Decimal+ price: Decimalsku: StringtrackInventory: Booleanweight: WeightScalardiff --git a/saleor/product/migrations/0118_populate_product_variant_price.py b/saleor/product/migrations/0118_populate_product_variant_price.pynew file mode 100644index 0000000000..9eadb30b16--- /dev/null+++ b/saleor/product/migrations/0118_populate_product_variant_price.py@@ -0,0 +1,40 @@+# Generated by Django 3.0.6 on 2020-05-27 08:14++from django.db import migrations, models+++def populate_product_variant_price(apps, schema_editor):+ ProductVariant = apps.get_model("product", "ProductVariant")+ for product_variant in ProductVariant.objects.iterator():+ price_override_amount = product_variant.price_override_amount+ if price_override_amount:+ product_variant.price_amount = price_override_amount+ else:+ product_price = product_variant.product.price_amount+ product_variant.price_amount = product_price++ product_variant.save(update_fields=["price_amount"])+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0117_auto_20200423_0737"),+ ]++ operations = [+ migrations.AddField(+ model_name="productvariant",+ name="price_amount",+ field=models.DecimalField(decimal_places=2, max_digits=12, null=True),+ ),+ migrations.RunPython(populate_product_variant_price),+ migrations.AlterField(+ model_name="productvariant",+ name="price_amount",+ field=models.DecimalField(decimal_places=2, max_digits=12),+ ),+ migrations.RemoveField(+ model_name="productvariant", name="price_override_amount",+ ),+ ]diff --git a/saleor/product/migrations/0119_auto_20200527_0402.py b/saleor/product/migrations/0119_auto_20200527_0402.pynew file mode 100644index 0000000000..7552f85f35--- /dev/null+++ b/saleor/product/migrations/0119_auto_20200527_0402.py@@ -0,0 +1,21 @@+# Generated by Django 3.0.6 on 2020-05-27 09:02++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0118_populate_product_variant_price"),+ ]++ operations = [+ migrations.RemoveField(model_name="product", name="price_amount",),+ migrations.AlterField(+ model_name="product",+ name="minimal_variant_price_amount",+ field=models.DecimalField(+ blank=True, decimal_places=2, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex df6ab80be7..b2084b7734 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -118,35 +118,6 @@ class ProductType(ModelWithMetadata):class ProductsQueryset(PublishedQuerySet):- MINIMAL_PRICE_FIELDS = {"minimal_variant_price_amount", "minimal_variant_price"}-- def create(self, **kwargs):- """Create a product.-- In the case of absent "minimal_variant_price" make it default to the "price"- """- if not kwargs.keys() & self.MINIMAL_PRICE_FIELDS:- minimal_amount = None- if "price" in kwargs:- minimal_amount = kwargs["price"].amount- elif "price_amount" in kwargs:- minimal_amount = kwargs["price_amount"]- kwargs["minimal_variant_price_amount"] = minimal_amount- 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_amount is None:- obj.minimal_variant_price_amount = obj.price.amount- return super().bulk_create(- objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts- )-def collection_sorted(self, user: "User"):qs = self.visible_to_user(user)qs = qs.order_by(@@ -273,15 +244,11 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):default=settings.DEFAULT_CURRENCY,)- price_amount = models.DecimalField(- max_digits=settings.DEFAULT_MAX_DIGITS,- decimal_places=settings.DEFAULT_DECIMAL_PLACES,- )- price = MoneyField(amount_field="price_amount", currency_field="currency")-minimal_variant_price_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ blank=True,+ null=True,)minimal_variant_price = MoneyField(amount_field="minimal_variant_price_amount", currency_field="currency"@@ -318,15 +285,6 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):def __str__(self) -> str:return self.name- def save(- self, force_insert=False, force_update=False, using=None, update_fields=None- ):- # Make sure the "minimal_variant_price_amount" is set- if self.minimal_variant_price_amount is None:- self.minimal_variant_price_amount = self.price_amount-- return super().save(force_insert, force_update, using, update_fields)-@propertydef plain_text_description(self) -> str:return json_content_to_raw_text(self.description_json)@@ -337,20 +295,14 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):def get_price_range(self, discounts: Optional[Iterable[DiscountInfo]] = None- ) -> MoneyRange:+ ) -> Optional[MoneyRange]:import opentracingwith opentracing.global_tracer().start_active_span("get_price_range"):if self.variants.all():prices = [variant.get_price(discounts) for variant in self]return MoneyRange(min(prices), max(prices))- price = calculate_discounted_price(- product=self,- price=self.price,- collections=self.collections.all(),- discounts=discounts,- )- return MoneyRange(start=price, stop=price)+ return None@staticmethoddef sort_by_attribute_fields() -> list:@@ -427,15 +379,11 @@ class ProductVariant(ModelWithMetadata):blank=True,null=True,)- price_override_amount = models.DecimalField(+ price_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,- blank=True,- null=True,- )- price_override = MoneyField(- amount_field="price_override_amount", currency_field="currency")+ price = MoneyField(amount_field="price_amount", currency_field="currency")product = models.ForeignKey(Product, related_name="variants", on_delete=models.CASCADE)@@ -467,18 +415,10 @@ class ProductVariant(ModelWithMetadata):def is_visible(self) -> bool:return self.product.is_visible- @property- def base_price(self) -> "Money":- return (- self.price_override- if self.price_override is not None- else self.product.price- )-def get_price(self, discounts: Optional[Iterable[DiscountInfo]] = None) -> "Money":return calculate_discounted_price(product=self.product,- price=self.base_price,+ price=self.price,collections=self.product.collections.all(),discounts=discounts,)diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex 33bbbf7a76..a704850d3d 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -3,10 +3,11 @@ from typing import TYPE_CHECKING, Iterable, Optional, Tuple, Unionimport opentracingfrom django.conf import settings-from prices import MoneyRange, TaxedMoney, TaxedMoneyRange+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRangefrom saleor.product.models import Collection, Product, ProductVariant+from ...core.taxes import zero_moneyfrom ...core.utils import to_local_currencyfrom ...discount import DiscountInfofrom ...discount.utils import calculate_discounted_price@@ -114,12 +115,6 @@ def _get_product_price_range(return price_range_local, discount_local_currency-def get_variant_base_price(*, variant: ProductVariant, product: Product):- return (- variant.price_override if variant.price_override is not None else product.price- )--def get_variant_price(*,variant: ProductVariant,@@ -129,7 +124,7 @@ def get_variant_price():return calculate_discounted_price(product=product,- price=get_variant_base_price(variant=variant, product=product),+ price=variant.price,collections=collections,discounts=discounts,)@@ -142,6 +137,7 @@ def get_product_price_range(collections: Iterable[Collection],discounts: Iterable[DiscountInfo]) -> MoneyRange:+ zero = Money(0, settings.DEFAULT_CURRENCY)with opentracing.global_tracer().start_active_span("get_product_price_range"):if variants:prices = [@@ -154,13 +150,8 @@ def get_product_price_range(for variant in variants]return MoneyRange(min(prices), max(prices))- price = calculate_discounted_price(- product=product,- price=product.price,- collections=collections,- discounts=discounts,- )- return MoneyRange(start=price, stop=price)++ return MoneyRange(zero, zero)def get_product_availability(diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.pyindex 99729ce73a..b06c118afc 100644--- a/saleor/product/utils/costs.py+++ b/saleor/product/utils/costs.py@@ -68,7 +68,7 @@ def get_cost_price(variant: "ProductVariant") -> "Money":def get_margin_for_variant(variant: "ProductVariant") -> Optional[float]:if variant.cost_price is None:return None- base_price = variant.base_price+ base_price = variant.priceif not base_price:return Nonemargin = base_price - variant.cost_pricediff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.pyindex d2cc2c649b..e2940d910a 100644--- a/saleor/product/utils/variant_prices.py+++ b/saleor/product/utils/variant_prices.py@@ -1,5 +1,6 @@import operatorfrom functools import reduce+from typing import Optionalfrom django.db.models.query_utils import Qfrom prices import Money@@ -8,9 +9,9 @@ from ...discount.utils import fetch_active_discountsfrom ..models import Product-def _get_product_minimal_variant_price(product, discounts) -> Money:+def _get_product_minimal_variant_price(product, discounts) -> Optional[Money]:# Start with the product's price as the minimal one- minimal_variant_price = product.price+ minimal_variant_price = Nonefor variant in product.variants.all():variant_price = variant.get_price(discounts=discounts)minimal_variant_price = min(minimal_variant_price, variant_price)diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 75bac83214..17ab7b3b2f 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -175,7 +175,6 @@ def generate_product_payload(product: "Product"):"name","description_json","currency",- "price_amount","minimal_variant_price_amount","attributes","updated_at",@@ -190,7 +189,7 @@ def generate_product_payload(product: "Product"):"sku","name","currency",- "price_override_amount",+ "price_amount","track_inventory","quantity","quantity_allocated",diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.pyindex 436fb6494c..3d83e7d54c 100644--- a/saleor/webhook/serializers.py+++ b/saleor/webhook/serializers.py@@ -14,7 +14,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:{"sku": variant.sku,"quantity": line.quantity,- "base_price": str(variant.base_price.amount),+ "base_price": str(variant.price.amount),"currency": variant.currency,"full_name": variant.display_product(),"product_name": product.name,