Skip to content

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

Remove unused code - account, product, order and seo schema

IKarbowiak8f23c60454f6
diff --git a/saleor/account/events.py b/saleor/account/events.py
index 43c43373ad..450b1d88a6 100644
--- a/saleor/account/events.py
+++ b/saleor/account/events.py
@@ -84,17 +84,6 @@ def staff_user_assigned_email_to_a_customer_event(
)
-def staff_user_added_note_to_a_customer_event(
- *, staff_user: UserType, note: str
-) -> CustomerEvent:
- return CustomerEvent.objects.create(
- user=staff_user,
- order=None,
- type=CustomerEvents.NOTE_ADDED,
- parameters={"message": note},
- )
-
-
def staff_user_assigned_name_to_a_customer_event(
*, staff_user: UserType, new_name: str
) -> CustomerEvent:
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index f2e08e8716..24562933fc 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -53,30 +53,6 @@ def change_user_default_address(user, address, address_type):
set_user_default_shipping_address(user, address)
-def get_user_first_name(user):
- """Return a user's first name from their default belling address.
-
- Return nothing if none where found.
- """
- if user.first_name:
- return user.first_name
- if user.default_billing_address:
- return user.default_billing_address.first_name
- return None
-
-
-def get_user_last_name(user):
- """Return a user's last name from their default belling address.
-
- Return nothing if none where found.
- """
- if user.last_name:
- return user.last_name
- if user.default_billing_address:
- return user.default_billing_address.last_name
- return None
-
-
def create_superuser(credentials):
user, created = User.objects.get_or_create(
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 8d2fb14b94..39bfb5e5b7 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -2,13 +2,10 @@ from functools import wraps
from django.conf import settings
from django.db import transaction
-from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from django.utils.translation import pgettext
from prices import Money, TaxedMoney
-from ..account.utils import store_user_address
-from ..checkout import AddressType
from ..core.taxes import zero_money
from ..core.weight import zero_weight
from ..discount.models import NotApplicable, Voucher, VoucherType
@@ -42,28 +39,6 @@ def order_needs_automatic_fullfilment(order: Order) -> bool:
return False
-def check_order_status(func):
- """Check if order meets preconditions of payment process.
-
- Order can not have draft status or be fully paid. Billing address
- must be provided.
- If not, redirect to order details page.
- """
- # pylint: disable=cyclic-import
- from .models import Order
-
- @wraps(func)
- def decorator(*args, **kwargs):
- token = kwargs.pop("token")
- order = get_object_or_404(Order.objects.confirmed(), token=token)
- if not order.billing_address or order.is_fully_paid():
- return redirect("order:details", token=order.token)
- kwargs["order"] = order
- return func(*args, **kwargs)
-
- return decorator
-
-
def update_voucher_discount(func):
"""Recalculate order discount amount based on order voucher."""
@@ -174,15 +149,6 @@ def update_order_status(order):
order.save(update_fields=["status"])
-def attach_order_to_user(order, user):
- """Associate existing order with user account."""
- order.user = user
- store_user_address(user, order.billing_address, AddressType.BILLING)
- if order.shipping_address:
- store_user_address(user, order.shipping_address, AddressType.SHIPPING)
- order.save(update_fields=["user"])
-
-
@transaction.atomic
def add_variant_to_order(
order,
diff --git a/saleor/product/filters.py b/saleor/product/filters.py
index 1f904291d0..937d4b2df4 100644
--- a/saleor/product/filters.py
+++ b/saleor/product/filters.py
@@ -140,29 +140,3 @@ class ProductFilter(SortedFilterSet):
if attribute_values:
queryset = filter_products_by_attributes_values(queryset, attribute_values)
return queryset
-
-
-class ProductCategoryFilter(ProductFilter):
- def __init__(self, *args, **kwargs):
- self.category = kwargs.pop("category")
- super().__init__(*args, **kwargs)
-
- def _get_product_attributes_lookup(self):
- categories = self.category.get_descendants(include_self=True)
- return Q(product_types__products__category__in=categories)
-
- def _get_variant_attributes_lookup(self):
- categories = self.category.get_descendants(include_self=True)
- return Q(product_variant_types__products__category__in=categories)
-
-
-class ProductCollectionFilter(ProductFilter):
- def __init__(self, *args, **kwargs):
- self.collection = kwargs.pop("collection")
- super().__init__(*args, **kwargs)
-
- def _get_product_attributes_lookup(self):
- return Q(product_types__products__collections=self.collection)
-
- def _get_variant_attributes_lookup(self):
- return Q(product_variant_types__products__collections=self.collection)
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 117117a425..29bdd62026 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -68,9 +68,3 @@ def update_products_minimal_variant_prices_of_discount_task(discount_pk: int):
def update_products_minimal_variant_prices_task(product_ids: List[int]):
products = Product.objects.filter(pk__in=product_ids)
update_products_minimal_variant_prices(products)
-
-
-def update_all_products_minimal_variant_prices_task():
- products = Product.objects.iterator()
- update_products_minimal_variant_prices(products)
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
deleted file mode 100644
index 53ef938427..0000000000
--- a/saleor/product/utils/variants_picker.py
+++ /dev/null
@@ -1,239 +0,0 @@
-from collections import defaultdict
-from dataclasses import asdict, dataclass, field
-from decimal import Decimal
-from typing import TYPE_CHECKING, Dict, Iterable, List, Optional
-
-from django.db.models import Count, Q
-from django_prices.templatetags import prices
-
-from ...core.taxes import display_gross_prices
-from ...core.utils import to_local_currency
-from ...discount import DiscountInfo
-from ...extensions.manager import get_extensions_manager
-from ...seo.schema.product import variant_json_ld
-from .availability import get_product_availability
-
-if TYPE_CHECKING:
- # flake8: noqa
- from prices import MoneyRange, Money
-
- from django.db.models.query import QuerySet
-
- from ...extensions.manager import ExtensionsManager
- from ..models import AssignedVariantAttribute, ProductVariant, Product
-
-
-AttributesMapType = Dict[str, str]
-
-
-def _attributes_to_map(instance: "ProductVariant") -> AttributesMapType:
- """Convert a variant's attributes to a flat attribute dict ({attr_pk: val_pk}).
-
- This is used for backward compatibility between the storefront 1.0
- and dashboard 2.0's new attribute mechanism.
- """
-
- attribute_map = {}
-
- # Skip multiple values - which should have been denied by the dashboard
- # FIXME: make sure Count(...) is hitting the prefetch
- attributes_qs = instance.attributes.annotate(Count("values")).exclude(
- ~Q(values__count=1)
- )
-
- for attribute_rel in attributes_qs: # type: AssignedVariantAttribute
- value = attribute_rel.values.first()
- attribute_pk = attribute_rel.attribute_pk
- attribute_map[str(attribute_pk)] = str(value.pk)
-
- return attribute_map
-
-
-@dataclass
-class VariantValues:
- pk: str
- name: str
- slug: str
-
-
-@dataclass
-class VariantAttributes:
- pk: str
- name: str
- slug: str
- values: List[VariantValues]
-
-
-@dataclass
-class MoneyAsDict:
- currency: str
- gross: Decimal
- grossLocalized: Decimal
- net: Decimal
- netLocalized: Decimal
-
-
-@dataclass
-class MoneyRangeAsDict:
- minPrice: Optional[MoneyAsDict] = None
- maxPrice: Optional[MoneyAsDict] = None
-
-
-@dataclass
-class VariantData:
- id: str
- availability: bool
- attributes: AttributesMapType
- schemaData: dict # TODO: Can it be changed to schema?
- price: Optional[MoneyAsDict] = None
- priceUndiscounted: Optional[MoneyAsDict] = None
- priceLocalCurrency: Optional[MoneyAsDict] = None
-
-
-@dataclass
-class ProductAvailability:
- discount: Optional[MoneyAsDict] = None
- taxRate: Decimal = Decimal(0)
- priceRange: Optional[MoneyRangeAsDict] = None
- priceRangeUndiscounted: Optional[MoneyRangeAsDict] = None
- priceRangeLocalCurrency: Optional[MoneyRangeAsDict] = None
-
-
-@dataclass
-class ProductPriceDisplay:
- displayGross: bool
- handleTaxes: bool
-
-
-@dataclass
-class VariantPickerData:
- availability: ProductAvailability
- priceDisplay: ProductPriceDisplay
- variantAttributes: List[VariantAttributes] = field(default_factory=list)
- variants: List[VariantData] = field(default_factory=list)
-
- def as_dict(self):
- return asdict(self)
-
-
-def get_variant_picker_data(
- product: "Product",
- discounts: Iterable[DiscountInfo] = None,
- extensions: Optional["ExtensionsManager"] = None,
- local_currency: Optional[str] = None,
- country: str = None,
- product_availability: Optional[ProductAvailability] = None,
-) -> VariantPickerData:
- if not extensions:
- extensions = get_extensions_manager()
- availability = get_product_availability(
- product, discounts, country, local_currency, extensions
- )
-
- product_price = extensions.apply_taxes_to_product(product, product.price, country)
- tax_rates = Decimal(0)
- if product_price.tax and product_price.net:
- tax_rates = (product_price.tax / product_price.net) * 100
- tax_rates = tax_rates.quantize(Decimal("1."))
-
- data = VariantPickerData(
- priceDisplay=ProductPriceDisplay(
- displayGross=display_gross_prices(),
- handleTaxes=extensions.show_taxes_on_storefront(),
- ),
- availability=ProductAvailability(
- discount=price_as_dict(availability.discount),
- taxRate=tax_rates,
- priceRange=price_range_as_dict(availability.price_range),
- priceRangeUndiscounted=price_range_as_dict(
- availability.price_range_undiscounted
- ),
- priceRangeLocalCurrency=price_range_as_dict(
- availability.price_range_local_currency
- ),
- ),
- )
-
- variant_attributes = (
- product.product_type.variant_attributes.all().variant_attributes_sorted()
- )
-
- variants: "QuerySet[ProductVariant]" = product.variants.all()
- # Collect only available variants
- filter_available_variants = defaultdict(list)
-
- for variant in variants: # type: ProductVariant
- price = extensions.apply_taxes_to_product(
- variant.product, variant.get_price(discounts), country
- )
- price_undiscounted = extensions.apply_taxes_to_product(
- variant.product, variant.get_price(), country
- )
- if local_currency:
- price_local_currency = to_local_currency(price, local_currency)
- else:
- price_local_currency = None
-
- in_stock = variant.is_in_stock()
- schema_data = variant_json_ld(price.net, variant, in_stock)
- attributes_map = _attributes_to_map(variant)
- variant_data = VariantData(
- id=variant.pk,
- availability=in_stock,
- price=price_as_dict(price),
- priceUndiscounted=price_as_dict(price_undiscounted),
- attributes=attributes_map,
- priceLocalCurrency=price_as_dict(price_local_currency),
- schemaData=schema_data,
- )
- data.variants.append(variant_data)
-
- for variant_key, variant_value in attributes_map.items():
- filter_available_variants[int(variant_key)].append(variant_value)
-
- for attribute in variant_attributes:
- available_variants = filter_available_variants.get(attribute.pk, None)
-
- if available_variants:
- data.variantAttributes.append(
- VariantAttributes(
- pk=attribute.pk,
- name=attribute.translated.name,
- slug=attribute.translated.slug,
- values=[
- VariantValues(
- pk=value.pk,
- name=value.translated.name,
- slug=value.translated.slug,
- )
- for value in attribute.values.filter(
- pk__in=available_variants
- ).prefetch_related("translations")
- ],
- )
- )
-
- return data
-
-
-def price_as_dict(price: Optional["Money"]) -> Optional[MoneyAsDict]:
- if price is None:
- return None
- return MoneyAsDict(
- currency=price.currency,
- gross=price.gross.amount,
- grossLocalized=prices.amount(price.gross),
- net=price.net.amount,
- netLocalized=prices.amount(price.net),
- )
-
-
-def price_range_as_dict(
- price_range: Optional["MoneyRange"]
-) -> Optional[MoneyRangeAsDict]:
- if not price_range:
- return None
- return MoneyRangeAsDict(
- minPrice=price_as_dict(price_range.start),
- maxPrice=price_as_dict(price_range.stop),
- )
diff --git a/saleor/seo/schema/product.py b/saleor/seo/schema/product.py
deleted file mode 100644
index a92ff41d1f..0000000000
--- a/saleor/seo/schema/product.py
+++ /dev/null
@@ -1,17 +0,0 @@
-IN_STOCK = "http://schema.org/InStock"
-OUT_OF_STOCK = "http://schema.org/OutOfStock"
-
-
-def variant_json_ld(price, variant, in_stock):
- schema_data = {
- "@type": "Offer",
- "itemCondition": "http://schema.org/NewCondition",
- "priceCurrency": price.currency,
- "price": price.amount,
- "sku": variant.sku,
- }
- if in_stock:
- schema_data["availability"] = IN_STOCK
- else:
- schema_data["availability"] = OUT_OF_STOCK
- return schema_data
diff --git a/tests/api/test_account_events.py b/tests/api/test_account_events.py
index 405f47b30b..f47f143815 100644
--- a/tests/api/test_account_events.py
+++ b/tests/api/test_account_events.py
@@ -317,26 +317,3 @@ def test_account_event_staff_user_assigned_email_to_customer_event_resolves_prop
)
assert expected_data == received_data
-
-
-def test_account_event_staff_user_added_note_to_customer_event_resolves_properly(
- staff_api_client, staff_user, permission_manage_staff
-):
- event = account_events.staff_user_added_note_to_a_customer_event(
- staff_user=staff_user, note="New note's content!"
- )
- expected_data = {
- "id": _model_to_node_id(event),
- "user": {"id": _model_to_node_id(staff_user)},
- "count": None,
- "message": "New note's content!",
- "order": None,
- "orderLine": None,
- "type": account_events.CustomerEvents.NOTE_ADDED.upper(),
- }
-
- received_data = _get_event_from_graphql(
- staff_api_client, staff_user, permission_manage_staff
- )
-
- assert expected_data == received_data
diff --git a/tests/test_account.py b/tests/test_account.py
index b065732929..53ed5486b4 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -13,12 +13,7 @@ from saleor.account import forms, i18n
from saleor.account.i18n import AddressForm
from saleor.account.models import User
from saleor.account.templatetags.i18n_address_tags import format_address
-from saleor.account.utils import (
- get_random_avatar,
- get_user_first_name,
- get_user_last_name,
- remove_staff_member,
-)
+from saleor.account.utils import get_random_avatar, remove_staff_member
from saleor.account.validators import validate_possible_number
@@ -298,35 +293,6 @@ def test_get_full_name(email, first_name, last_name, full_name, address):
assert user.get_full_name() == full_name
- "first_name, default_billing_address_first_name, result",
- [
- ("John", "Arnold", "John"),
- ("John", "", "John"),
- ("", "Arnold", "Arnold"),
- ("", "", ""),
- ],
-)
-def test_get_user_first_name(
- first_name, default_billing_address_first_name, result, address
-):
- address.first_name = default_billing_address_first_name
- user = User(first_name=first_name, default_billing_address=address)
- assert get_user_first_name(user) == result
-
-
- "last_name, default_billing_address_last_name, result",
- [("Doe", "Green", "Doe"), ("Doe", "", "Doe"), ("", "Green", "Green"), ("", "", "")],
-)
-def test_get_user_last_name(
- last_name, default_billing_address_last_name, result, address
-):
- address.last_name = default_billing_address_last_name
- user = User(last_name=last_name, default_billing_address=address)
- assert get_user_last_name(user) == result
-
-
def test_get_random_avatar():
avatar = get_random_avatar()
assert isinstance(avatar, File)
diff --git a/tests/test_category.py b/tests/test_category.py
index ecfc5046e6..2d5df1fa3a 100644
--- a/tests/test_category.py
+++ b/tests/test_category.py
@@ -1,23 +1,9 @@
from unittest.mock import patch
-from saleor.product.filters import ProductCategoryFilter
from saleor.product.models import Category
from saleor.product.utils import collect_categories_tree_products, delete_categories
-def test_product_category_filter_filters_from_child_category(
- product_type, categories_tree
-):
- product_filter = ProductCategoryFilter(data={}, category=categories_tree)
- attributes = product_filter._get_attributes()
-
- product_attr = product_type.product_attributes.get()
- variant_attr = product_type.variant_attributes.get()
-
- assert product_attr in attributes
- assert variant_attr in attributes
-
-
def test_collect_categories_tree_products(categories_tree):
parent = categories_tree
child = parent.children.first()
diff --git a/tests/test_product.py b/tests/test_product.py
index cbd4117943..1723acc005 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -1,16 +1,14 @@
import os
from decimal import Decimal
-from unittest.mock import patch
import pytest
from freezegun import freeze_time
-from prices import Money, MoneyRange, TaxedMoney
+from prices import Money, MoneyRange
from saleor.account import events as account_events
-from saleor.product import AttributeInputType, models
+from saleor.product import models
from saleor.product.filters import filter_products_by_attributes_values
-from saleor.product.models import Attribute, AttributeValue, DigitalContentUrl
-from saleor.product.thumbnails import create_product_thumbnails
+from saleor.product.models import DigitalContentUrl
from saleor.product.utils import (
allocate_stock,
deallocate_stock,
@@ -20,7 +18,6 @@ from saleor.product.utils import (
from saleor.product.utils.attributes import associate_attribute_values_to_instance
from saleor.product.utils.costs import get_margin_for_variant
from saleor.product.utils.digital_products import increment_download_count
-from saleor.product.utils.variants_picker import get_variant_picker_data
@pytest.mark.parametrize(
@@ -100,54 +97,6 @@ def test_filtering_by_attribute(db, color_attribute, category, settings):
assert product_b.pk in list(filtered)
-def test_get_variant_picker_data_proper_variant_count(product):
- data = get_variant_picker_data(
- product, discounts=None, extensions=None, local_currency=None
- ).as_dict()
-
- assert len(data["variantAttributes"][0]["values"]) == 1
-
-
-def test_get_variant_picker_data_no_nested_attributes(variant, product_type, category):
- """Ensures that if someone bypassed variant attributes checks (e.g. a raw SQL query)
- and inserted an attribute with multiple values, it doesn't return invalid data
- to the storefront that would crash it."""
-
- variant_attr = Attribute.objects.create(
- slug="modes", name="Available Modes", input_type=AttributeInputType.MULTISELECT
- )
-
- attr_val_1 = AttributeValue.objects.create(
- attribute=variant_attr, name="Eco Mode", slug="eco"
- )
- attr_val_2 = AttributeValue.objects.create(
- attribute=variant_attr, name="Performance Mode", slug="power"
- )
-
- product_type.variant_attributes.clear()
- product_type.variant_attributes.add(variant_attr)
-
- associate_attribute_values_to_instance(
- variant, variant_attr, attr_val_1, attr_val_2
- )
-
- product = variant.product
- data = get_variant_picker_data(
- product, discounts=None, local_currency=None
- ).as_dict()
-
- assert len(data["variantAttributes"]) == 0
-
-
-@patch("saleor.product.thumbnails.create_thumbnails")
-def test_create_product_thumbnails(mock_create_thumbnails, product_with_image):
- product_image = product_with_image.images.first()
- create_product_thumbnails(product_image.pk)
- assert mock_create_thumbnails.called_once_with(
- product_image.pk, models.ProductImage, "products"
- )
-
-
@pytest.mark.parametrize(
"expected_price, include_discounts",
[(Decimal("10.00"), True), (Decimal("15.0"), False)],
@@ -264,15 +213,6 @@ def test_variant_base_price(product, price_override):
assert variant.base_price == variant.price_override
-def test_variant_picker_data_with_translations(
- product, translated_variant_fr, settings
-):
- settings.LANGUAGE_CODE = "fr"
- variant_picker_data = get_variant_picker_data(product).as_dict()
- attribute = variant_picker_data["variantAttributes"][0]
- assert attribute["name"] == translated_variant_fr.name
-
-
def test_digital_product_view(client, digital_content_url):
"""Ensure a user (anonymous or not) can download a non-expired digital good
using its associated token and that all associated events
@@ -363,37 +303,6 @@ def test_digital_product_view_url_expired(client, digital_content):
assert response.status_code == 404
-def test_variant_picker_data_price_range(product_type, category):
- product = models.Product.objects.create(
- product_type=product_type, category=category, price=Money("15.00", "USD")
- )
- product.variants.create(sku="1")
- product.variants.create(sku="2", price_override=Money("20.00", "USD"))
- product.variants.create(sku="3", price_override=Money("11.00", "USD"))
-
- start = TaxedMoney(net=Money("11.00", "USD"), gross=Money("11.00", "USD"))
- stop = TaxedMoney(net=Money("20.00", "USD"), gross=Money("20.00", "USD"))
-
- picker_data = get_variant_picker_data(
- product, discounts=None, local_currency=None
- ).as_dict()
-
- min_price = picker_data["availability"]["priceRange"]["minPrice"]
- min_price = TaxedMoney(
- net=Money(min_price["net"], min_price["currency"]),
- gross=Money(min_price["gross"], min_price["currency"]),
- )
-
- max_price = picker_data["availability"]["priceRange"]["maxPrice"]
- max_price = TaxedMoney(
- net=Money(max_price["net"], max_price["currency"]),
- gross=Money(max_price["gross"], max_price["currency"]),
- )
-
- assert min_price == start
- assert max_price == stop
-
-
@pytest.mark.parametrize(
"price, cost", [(Money("0", "USD"), Money("1", "USD")), (Money("2", "USD"), None)]
)
diff --git a/tests/test_product_minimal_variant_price.py b/tests/test_product_minimal_variant_price.py
index 731d8e2cf9..5fecc12e44 100644
--- a/tests/test_product_minimal_variant_price.py
+++ b/tests/test_product_minimal_variant_price.py
@@ -5,7 +5,6 @@ from prices import Money
from saleor.product.models import Product, ProductVariant
from saleor.product.tasks import (
- update_all_products_minimal_variant_prices_task,
update_products_minimal_variant_prices_of_catalogues,
update_products_minimal_variant_prices_task,
)
@@ -71,22 +70,6 @@ def test_update_products_minimal_variant_prices_of_catalogues_for_collection(
assert product.minimal_variant_price == variant.price_override
-def test_update_all_products_minimal_variant_prices_task(product_list):
- price_override = Money("0.01", "USD")
- for product in product_list:
- assert product.minimal_variant_price > price_override
- variant = product.variants.first()
- variant.price_override = price_override
- variant.save()
- # Check that "variant.save()" doesn't update the "minimal_variant_price"
- assert product.minimal_variant_price > price_override
-
- update_all_products_minimal_variant_prices_task.apply()
- for product in product_list:
- product.refresh_from_db()
- assert product.minimal_variant_price == price_override
-
-
def test_update_products_minimal_variant_prices_task(product_list):
price_override = Money("0.01", "USD")
for product in product_list: