Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
WIP
Pacu2fee6d4460e2a
diff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex 3e8c553172..d49ef9f310 100644--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -2,12 +2,10 @@from django.http import JsonResponsefrom django.shortcuts import get_object_or_404, redirect, renderfrom django.template.response import TemplateResponse-from django.urls import reversefrom ..core.utils import (format_money, get_user_shipping_country, to_local_currency)from ..product.models import ProductVariant-from ..product.utils import display_variant_attributesfrom ..shipping.utils import get_shipment_optionsfrom .forms import CountryForm, ReplaceCartLineFormfrom .models import Cart@@ -112,21 +110,14 @@ def update(request, cart, variant_id):def summary(request, cart):"""Display a cart summary suitable for displaying on all pages."""def prepare_line_data(line):- product_type = line.variant.product.product_type- attributes = product_type.variant_attributes.all()first_image = line.variant.get_first_image()- price_per_item = line.get_price_per_item(discounts=request.discounts)line_total = line.get_total(discounts=request.discounts)return {'product': line.variant.product,'variant': line.variant.name,'quantity': line.quantity,- 'attributes': display_variant_attributes(line.variant, attributes),'image': first_image,- 'price_per_item': format_money(price_per_item.gross),'line_total': format_money(line_total.gross),- 'update_url': reverse(- 'cart:update-line', kwargs={'variant_id': line.variant_id}),'variant_url': line.variant.get_absolute_url()}if cart.quantity == 0:data = {'quantity': 0}diff --git a/saleor/core/templatetags/attributes.py b/saleor/core/templatetags/attributes.pyindex 5f922c2592..506e0c10c9 100644--- a/saleor/core/templatetags/attributes.py+++ b/saleor/core/templatetags/attributes.py@@ -1,23 +1,7 @@from django.template import Library-from ...product.utils import get_attributes_display_map-register = Library()-ATTRIBUTE_EMPTY_VALUE = '-'---def attributes_values_with_empty(variant, attributes):- attr_values = get_attributes_display_map(variant, attributes)- values = []- for attribute in attributes:- if attribute.pk in attr_values:- values.append(attr_values[attribute.pk])- else:- values.append(ATTRIBUTE_EMPTY_VALUE)- return values-@register.simple_tagdef get_object_properties(object, properties):diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 05d87fe95d..541f1e2b2a 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -25,7 +25,7 @@ from ...product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,ProductImage, ProductType, ProductVariant, Stock, StockLocation)from ...product.thumbnails import create_product_thumbnails-from ...product.utils import generate_name_from_variant_attributes+from ...product.utils import display_variant_attributesfrom ...shipping.models import ANY_COUNTRY, ShippingMethodfake = Factory.create()@@ -300,8 +300,7 @@ def create_variant(product, **kwargs):defaults.update(kwargs)variant = ProductVariant(**defaults)if variant.attributes:- variant.name = generate_name_from_variant_attributes(- variant, variant.attributes)+ variant.name = display_variant_attributes(variant, variant.attributes)variant.save()create_stock(variant)return variantdiff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 8b5b9a5029..0c19a90020 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -15,8 +15,7 @@ from ...product.models import (ProductImage, ProductType, ProductVariant, Stock, StockLocation,VariantImage)from ...product.thumbnails import create_product_thumbnails-from ...product.utils import (- display_variant_attributes, generate_name_from_variant_attributes)+from ...product.utils import display_variant_attributesfrom ..forms import ModelChoiceOrCreationField, OrderedModelMultipleChoiceFieldfrom ..seo.fields import SeoDescriptionField, SeoTitleFieldfrom ..seo.utils import prepare_seo_description@@ -125,19 +124,21 @@ class ProductTypeForm(forms.ModelForm):'and its variant.')self.add_error('variant_attributes', msg)- if self.instance.pk:- variants_changed = (- self.fields['has_variants'].initial != has_variants)- if variants_changed:- query = self.instance.products.all()- query = query.annotate(variants_counter=Count('variants'))- query = query.filter(variants_counter__gt=1)- if query.exists():- msg = pgettext_lazy(- 'Product type form error',- 'Some products of this type have more than '- 'one variant.')- self.add_error('has_variants', msg)+ if not self.instance.pk:+ return data++ variants_changed = (+ self.fields['has_variants'].initial != has_variants)+ if variants_changed:+ query = self.instance.products.all()+ query = query.annotate(variants_counter=Count('variants'))+ query = query.filter(variants_counter__gt=1)+ if query.exists():+ msg = pgettext_lazy(+ 'Product type form error',+ 'Some products of this type have more than '+ 'one variant.')+ self.add_error('has_variants', msg)# Some variant attributes could be removed so name should be updated# accordingly@@ -289,7 +290,7 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):def save(self, commit=True):attributes = self.get_saved_attributes()self.instance.attributes = attributes- self.instance.name = generate_name_from_variant_attributes(+ self.instance.name = display_variant_attributes(self.instance, attributes)return super().save(commit=commit)diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex e58a8412ae..c0b8d8ed63 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -785,9 +785,15 @@ def ajax_available_variants_list(request):variant.sku, variant.display_product(),prices_i18n.amount(variant.get_price_per_item(discounts).gross))- available_products = Product.objects.available_products()+ available_products = Product.objects.available_products().prefetch_related(+ 'product_type__variant_attributes',+ 'category',+ 'product_type__product_attributes')queryset = ProductVariant.objects.filter(- product__in=available_products).prefetch_related('product')+ product__in=available_products).prefetch_related(+ 'product__product_type__variant_attributes',+ 'product__category',+ 'product__product_type__product_attributes')search_query = request.GET.get('q', '')if search_query:queryset = queryset.filter(diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.pyindex 4b1db90846..050794b866 100644--- a/saleor/graphql/utils.py+++ b/saleor/graphql/utils.py@@ -30,15 +30,17 @@ def get_attributes_dict_from_list(attributes, attr_slug_id):raise ValueError('Unknown attribute slug: %r' % (attr_slug,))value = attribute.get('value')- if value:- if not value_slug_id.get(value):- attr = ProductAttribute.objects.get(slug=attr_slug)- value = AttributeChoiceValue(- attribute_id=attr.pk, name=value, slug=slugify(value))- value.save()- attr_ids[smart_text(- attr_slug_id.get(attr_slug))] = smart_text(value.pk)- else:- attr_ids[smart_text(attr_slug_id.get(attr_slug))] = smart_text(- value_slug_id.get(value))+ if not value:+ continue++ if not value_slug_id.get(value):+ attr = ProductAttribute.objects.get(slug=attr_slug)+ value = AttributeChoiceValue(+ attribute_id=attr.pk, name=value, slug=slugify(value))+ value.save()+ attr_ids[smart_text(+ attr_slug_id.get(attr_slug))] = smart_text(value.pk)+ else:+ attr_ids[smart_text(attr_slug_id.get(attr_slug))] = smart_text(+ value_slug_id.get(value))return attr_idsdiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 42dad1935b..b11ab4fc70 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -215,9 +215,8 @@ def merge_duplicates_into_order_line(line):def change_order_line_quantity(line, new_quantity):"""Change the quantity of ordered items in a order line."""- line.quantity = new_quantity-- if line.quantity:+ if new_quantity:+ line.quantity = new_quantityline.save()else:line.delete()diff --git a/saleor/product/migrations/0057_auto_20180403_0852.py b/saleor/product/migrations/0057_auto_20180403_0852.pynew file mode 100644index 0000000000..cae6be5433--- /dev/null+++ b/saleor/product/migrations/0057_auto_20180403_0852.py@@ -0,0 +1,18 @@+# Generated by Django 2.0.3 on 2018-04-03 13:52++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0056_auto_20180330_0321'),+ ]++ operations = [+ migrations.AlterField(+ model_name='productvariant',+ name='name',+ field=models.CharField(blank=True, max_length=255),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 6e7c8a7729..05860c1d76 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -20,7 +20,6 @@ from versatileimagefield.fields import PPOIField, VersatileImageFieldfrom ..core.exceptions import InsufficientStockfrom ..discount.utils import calculate_discounted_pricefrom ..seo.models import SeoModel-from .utils import get_attributes_display_mapclass Category(MPTTModel, SeoModel):diff --git a/saleor/product/utils.py b/saleor/product/utils.pyindex fedd7bbb78..48d9944631 100644--- a/saleor/product/utils.py+++ b/saleor/product/utils.py@@ -171,14 +171,6 @@ def get_variant_picker_data(product, discounts=None, local_currency=None):return data-def get_product_attributes_data(product):- attributes = product.product_type.product_attributes.all()- attributes_map = {attribute.pk: attribute for attribute in attributes}- values_map = get_attributes_display_map(product, attributes)- return {attributes_map.get(attr_pk): value_obj- for (attr_pk, value_obj) in values_map.items()}--def price_as_dict(price):if price is None:return None@@ -209,20 +201,6 @@ def get_variant_url(variant):return get_variant_url_from_product(variant.product, attributes)-def get_attributes_display_map(obj, attributes):- display_map = {}- for attribute in attributes:- value = obj.attributes.get(smart_text(attribute.pk))- if value:- choices = {smart_text(a.pk): a for a in attribute.values.all()}- choice_obj = choices.get(value)- if choice_obj:- display_map[attribute.pk] = choice_obj- else:- display_map[attribute.pk] = value- return display_map--def get_product_availability_status(product):from .models import Stock@@ -375,21 +353,42 @@ def get_product_list_context(request, filter_set):'is_descending': is_descending}+def get_product_attributes_data(product):+ product_attributes = list(product.product_type.product_attributes.all())+ values_map = get_attributes_display_map(product, product_attributes)+ return {+ attribute if attribute in product_attributes else None: value_obj+ for (attribute, value_obj) in values_map.items()}++def display_variant_attributes(variant, attributes=None):if attributes is None:attributes = variant.product.product_type.variant_attributes.all()- values = get_attributes_display_map(variant, attributes)- if not values:- return ''- return ', '.join(- '%s: %s' % (- smart_text(- next(attr for attr in attributes if attr.pk == key)),- smart_text(value))- for (key, value) in values.items())---def get_attributes_from_dict(variant, attributes):++ if isinstance(attributes, dict):+ values = get_attributes_display_map_from_dict(variant, attributes)+ else:+ values = get_attributes_display_map(variant, attributes)+ return generate_name_from_values(values)+++def get_attributes_display_map(obj, attributes):+ display_map = {}+ for attribute in attributes:+ import pdb; pdb.set_trace()++ value = obj.attributes.get(smart_text(attribute.pk))+ if value:+ choices = {smart_text(a.pk): a for a in attribute.values.all()}+ choice_obj = choices.get(value)+ if choice_obj:+ display_map[attribute] = choice_obj+ else:+ display_map[attribute] = value+ return display_map+++def get_attributes_display_map_from_dict(variant, attributes):display_map = {}for attribute_pk, attribute_choice_pk in attributes.items():attributes = variant.product.product_type.variant_attributes.all()@@ -406,9 +405,6 @@ def get_attributes_from_dict(variant, attributes):return display_map-def generate_name_from_variant_attributes(variant, attributes):- values = get_attributes_from_dict(variant, attributes)- if not values:- return ''+def generate_name_from_values(values):return ' / '.join(- smart_text(attribute) for attribute, value in values.items())+ smart_text(value) for attribute, value in values.items())diff --git a/saleor/seo/schema/product.py b/saleor/seo/schema/product.pyindex 18c4106c27..8677b04690 100644--- a/saleor/seo/schema/product.py+++ b/saleor/seo/schema/product.py@@ -9,6 +9,7 @@ def get_brand_from_attributes(attributes):returnbrand = ''for key in attributes:+ import pdb; pdb.set_trace()if key.name == 'brand':brand = attributes[key].namebreakdiff --git a/tests/test_product.py b/tests/test_product.pyindex cb2fca7cdf..0062a64953 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -324,17 +324,6 @@ def test_get_attributes_display_map_empty(product_with_no_attributes):assert get_attributes_display_map(product, attributes) == {}-def test_get_attributes_display_map_no_choices(product_in_stock):- attributes = product_in_stock.product_type.product_attributes.all()- product_attr = attributes.first()-- product_in_stock.attributes[str(product_attr.pk)] = '-1'- attributes_display_map = get_attributes_display_map(- product_in_stock, attributes)-- assert attributes_display_map == {product_attr.pk: '-1'}--def test_product_availability_status(unavailable_product):product = unavailable_productproduct.product_type.has_variants = True@@ -483,7 +472,7 @@ def test_get_variant_picker_data_proper_variant_count(product_in_stock):def test_view_ajax_available_variants_list(admin_client, product_in_stock):variant = product_in_stock.variants.first()variant_list = [- {'id': variant.pk, 'text': '123, Test product (Size: Small), $10.00'}]+ {'id': variant.pk, 'text': '123, Test product, $10.00'}]url = reverse('dashboard:ajax-available-variants')response = admin_client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')