Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix tests, clean up code
Pacu2b377a4b77a30
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 31b2960775..a691316780 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -15,7 +15,7 @@ from prices import Money, TaxedMoneyfrom ...account.models import Address, Userfrom ...account.utils import store_user_address-from ...core.utils.text import generate_seo_description+from ...core.utils.text import strip_html_and_truncatefrom ...discount import DiscountValueType, VoucherTypefrom ...discount.models import Sale, Voucherfrom ...menu.models import Menu@@ -298,7 +298,7 @@ def create_product(**kwargs):'name': fake.company(),'price': fake.money(),'description': '\n\n'.join(description),- 'seo_description': generate_seo_description(description[0], 300)}+ 'seo_description': strip_html_and_truncate(description[0], 300)}defaults.update(kwargs)return Product.objects.create(**defaults)diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.pyindex b146881fee..0330a81c89 100644--- a/saleor/core/utils/text.py+++ b/saleor/core/utils/text.py@@ -53,7 +53,7 @@ def strip_html(text: str, **serializer_kwargs: bool):return text-def generate_seo_description(html_text: str, max_length: int):+def strip_html_and_truncate(html_text: str, max_length: int):"""Strips HTML tags and whitespaces from text,then trim the description."""text = strip_html(html_text, strip_whitespace=True)diff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.pyindex 01683fe9ca..88ad23b484 100644--- a/saleor/dashboard/category/forms.py+++ b/saleor/dashboard/category/forms.py@@ -12,17 +12,10 @@ class CategoryForm(forms.ModelForm):def __init__(self, *args, **kwargs):self.parent_pk = kwargs.pop('parent_pk')super().__init__(*args, **kwargs)- field_maxlength = self.fields['seo_description'].max_length- # Placeholder should be no longer than fields maximum size- placeholder = self.instance.description[:field_maxlength]self.fields['seo_description'].widget.attrs.update({- 'id': 'seo_description',- 'data-bind': self['description'].auto_id,- 'placeholder': placeholder})+ 'data-bind': self['description'].auto_id})self.fields['seo_title'].widget.attrs.update({- 'id': 'seo_title',- 'data-bind': self['name'].auto_id,- 'placeholder': self.instance.name})+ 'data-bind': self['name'].auto_id})class Meta:model = Categorydiff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.pyindex d577c55332..8db5b7a425 100644--- a/saleor/dashboard/collection/forms.py+++ b/saleor/dashboard/collection/forms.py@@ -6,8 +6,8 @@ from text_unidecode import unidecodefrom ...product.models import Collection, Productfrom ..forms import AjaxSelect2MultipleChoiceField-from ..widgets import CharsLeftWidgetfrom ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS+from ..widgets import CharsLeftWidgetclass CollectionForm(forms.ModelForm):@@ -39,14 +39,9 @@ class CollectionForm(forms.ModelForm):if self.instance.pk:self.fields['products'].set_initial(self.instance.products.all())self.fields['seo_description'].widget.attrs.update({- 'id': 'seo_description',- 'data-bind': '',- 'placeholder': '','min-recommended-length': 130})self.fields['seo_title'].widget.attrs.update({- 'id': 'seo_title','data-bind': self['name'].auto_id,- 'placeholder': self.instance.name[:70],'min-recommended-length': 25})def save(self, commit=True):diff --git a/saleor/dashboard/page/forms.py b/saleor/dashboard/page/forms.pyindex e52a9b5006..308bcce0db 100644--- a/saleor/dashboard/page/forms.py+++ b/saleor/dashboard/page/forms.py@@ -1,30 +1,20 @@from django import formsfrom django.utils.translation import pgettext_lazy-from ...core.utils.text import generate_seo_descriptionfrom ...page.models import Pagefrom ..product.forms import RichTextField-from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS+from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS, prepare_seo_descriptionclass PageForm(forms.ModelForm):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- # Placeholder should be no longer than fields maximum size- field_maxlength = self.fields['seo_description'].max_length- # Page's content contains htm tags which should be stripped- placeholder = generate_seo_description(- self.instance.content, field_maxlength)self.fields['seo_description'].widget.attrs.update({- 'id': 'seo_description','data-bind': self['content'].auto_id,- 'data-materialize': self['content'].html_name,- 'placeholder': placeholder})+ 'data-materialize': self['content'].html_name})self.fields['seo_title'].widget.attrs.update({- 'id': 'seo_title',- 'data-bind': self['title'].auto_id,- 'placeholder': self.instance.title})+ 'data-bind': self['title'].auto_id})class Meta:model = Page@@ -50,14 +40,8 @@ class PageForm(forms.ModelForm):return slugdef clean_seo_description(self):- seo_description = self.cleaned_data['seo_description']-- # if there is no SEO friendly description set,- # generate it from the HTML description- if not seo_description:- # get the non-safe description (has non escaped HTML tags in it)- description = self.data['description']-- # generate a SEO friendly from HTML description- seo_description = generate_seo_description(description, 300)+ seo_description = prepare_seo_description(+ seo_description=self.cleaned_data['seo_description'],+ html_description=self.data['content'],+ max_length=self.fields['seo_description'].max_length)return seo_descriptiondiff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 04e2bbe4f8..b6a54b5889 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -9,7 +9,6 @@ from django.utils.text import slugifyfrom django.utils.translation import pgettext_lazyfrom mptt.forms import TreeNodeChoiceField-from ...core.utils.text import generate_seo_descriptionfrom ...product.models import (AttributeChoiceValue, Category, Collection, Product, ProductAttribute,ProductImage, ProductType, ProductVariant, Stock, StockLocation,@@ -18,7 +17,7 @@ from ..forms import OrderedModelMultipleChoiceField, ModelChoiceOrCreationFieldfrom ..widgets import RichTextEditorWidgetfrom .widgets import ImagePreviewWidgetfrom . import ProductBulkAction-from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS+from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS, prepare_seo_descriptionclass RichTextField(forms.CharField):@@ -221,34 +220,17 @@ class ProductForm(forms.ModelForm, AttributesMixin):self.prepare_fields_for_attributes()self.fields['collections'].initial = Collection.objects.filter(products__name=self.instance)- # Placeholder should be no longer than fields maximum size- field_maxlength = self.fields['seo_description'].max_length- # Product's description contains htm tags which should be stripped- placeholder = generate_seo_description(- self.instance.description, field_maxlength)self.fields['seo_description'].widget.attrs.update({- 'id': 'seo_description','data-bind': self['description'].auto_id,- 'data-materialize': self['description'].html_name,- 'placeholder': placeholder})+ 'data-materialize': self['description'].html_name})self.fields['seo_title'].widget.attrs.update({- 'id': 'seo_title',- 'data-bind': self['name'].auto_id,- 'placeholder': self.instance.name})+ 'data-bind': self['name'].auto_id})def clean_seo_description(self):- seo_description = self.cleaned_data['seo_description']-- # if there is no SEO friendly description set,- # generate it from the HTML description- if not seo_description:- # get the non-safe description (has non escaped HTML tags in it)- product_description = self.data['description']-- # generate a SEO friendly from HTML description- seo_description = generate_seo_description(- product_description, 300)-+ seo_description = prepare_seo_description(+ seo_description=self.cleaned_data['seo_description'],+ html_description=self.data['description'],+ max_length=self.fields['seo_description'].max_length)return seo_descriptiondef save(self, commit=True):diff --git a/saleor/dashboard/seo/utils.py b/saleor/dashboard/seo/utils.pynew file mode 100644index 0000000000..b38401a40a--- /dev/null+++ b/saleor/dashboard/seo/utils.py@@ -0,0 +1,36 @@+from django.utils.translation import pgettext_lazy++from ...core.utils.text import strip_html_and_truncate++SEO_HELP_TEXTS = {+ 'seo_description': pgettext_lazy(+ 'Form field help text',+ (+ 'If empty, the preview shows what will be autogenerated.')),+ 'seo_title': pgettext_lazy(+ 'Form field help text',+ (+ 'If empty, the preview shows what will be autogenerated.'))}++SEO_LABELS = {+ 'seo_description': pgettext_lazy(+ (+ 'Field name, Meta Description is page summary '+ 'used by Search Engines'),+ 'Meta Description'),+ 'seo_title': pgettext_lazy(+ (+ 'Field name, '+ 'Title that will be used to describe page in Search Engines'),+ 'SEO Title')}+++def prepare_seo_description(seo_description, html_description, max_length):+ # if there is no SEO friendly description set,+ # generate it from the HTML description+ if not seo_description:+ # get the non-safe description (has non escaped HTML tags in it)+ # generate a SEO friendly from HTML description+ seo_description = strip_html_and_truncate(+ html_description, max_length)+ return seo_descriptiondiff --git a/saleor/product/migrations/0053_product_seo_description.py b/saleor/product/migrations/0053_product_seo_description.pyindex 15c29c832a..0c388e3d37 100644--- a/saleor/product/migrations/0053_product_seo_description.py+++ b/saleor/product/migrations/0053_product_seo_description.py@@ -3,7 +3,7 @@ import htmlfrom django.core.validators import MaxLengthValidatorfrom django.db import migrations, models-from saleor.core.utils.text import generate_seo_description+from saleor.core.utils.text import strip_html_and_truncatedef to_seo_friendly(text):@@ -12,7 +12,7 @@ def to_seo_friendly(text):text = html.unescape(text)# cleanup the description and make it seo friendly- return generate_seo_description(text, 300)+ return strip_html_and_truncate(text, 300)def assign_seo_descriptions(apps, schema_editor):diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 1817c9a9bf..e4475cd307 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -3,8 +3,7 @@ from decimal import Decimalfrom django.conf import settingsfrom django.contrib.postgres.fields import HStoreField-from django.core.validators import (- MinValueValidator, RegexValidator)+from django.core.validators import MinValueValidator, RegexValidatorfrom django.db import modelsfrom django.db.models import F, Max, Qfrom django.urls import reversediff --git a/saleor/seo/models.py b/saleor/seo/models.pyindex 392aa6a8da..8343fbf35f 100644--- a/saleor/seo/models.py+++ b/saleor/seo/models.py@@ -1,5 +1,5 @@-from django.db import modelsfrom django.core.validators import MaxLengthValidator+from django.db import modelsclass SeoModel(models.Model):diff --git a/saleor/static/dashboard/js/components/google-preview.js b/saleor/static/dashboard/js/components/google-preview.jsindex 3fc786bb79..4d05f9b15a 100644--- a/saleor/static/dashboard/js/components/google-preview.js+++ b/saleor/static/dashboard/js/components/google-preview.js@@ -1,10 +1,11 @@-const $seoTitle = $('#seo_title');+const $seoTitle = $('#id_seo_title');const $nameId = $seoTitle.data('bind');const $name = $(`#${$nameId}`);-const $seoDescription = $('#seo_description');+const $seoDescription = $('#id_seo_description');const $descriptionMaterialize = $seoDescription.data('materialize');+let $description = '';if ($descriptionMaterialize) {$description = $(`.materialize-textarea[name='${$descriptionMaterialize}']`);@@ -22,11 +23,21 @@ const $previewErrors = $('#preview-error');const watchedEvents = 'input propertychange cut paste copy change';-function updateCharsCount(field) {- const $fieldId = field.attr('id');+function setPlaceholderAndPreview(field, seoField, previewField) {+ const $text = field.text() || field.val();+ const $placeholderText = truncate($text, seoField);+ seoField.attr('placeholder', $placeholderText);+ previewField.text(seoField.val() || $placeholderText);+}++function updateCharsCount(seoField) {+ const $fieldId = seoField.attr('id');const $charCount = $(`span[data-bind=${$fieldId}]`);- const $fieldLength = field.val().length || field.attr('placeholder').length;- const $minRecommendedLength = field.attr('min-recommended-length');+ let $fieldLength = seoField.val().length || seoField.text().length;+ if (!$fieldLength && seoField.attr('placeholder')) {+ $fieldLength = seoField.attr('placeholder').length;+ }+ const $minRecommendedLength = seoField.attr('min-recommended-length');const $charCountWrapper = $charCount.parent();if ($fieldLength < $minRecommendedLength) {$charCountWrapper.addClass('red-text');@@ -46,28 +57,31 @@ function checkForErrors() {$previewErrors.hide();} else if (!$descriptionText && !$titleText) {$preview.hide();- $previewErrors.text(gettext('Please provide title and description to see how this product might appear in search engine results.'));+ $previewErrors.text(gettext('Please provide SEO Title and Meta Description to see how this product might appear in search engine results.'));$previewErrors.show();} else if (!$descriptionText) {$preview.hide();- $previewErrors.text(gettext('Please provide description to see how this product might appear in search engine results.'));+ $previewErrors.text(gettext('Please provide Meta Description to see how this product might appear in search engine results.'));$previewErrors.show();} else if (!$titleText) {$preview.hide();- $previewErrors.text(gettext('Please provide title to see how this product might appear in search engine results.'));+ $previewErrors.text(gettext('Please provide SEO Title to see how this product might appear in search engine results.'));$previewErrors.show();}}function truncate(text, seoField) {const $fieldMaxLength = seoField.prop('maxLength');- return text.substring(text, $fieldMaxLength);+ if (text && text.length > $fieldMaxLength) {+ return text.substring(text, $fieldMaxLength);+ }+ return text;}function updatePlaceholderOnInput(field, seoField, previewField) {field.on(watchedEvents, (e) => {const $target = $(e.currentTarget);- const $placeholderText = $target.val();+ const $placeholderText = $target.val() || $target.text();seoField.attr('placeholder', truncate($placeholderText, seoField));const $seoText = seoField.val();if (!$seoText) {@@ -93,12 +107,20 @@ function updatePreviewOnInput(seoField, previewField) {});}-checkForErrors();-updatePlaceholderOnInput($name, $seoTitle, $googleTitlePreview);-if ($description) {- updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);+if ($seoTitle.length) {+ if ($name) {+ setPlaceholderAndPreview($name, $seoTitle, $googleTitlePreview);+ updatePlaceholderOnInput($name, $seoTitle, $googleTitlePreview);+ }+ updatePreviewOnInput($seoTitle, $googleTitlePreview);+ updateCharsCount($seoTitle);}-updatePreviewOnInput($seoTitle, $googleTitlePreview);-updatePreviewOnInput($seoDescription, $googleDescriptionPreview);-updateCharsCount($seoTitle);-updateCharsCount($seoDescription);+if ($seoDescription.length) {+ if ($description) {+ setPlaceholderAndPreview($description, $seoDescription, $googleDescriptionPreview);+ updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);+ }+ updatePreviewOnInput($seoDescription, $googleDescriptionPreview);+ updateCharsCount($seoDescription);+}+checkForErrors();diff --git a/saleor/static/dashboard/scss/components/_google-preview.scss b/saleor/static/dashboard/scss/components/_google-preview.scssindex 017619d886..a9d5f66507 100644--- a/saleor/static/dashboard/scss/components/_google-preview.scss+++ b/saleor/static/dashboard/scss/components/_google-preview.scss@@ -1,7 +1,7 @@.google-preview {text-align: left;letter-spacing: initial;-+ padding-top: 1rem;&__container {margin: 12px;background-color: #fff;@@ -12,11 +12,11 @@text-overflow: ellipsis;margin-bottom: 2px;a {- color: rgb(26, 13, 171);+ color: #1A0DAB;cursor: pointer;font-size: 18px;line-height: 21px;- text-decoration: none solid rgb(26, 13, 171);+ text-decoration: none solid #1A0DAB;&:hover {text-decoration: underline;}@@ -25,13 +25,13 @@}}&__description {- color: rgb(84, 84, 84);+ color: #545454;font-size: 13px;line-height: 18px;overflow-wrap: break-word;}&__url {- color: rgb(0, 102, 33);+ color: #006621;font-size: 13px;line-height: 16px;white-space: nowrap;diff --git a/templates/dashboard/includes/_google_preview.html b/templates/dashboard/includes/_google_preview.htmlindex 9d4a8b6372..445b82e1f3 100644--- a/templates/dashboard/includes/_google_preview.html+++ b/templates/dashboard/includes/_google_preview.html@@ -9,7 +9,7 @@<div id="preview-error"></div><div id="google-preview"><div class='google-preview__title'>- <a id="google-preview-title" href='#'>{{ object.seo_title|default:form.seo_title.field.widget.attrs.placeholder }}</a>+ <a id="google-preview-title" href='#'>{{ object.seo_title|default:"" }}</a></div><div class='google-preview__url'>{% if object.pk %}@@ -18,7 +18,7 @@{% build_absolute_uri request=request location="/" %}{% endif %}</div>- <div id="google-preview-description" class='google-preview__description'>{{ object.seo_description|default:form.seo_description.field.widget.attrs.placeholder }}</div>+ <div id="google-preview-description" class='google-preview__description'>{{ object.seo_description|default:"" }}</div></div></div></div>diff --git a/templates/materializecssform/field.html b/templates/materializecssform/field.htmlindex bac8d7b657..7049c49df2 100644--- a/templates/materializecssform/field.html+++ b/templates/materializecssform/field.html@@ -344,7 +344,7 @@{% endif %}</label><span class="chars-left__count">- <span class="chars-left__count__current" data-bind="{{ field.field.widget.attrs.id }}">+ <span class="chars-left__count__current" data-bind="{{ field.auto_id }}">{% blocktrans with current_chars_count=field.value|length max_chars_count=field.field.max_length context "Message showing how many chars were used out of maximum field's length" %}{{ current_chars_count }}</span> of {{ max_chars_count }} characters used{% endblocktrans %}diff --git a/tests/dashboard/test_page.py b/tests/dashboard/test_page.pyindex 095e15ed6d..01473115b7 100644--- a/tests/dashboard/test_page.py+++ b/tests/dashboard/test_page.py@@ -54,7 +54,7 @@ def test_page_delete(admin_client, page):def test_sanitize_page_content(page, default_category):data = model_to_dict(page)- data['description'] = (+ data['content'] = ('<b>bold</b><p><i>italic</i></p><h2>Header</h2><h3>subheader</h3>''<blockquote>quote</blockquote>''<p><a href="www.mirumee.com">link</a></p>'@@ -72,17 +72,17 @@ def test_sanitize_page_content(page, default_category):'bolditalicHeadersubheaderquotelinkan evil()example')-def test_set_product_seo_description(unavailable_product):+def test_set_page_seo_description(page):seo_description = (- 'This is a dummy product. '+ 'This is a dummy page. ''HTML <b>shouldn\'t be removed</b> since it\'s a simple text field.')- data = model_to_dict(unavailable_product)+ data = model_to_dict(page)data['price'] = 20- data['description'] = 'a description'+ data['content'] = 'a description'data['seo_description'] = seo_description- form = PageForm(data, instance=unavailable_product)+ form = PageForm(data, instance=page)assert form.is_valid()form.save()- assert unavailable_product.seo_description == seo_description+ assert page.seo_description == seo_description