Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove unused code from core and product
IKarbowiak57532394c80e
diff --git a/.isort.cfg b/.isort.cfgindex 049ebdc9d4..e2f3326beb 100644--- a/.isort.cfg+++ b/.isort.cfg@@ -1,2 +1,2 @@[settings]-known_third_party = PIL,babel,bleach,bootstrap4,braintree,celery,dj_database_url,dj_email_url,django,django_babel,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphene_federation,graphql,graphql_jwt,graphql_relay,html5lib,html_to_draftjs,i18naddress,markdown,measurement,mptt,oauthlib,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,requests,sentry_sdk,six,social_core,storages,stripe,templated_email,text_unidecode,tqdm,versatileimagefield+known_third_party = PIL,babel,bleach,bootstrap4,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphene_federation,graphql,graphql_jwt,graphql_relay,html5lib,html_to_draftjs,i18naddress,markdown,measurement,mptt,oauthlib,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,requests,sentry_sdk,six,social_core,storages,stripe,templated_email,text_unidecode,tqdm,versatileimagefielddiff --git a/saleor/core/i18n.py b/saleor/core/i18n.pydeleted file mode 100644index 03a973c432..0000000000--- a/saleor/core/i18n.py+++ /dev/null@@ -1,6 +0,0 @@-from django.utils.translation import pgettext_lazy-from django_countries import countries--ANY_COUNTRY = ""-ANY_COUNTRY_DISPLAY = pgettext_lazy("Country choice", "Any Country")-COUNTRY_CODE_CHOICES = [(ANY_COUNTRY, ANY_COUNTRY_DISPLAY)] + list(countries)diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 568eacb95f..a4c5b760fd 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,47 +1,22 @@-import decimalimport loggingimport socket-from json import JSONEncoderfrom urllib.parse import urljoinfrom babel.numbers import get_territory_currencies-from django import formsfrom django.conf import settingsfrom django.contrib.sites.models import Site-from django.core import serializers-from django.core.paginator import InvalidPage, Paginator-from django.http import Http404-from django.utils.encoding import iri_to_uri, smart_text-from django_babel.templatetags.babel import currencyfmt+from django.utils.encoding import iri_to_urifrom django_countries import countriesfrom django_countries.fields import Countryfrom django_prices_openexchangerates import exchange_currency-from django_prices_openexchangerates.tasks import update_conversion_ratesfrom geolite2 import geolite2from prices import MoneyRangefrom versatileimagefield.image_warmer import VersatileImageFieldWarmer-from ...celeryconf import app-from ...core.i18n import COUNTRY_CODE_CHOICES-georeader = geolite2.reader()logger = logging.getLogger(__name__)-class CategoryChoiceField(forms.ModelChoiceField):- def label_from_instance(self, obj):- # pylint: disable=W0212- level = getattr(obj, obj._mptt_meta.level_attr)- indent = max(0, level - 1) * "│"- if obj.parent:- last = (obj.parent.rght - obj.rght == 1) and (obj.rght - obj.lft == 1)- if last:- indent += "└ "- else:- indent += "├ "- return "%s%s" % (indent, smart_text(obj))--def build_absolute_uri(location):# type: (str) -> strhost = Site.objects.get_current().domain@@ -51,6 +26,23 @@ def build_absolute_uri(location):return iri_to_uri(location)+def get_client_ip(request):+ """Retrieve the IP address from the request data.++ Tries to get a valid IP address from X-Forwarded-For, if the user is hiding behind+ a transparent proxy or if the server is behind a proxy.++ If no forwarded IP was provided or all of them are invalid,+ it fallback to the requester IP.+ """+ ip = request.META.get("HTTP_X_FORWARDED_FOR", "")+ ips = ip.split(",")+ for ip in ips:+ if is_valid_ipv4(ip) or is_valid_ipv6(ip):+ return ip+ return request.META.get("REMOTE_ADDR", None)++def is_valid_ipv4(ip: str) -> bool:"""Check whether the passed IP is a valid V4 IP address."""try:@@ -69,23 +61,6 @@ def is_valid_ipv6(ip: str) -> bool:return True-def get_client_ip(request):- """Retrieve the IP address from the request data.-- Tries to get a valid IP address from X-Forwarded-For, if the user is hiding behind- a transparent proxy or if the server is behind a proxy.-- If no forwarded IP was provided or all of them are invalid,- it fallback to the requester IP.- """- ip = request.META.get("HTTP_X_FORWARDED_FOR", "")- ips = ip.split(",")- for ip in ips:- if is_valid_ipv4(ip) or is_valid_ipv6(ip):- return ip- return request.META.get("REMOTE_ADDR", None)--def get_country_by_ip(ip_address):geo_data = georeader.get(ip_address)if geo_data and "country" in geo_data and "iso_code" in geo_data["country"]:@@ -102,29 +77,6 @@ def get_currency_for_country(country):return settings.DEFAULT_CURRENCY-def get_paginator_items(items, paginate_by, page_number):- if not page_number:- page_number = 1- paginator = Paginator(items, paginate_by)- try:- page_number = int(page_number)- except ValueError:- raise Http404("Page can not be converted to an int.")-- try:- items = paginator.page(page_number)- except InvalidPage as err:- raise Http404(- "Invalid page (%(page_number)s): %(message)s"- % {"page_number": page_number, "message": str(err)}- )- return items---def format_money(money):- return currencyfmt(money.amount, money.currency)--def to_local_currency(price, currency):if price is None:return None@@ -142,26 +94,6 @@ def to_local_currency(price, currency):return None-def update_conversion_rates_from_openexchangerates():- conversion_rates_queryset = update_conversion_rates()- return serializers.serialize("json", conversion_rates_queryset)---def get_user_shipping_country(request):- if request.user.is_authenticated:- default_shipping = request.user.default_shipping_address- if default_shipping:- return default_shipping.country- return request.country---def serialize_decimal(obj):- if isinstance(obj, decimal.Decimal):- return str(obj)- return JSONEncoder().default(obj)--def create_thumbnails(pk, model, size_set, image_attr=None):instance = model.objects.get(pk=pk)if not image_attr:@@ -179,15 +111,3 @@ def create_thumbnails(pk, model, size_set, image_attr=None):logger.info("Created %d thumbnails", num_created)if failed_to_create:logger.error("Failed to generate thumbnails", extra={"paths": failed_to_create})---def get_country_name_by_code(country_code):- country_name = next(- (name for code, name in COUNTRY_CODE_CHOICES if code == country_code),- country_code,- )- return country_name---def get_company_address():- return Site.objects.get_current().settings.company_addressdiff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.pyindex 6b27683f6f..ed9e5e8127 100644--- a/saleor/product/utils/__init__.py+++ b/saleor/product/utils/__init__.py@@ -6,8 +6,6 @@ from django.db import transactionfrom django.db.models import Ffrom ...core.taxes import TaxedMoney, zero_taxed_money-from ...core.utils import get_paginator_items-from ...core.utils.filters import get_now_sorted_byfrom ..tasks import update_products_minimal_variant_prices_taskfrom .availability import products_with_availability@@ -23,63 +21,6 @@ if TYPE_CHECKING:from ..filters import ProductCategoryFilter-def products_visible_to_user(user: "User") -> "QuerySet[User]":- # pylint: disable=cyclic-import- from ..models import Product-- if user.is_authenticated and user.is_active and user.is_staff:- return Product.objects.all()- return Product.objects.published()---def products_with_details(user: "User") -> "QuerySet[Product]":- products = products_visible_to_user(user)- products = products.prefetch_related(- "translations",- "category__translations",- "collections__translations",- "images",- "product_type__product_attributes__translations",- "product_type__product_attributes__values__translations",- "attributes__values__translations",- "attributes__assignment__attribute__translations",- "variants__variant_images__image",- "variants__attributes__values__translations",- "variants__attributes__assignment__attribute__translations",- )- return products---def products_for_products_list(user: "User") -> "QuerySet[Product]":- products = products_visible_to_user(user)- products = products.prefetch_related(- "translations", "images", "variants__variant_images__image"- )- return products---def products_for_homepage(- user: "User", homepage_collection: "Collection"-) -> "QuerySet[Product]":- products = products_visible_to_user(user)- products = products.prefetch_related(- "translations", "images", "variants__variant_images__image", "collections"- )- products = products.filter(collections=homepage_collection)- return products---def get_product_images(product: "Product") -> List["ProductImage"]:- """Return list of product images that will be placed in product gallery."""- return list(product.images.all())---def products_for_checkout(user: "User") -> "QuerySet[Product]":- products = products_visible_to_user(user)- products = products.prefetch_related("variants__variant_images__image")- return products--def allocate_stock(variant: "ProductVariant", quantity: int):variant.quantity_allocated = F("quantity_allocated") + quantityvariant.save(update_fields=["quantity_allocated"])@@ -106,50 +47,6 @@ def increase_stock(variant: "ProductVariant", quantity, allocate: bool = False):variant.save(update_fields=update_fields)-def get_product_list_context(- request: "HttpRequest", filter_set: "ProductCategoryFilter"-) -> dict:- """Build a context from the given filter set."""- # Avoiding circular dependency- from ..filters import SORT_BY_FIELDS-- qs = filter_set.qs- if not filter_set.form.is_valid():- qs = qs.none()- products_paginated = get_paginator_items(- qs, settings.PAGINATE_BY, request.GET.get("page")- )- products_and_availability = list(- products_with_availability(- products_paginated,- request.discounts,- request.country,- request.currency,- request.extensions,- )- )- now_sorted_by = get_now_sorted_by(filter_set)- arg_sort_by = request.GET.get("sort_by")- is_descending = arg_sort_by.startswith("-") if arg_sort_by else False- return {- "filter_set": filter_set,- "products": products_and_availability,- "products_paginated": products_paginated,- "sort_by_choices": SORT_BY_FIELDS,- "now_sorted_by": now_sorted_by,- "is_descending": is_descending,- }---def collections_visible_to_user(user: "User") -> "QuerySet[Collection]":- # pylint: disable=cyclic-import- from ..models import Collection-- if user.is_authenticated and user.is_active and user.is_staff:- return Collection.objects.all()- return Collection.objects.published()--def calculate_revenue_for_variant(variant: "ProductVariant", start_date: Union["date", "datetime"]) -> TaxedMoney:@@ -163,15 +60,6 @@ def calculate_revenue_for_variant(return revenue-def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]":- """Collect products from all levels in category tree."""- products = category.products.all()- descendants = category.get_descendants()- for descendant in descendants:- products = products | descendant.products.all()- return products--@transaction.atomicdef delete_categories(categories_ids: List[str]):"""Delete categories and perform all necessary actions.@@ -192,3 +80,12 @@ def delete_categories(categories_ids: List[str]):product_ids = list(products.values_list("id", flat=True))categories.delete()update_products_minimal_variant_prices_task.delay(product_ids=product_ids)+++def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]":+ """Collect products from all levels in category tree."""+ products = category.products.all()+ descendants = category.get_descendants()+ for descendant in descendants:+ products = products | descendant.products.all()+ return productsdiff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex 8cd40d6ff4..b41aa0f3b0 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -2,9 +2,9 @@ from decimal import Decimalimport grapheneimport pytest+from django_countries.fields import Countryfrom saleor.checkout import calculations-from saleor.core.utils import get_country_name_by_codefrom saleor.graphql.payment.enums import OrderAction, PaymentChargeStatusEnumfrom saleor.payment.interface import CreditCardInfo, CustomerSource, TokenConfigfrom saleor.payment.models import ChargeStatus, Payment, TransactionKind@@ -503,7 +503,7 @@ def test_payments_query("postalCode": pay.billing_postal_code,"country": {"code": pay.billing_country_code,- "country": get_country_name_by_code(pay.billing_country_code),+ "country": Country(pay.billing_country_code).name,},}assert data["actions"] == [OrderAction.REFUND.name]diff --git a/tests/test_core.py b/tests/test_core.pyindex 3ea6b662db..34d64d9695 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -7,7 +7,6 @@ import pytestfrom django.templatetags.static import staticfrom django.test import RequestFactory, override_settingsfrom measurement.measures import Weight-from prices import Moneyfrom saleor.account.models import Address, Userfrom saleor.account.utils import create_superuser@@ -16,10 +15,8 @@ from saleor.core.utils import (Country,build_absolute_uri,create_thumbnails,- format_money,get_client_ip,get_country_by_ip,- get_country_name_by_code,get_currency_for_country,random_data,)@@ -44,11 +41,6 @@ type_schema = {}-def test_format_money():- money = Money("123.99", "USD")- assert format_money(money) == "$123.99"--@pytest.mark.parametrize("ip_data, expected_country",[@@ -249,8 +241,3 @@ def test_delete_sort_order_with_null_value(menu_item):menu_item.sort_order = Nonemenu_item.save(update_fields=["sort_order"])menu_item.delete()---def test_get_country_name_by_code():- country_name = get_country_name_by_code("PL")- assert country_name == "Poland"