Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add flag to Collection
Andy Summers24acc95704d0
diff --git a/saleor/core/sitemaps.py b/saleor/core/sitemaps.pyindex c242646b17..af923cfa82 100644--- a/saleor/core/sitemaps.py+++ b/saleor/core/sitemaps.py@@ -26,7 +26,7 @@ class CategorySitemap(I18nSitemap):class CollectionSitemap(I18nSitemap):def items(self):- collections = Collection.objects.all().order_by('id')+ collections = Collection.objects.public().order_by('id')return collections.only('id', 'name', 'slug')diff --git a/saleor/core/templatetags/status.py b/saleor/core/templatetags/status.pyindex 61188dc83f..8bd43cba0b 100644--- a/saleor/core/templatetags/status.py+++ b/saleor/core/templatetags/status.py@@ -73,3 +73,14 @@ def render_page_availability(page):label_cls = LABEL_SUCCESSctx.update({'label_cls': label_cls})return ctx++[email protected]_tag('dashboard/includes/_collection_availability.html')+def render_collection_availability(collection):+ if collection.is_published:+ label_cls = LABEL_SUCCESS+ else:+ label_cls = LABEL_DANGER+ return {'is_published': collection.is_published,+ 'collection': collection,+ 'label_cls': label_cls}diff --git a/saleor/dashboard/collection/filters.py b/saleor/dashboard/collection/filters.pyindex 8cfb0f7d20..2c8eae15bc 100644--- a/saleor/dashboard/collection/filters.py+++ b/saleor/dashboard/collection/filters.py@@ -1,5 +1,6 @@+from django import formsfrom django.utils.translation import npgettext, pgettext_lazy-from django_filters import CharFilter, OrderingFilter+from django_filters import CharFilter, ChoiceFilter, OrderingFilterfrom ...core.filters import SortedFilterSetfrom ...product.models import Collection@@ -7,11 +8,20 @@ from ...product.models import CollectionSORT_BY_FIELDS = {'name': pgettext_lazy('Collection list sorting option', 'name')}+PUBLISHED_CHOICES = (+ ('1', pgettext_lazy('Is publish filter choice', 'Published')),+ ('0', pgettext_lazy('Is publish filter choice', 'Not published')))+class CollectionFilter(SortedFilterSet):name = CharFilter(label=pgettext_lazy('Collection list name filter label', 'Name'),lookup_expr='icontains')+ is_published = ChoiceFilter(+ label=pgettext_lazy('Collection list filter label', 'Is published'),+ choices=PUBLISHED_CHOICES,+ empty_label=pgettext_lazy('Filter empty choice label', 'All'),+ widget=forms.Select)sort_by = OrderingFilter(label=pgettext_lazy('Collection list sorting filter label', 'Sort by'),fields=SORT_BY_FIELDS.keys(),diff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.pyindex da850f3e4f..9b7d464e03 100644--- a/saleor/dashboard/collection/forms.py+++ b/saleor/dashboard/collection/forms.py@@ -22,7 +22,10 @@ class CollectionForm(forms.ModelForm):'products': pgettext_lazy('Products selection', 'Products'),'background_image': pgettext_lazy('Products selection',- 'Background Image')}+ 'Background Image'),+ 'is_published': pgettext_lazy(+ 'Collection published toggle',+ 'Published')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)diff --git a/saleor/dashboard/collection/urls.py b/saleor/dashboard/collection/urls.pyindex 669540c1cd..640d468044 100644--- a/saleor/dashboard/collection/urls.py+++ b/saleor/dashboard/collection/urls.py@@ -7,5 +7,7 @@ urlpatterns = [url(r'^add/$', views.collection_create, name='collection-add'),url(r'^(?P<pk>[0-9]+)/edit/$',views.collection_update, name='collection-update'),+ url(r'^(?P<pk>[0-9]+)/publish/$', views.collection_toggle_is_published,+ name='collection-publish'),url(r'^(?P<pk>[0-9]+)/delete/$',views.collection_delete, name='collection-delete')]diff --git a/saleor/dashboard/collection/views.py b/saleor/dashboard/collection/views.pyindex e0b1b5f4d3..f6e745bffa 100644--- a/saleor/dashboard/collection/views.py+++ b/saleor/dashboard/collection/views.py@@ -6,6 +6,7 @@ from django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponsefrom django.urls import reversefrom django.utils.translation import pgettext_lazy+from django.views.decorators.http import require_POSTfrom ...core.utils import get_paginator_itemsfrom ...product.models import Collection@@ -74,3 +75,14 @@ def collection_delete(request, pk=None):ctx = {'collection': collection}return TemplateResponse(request, 'dashboard/collection/confirm_delete.html', ctx)+++@require_POST+@staff_member_required+@permission_required('product.edit_product')+def collection_toggle_is_published(request, pk):+ collection = get_object_or_404(Collection, pk=pk)+ collection.is_published = not collection.is_published+ collection.save(update_fields=['is_published'])+ return JsonResponse(+ {'success': True, 'is_published': collection.is_published})diff --git a/saleor/product/migrations/0060_collection_is_published.py b/saleor/product/migrations/0060_collection_is_published.pynew file mode 100644index 0000000000..5978d80bbb--- /dev/null+++ b/saleor/product/migrations/0060_collection_is_published.py@@ -0,0 +1,18 @@+# Generated by Django 2.0.3 on 2018-04-21 00:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0059_generate_variant_name_from_attrs'),+ ]++ operations = [+ migrations.AddField(+ model_name='collection',+ name='is_published',+ field=models.BooleanField(default=False),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 497df12458..789c3f3728 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -320,6 +320,11 @@ class VariantImage(models.Model):ProductImage, related_name='variant_images', on_delete=models.CASCADE)+class CollectionQuerySet(models.QuerySet):+ def public(self):+ return self.filter(is_published=True)++class Collection(SeoModel):name = models.CharField(max_length=128, unique=True)slug = models.SlugField(max_length=128)@@ -327,6 +332,9 @@ class Collection(SeoModel):Product, blank=True, related_name='collections')background_image = VersatileImageField(upload_to='collection-backgrounds', blank=True, null=True)+ is_published = models.BooleanField(default=False)++ objects = CollectionQuerySet.as_manager()class Meta:ordering = ['pk']diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.pyindex 97bc2d67c9..ede7a70c1e 100644--- a/saleor/product/utils/__init__.py+++ b/saleor/product/utils/__init__.py@@ -116,3 +116,11 @@ def get_product_list_context(request, filter_set):'sort_by_choices': SORT_BY_FIELDS,'now_sorted_by': now_sorted_by,'is_descending': is_descending}+++def collections_visible_to_user(user):+ # 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.public()diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 50723a3d22..49194f22ee 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -13,7 +13,7 @@ from .filters import ProductCategoryFilter, ProductCollectionFilterfrom .models import Category, Collectionfrom .utils import (get_product_images, get_product_list_context, handle_cart_form,- products_for_cart, products_with_details)+ products_for_cart, products_with_details, collections_visible_to_user)from .utils.attributes import get_product_attributes_datafrom .utils.availability import get_availabilityfrom .utils.variants_picker import get_variant_picker_data@@ -128,7 +128,8 @@ def category_index(request, path, category_id):def collection_index(request, slug, pk):- collection = get_object_or_404(Collection, id=pk)+ collections = collections_visible_to_user(request.user)+ collection = get_object_or_404(collections, id=pk)if collection.slug != slug:return HttpResponsePermanentRedirect(collection.get_absolute_url())products = products_with_details(user=request.user).filter(diff --git a/saleor/static/dashboard/js/components/misc.js b/saleor/static/dashboard/js/components/misc.jsindex 35880e463f..82a0bbdb1a 100644--- a/saleor/static/dashboard/js/components/misc.js+++ b/saleor/static/dashboard/js/components/misc.js@@ -39,24 +39,27 @@ $(document).on('mouseup', 'tr[data-action-go] > td:not(.ignore-link)', (e) => {}});-// Publish / unpublish lever in product detail view-$('#product-is-published').on('click', (e) => {- const form = $(e.currentTarget).closest('#toggle-publish-form');- const input = form.find('#toggle-publish-switch')[0];- if (e.target === input) {- const url = form.attr('action');- fetch(url, {- method: 'POST',- credentials: 'same-origin',- headers: {- 'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val()- }- }).then(() => {- window.location.reload();- }).catch(() => {- window.location.reload();- });- }+// Publish / unpublish lever in detail views+const selectors = ['#product-is-published', '#collection-is-published'];+selectors.forEach(selector => {+ $(selector).on('click', (e) => {+ const form = $(e.currentTarget).closest('#toggle-publish-form');+ const input = form.find('#toggle-publish-switch')[0];+ if (e.target === input) {+ const url = form.attr('action');+ fetch(url, {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ 'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val()+ }+ }).then(() => {+ window.location.reload();+ }).catch(() => {+ window.location.reload();+ });+ }+ });});// Styleguide sticky right menudiff --git a/templates/collection/index.html b/templates/collection/index.htmlindex 5526622b83..6f4a7d9747 100644--- a/templates/collection/index.html+++ b/templates/collection/index.html@@ -9,6 +9,17 @@<li><a href='{{ object.get_absolute_url }}'>{{ object.name }}</a></li>{% endblock %}+{% block collection_published_warning %}+ {% if not object.is_published %}+ <div class="alert alert-warning" role="alert">+ {% blocktrans context "Unavailable collection detail text" %}+ <strong>Warning!</strong>+ You are previewing a collection that is not published.+ {% endblocktrans %}+ </div>+ {% endif %}+{% endblock %}+{% block filters %}{% include "product/_filters.html" %}{% endblock filters %}diff --git a/templates/dashboard/collection/detail.html b/templates/dashboard/collection/detail.htmlindex 591fb186e6..bfc18933de 100644--- a/templates/dashboard/collection/detail.html+++ b/templates/dashboard/collection/detail.html@@ -2,6 +2,7 @@{% load materializecss %}{% load i18n %}{% load staticfiles %}+{% load status %}{% block title %}{% if collection.pk %}{{ collection }}{% else %}{% trans 'Add new collection' %}{% endif %} - {% trans 'Collections' %} - {{ block.super }}{% endblock %}@@ -58,6 +59,10 @@<div class="row">{{ form.background_image|materializecss }}</div>+ <span class="card-title">Availability</span>+ <div class="row">+ {{ form.is_published|materializecss }}+ </div>{% include "dashboard/includes/_google_preview.html" with object=collection form=form %}</div><div class="card-action right-align">@@ -76,5 +81,36 @@</form></div></div>+ {% if collection.pk %}+ <div class="col s12 l3">+ <div id="status">+ <div class="row no-margin">+ <div class="col s12">+ <div class="card">+ <div class="card-content">+ <form id="toggle-publish-form" action="{% url 'dashboard:collection-publish' pk=collection.pk %}">+ <div class="switch" id="collection-is-published">+ <label>+ <input id="toggle-publish-switch" type="checkbox" {% if collection.is_published %} checked {% endif %}>+ <span class="lever"></span>+ <span class="label">+ {% if collection.is_published %}+ {% trans "Published" context "Collection field" %}+ {% else %}+ {% trans "Draft" context "Collection field" %}+ {% endif %}+ </span>+ </label>+ </div>+ {% csrf_token %}+ </form>+ <h5>{% render_collection_availability collection %}</h5>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ {% endif %}</div>{% endblock %}diff --git a/templates/dashboard/collection/list.html b/templates/dashboard/collection/list.htmlindex c2b0bcc317..b10649aa0d 100644--- a/templates/dashboard/collection/list.html+++ b/templates/dashboard/collection/list.html@@ -2,6 +2,7 @@{% load i18n %}{% load staticfiles %}+{% load status %}{% load utils %}{% block title %}@@ -42,6 +43,9 @@<th>{% trans "Number of products" context "Voucher table header" %}</th>+ <th>+ {% trans "Visibility" context "Collections list table header" %}+ </th></tr></thead>{% for node in collections %}@@ -57,6 +61,9 @@-{% endif %}</td>+ <td>+ {% render_collection_availability node %}+ </td></tr></tbody>{% endfor %}diff --git a/templates/dashboard/includes/_collection_availability.html b/templates/dashboard/includes/_collection_availability.htmlnew file mode 100644index 0000000000..780bffc204--- /dev/null+++ b/templates/dashboard/includes/_collection_availability.html@@ -0,0 +1,9 @@+{% load i18n %}++ <div class="label label-{{ label_cls }}">+ {% if is_published %}+ {% trans "Published" context "Collection availability status" %}+ {% else %}+ {% trans "Not Published" context "Collection availability status" %}+ {% endif %}+ </div>diff --git a/templates/product/product_list_base.html b/templates/product/product_list_base.htmlindex 7dbdf05c72..8501e206ff 100644--- a/templates/product/product_list_base.html+++ b/templates/product/product_list_base.html@@ -114,6 +114,9 @@{% endblock topcontent %}{% block content %}++ {% block collection_published_warning %}{% endblock %}+<div id="product-list-page"><div class="row"><div class="col-md-4 col-lg-3">diff --git a/tests/conftest.py b/tests/conftest.pyindex aaa0fac1e5..c4d77d8eac 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -629,6 +629,13 @@ def permission_view_menu():@pytest.fixturedef collection(db):+ collection = Collection.objects.create(+ name='Collection', slug='collection', is_published=True)+ return collection+++def draft_collection(db):collection = Collection.objects.create(name='Collection', slug='collection')return collectiondiff --git a/tests/dashboard/test_collection.py b/tests/dashboard/test_collection.pyindex ba76b1f51a..7a2491212b 100644--- a/tests/dashboard/test_collection.py+++ b/tests/dashboard/test_collection.py@@ -1,3 +1,4 @@+import jsonimport pytestfrom django.urls import reverse@@ -74,3 +75,14 @@ def test_collection_delete_view(admin_client, collection):response = admin_client.post(url)assert response.status_code == 302assert Collection.objects.count() == (collections_count - 1)+++def test_collection_is_published_toggle_view(db, admin_client, collection):+ url = reverse('dashboard:collection-publish', kwargs={'pk': collection.pk})+ response = admin_client.post(url)+ assert response.status_code == 200+ data = {'success': True, 'is_published': False}+ assert json.loads(response.content.decode('utf8')) == data+ admin_client.post(url)+ collection.refresh_from_db()+ assert collection.is_publisheddiff --git a/tests/test_collection.py b/tests/test_collection.pyindex fbd31e631e..0c1afb9b41 100644--- a/tests/test_collection.py+++ b/tests/test_collection.py@@ -31,3 +31,10 @@ def test_collection_not_exists(client):url = reverse('product:collection', kwargs=url_kwargs)response = client.get(url)assert response.status_code == 404+++def test_collection_not_published_404(client, draft_collection):+ url_kwargs = {'pk': draft_collection.pk, 'slug': draft_collection.slug}+ url = reverse('product:collection', kwargs=url_kwargs)+ response = client.get(url)+ assert response.status_code == 404