Skip to content

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

Rework Menu into JSON

Pacu2dfee30fdc8f4
diff --git a/requirements.txt b/requirements.txt
index 0f66195645..cdb1123383 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -65,7 +65,7 @@ graphene==2.1.3 # via django-graphql-jwt, graphene-django
graphql-core==2.1 # via graphene, graphene-django, graphql-relay
graphql-relay==0.4.5 # via graphene
html5lib==1.0.1 # via bleach, weasyprint
-idna==2.6 # via cryptography, requests
+idna==2.6 # via cryptography, requests, yarl
iso8601==0.1.12 # via graphene-django
jmespath==0.9.3 # via boto3, botocore
jsonfield==2.0.2
@@ -73,6 +73,7 @@ kombu==4.2.1 # via celery
markdown==2.6.11
maxminddb-geolite2==2017.803
maxminddb==1.3.0
+multidict==4.3.1 # via yarl
oauthlib==2.0.6 # via requests-oauthlib, social-auth-core
pdfrw==0.4 # via weasyprint
phonenumberslite==8.9.1
@@ -118,3 +119,4 @@ weasyprint==0.42.2
webencodings==0.5.1 # via html5lib, tinycss2
wrapt==1.10.11 # via vcrpy
xmltodict==0.11.0 # via django-payments
+yarl==1.2.6 # via vcrpy
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 5813d12179..4351adeafc 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -344,5 +344,8 @@ class CartVoucherForm(forms.ModelForm):
voucher = self.cleaned_data['voucher']
self.instance.voucher_code = voucher.code
self.instance.discount_name = voucher.name
+ self.instance.translated_discount_name = (
+ voucher.translated.name
+ if voucher.translated.name != voucher.name else '')
self.instance.discount_amount = self.cleaned_data['discount_amount']
return super().save(commit)
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index b84f836cde..f3fcb67c88 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -57,6 +57,8 @@ class Cart(models.Model):
currency=settings.DEFAULT_CURRENCY, max_digits=12,
decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)
discount_name = models.CharField(max_length=255, blank=True, null=True)
+ translated_discount_name = models.CharField(
+ max_length=255, blank=True, null=True)
voucher_code = models.CharField(max_length=12, blank=True, null=True)
objects = CartQueryset.as_manager()
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index e8bb953d63..ad18cf5885 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -727,7 +727,13 @@ def recalculate_cart_discount(cart, discounts, taxes):
subtotal = cart.get_subtotal(discounts, taxes).gross
cart.discount_amount = min(discount, subtotal)
cart.discount_name = voucher.name
- cart.save(update_fields=['discount_amount', 'discount_name'])
+ cart.translated_discount_name = (
+ voucher.translated.name
+ if voucher.translated.name != voucher.name else '')
+ cart.save(
+ update_fields=[
+ 'translated_discount_name',
+ 'discount_amount', 'discount_name'])
else:
remove_voucher_from_cart(cart)
@@ -736,9 +742,12 @@ def remove_voucher_from_cart(cart):
"""Remove voucher data from cart."""
cart.voucher_code = None
cart.discount_name = None
+ cart.translated_discount_name = None
cart.discount_amount = ZERO_MONEY
- cart.save(update_fields=[
- 'voucher_code', 'discount_name', 'discount_amount'])
+ cart.save(
+ update_fields=[
+ 'voucher_code', 'discount_name', 'translated_discount_name',
+ 'discount_amount'])
def get_taxes_for_cart(cart, default_taxes):
@@ -782,7 +791,8 @@ def _process_voucher_data_for_order(cart):
return {
'voucher': voucher,
'discount_amount': cart.discount_amount,
- 'discount_name': cart.discount_name}
+ 'discount_name': cart.discount_name,
+ 'translated_discount_name': cart.translated_discount_name}
def _process_shipping_data_for_order(cart, taxes):
diff --git a/saleor/core/__init__.py b/saleor/core/__init__.py
index c362432507..a26d54fed4 100644
--- a/saleor/core/__init__.py
+++ b/saleor/core/__init__.py
@@ -3,7 +3,6 @@ from django.core.checks import register, Warning
TOKEN_PATTERN = ('(?P<token>[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}'
'-[0-9a-z]{12})')
-NAVIGATION_CONTEXT_NAME = 'menus'
@register()
diff --git a/saleor/core/context_processors.py b/saleor/core/context_processors.py
index 794b4a166e..ceb9e1e3d3 100644
--- a/saleor/core/context_processors.py
+++ b/saleor/core/context_processors.py
@@ -1,8 +1,5 @@
from django.conf import settings
-from . import NAVIGATION_CONTEXT_NAME
-from ..menu.models import Menu
-
def get_setting_as_dict(name, short_name=None):
short_name = short_name or name
@@ -18,15 +15,5 @@ def default_currency(request):
return get_setting_as_dict('DEFAULT_CURRENCY')
-# request is a required parameter
-# pylint: disable=W0613
-def navigation(request):
- menus = Menu.objects.prefetch_related(
- 'items__collection', 'items__category', 'items__page',
- 'items__translations'
- ).filter(items__parent=None)
- return {NAVIGATION_CONTEXT_NAME: list(menus)}
-
-
def search_enabled(request):
return {'SEARCH_IS_ENABLED': settings.ENABLE_SEARCH}
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index b7e8ba3ad0..7fd28c0e9b 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -52,27 +52,27 @@ class Command(BaseCommand):
def handle(self, *args, **options):
self.make_database_faster()
- create_images = not options['withoutimages']
- # for msg in create_shipping_methods():
- # self.stdout.write(msg)
- # create_products_by_schema(
- # self.placeholders_dir, 10, create_images, stdout=self.stdout)
- # for msg in create_product_sales(5):
- # self.stdout.write(msg)
- # for msg in create_vouchers():
- # self.stdout.write(msg)
- # for msg in create_users(20):
- # self.stdout.write(msg)
- # for msg in create_orders(20):
- # self.stdout.write(msg)
- # for msg in set_featured_products(16):
- # self.stdout.write(msg)
- # for msg in create_collections_by_schema(self.placeholders_dir):
- # self.stdout.write(msg)
- # for msg in create_page():
- # self.stdout.write(msg)
- # for msg in create_menus():
- # self.stdout.write(msg)
+ create_images = False and not options['withoutimages']
+ for msg in create_shipping_methods():
+ self.stdout.write(msg)
+ create_products_by_schema(
+ self.placeholders_dir, 10, create_images, stdout=self.stdout)
+ for msg in create_product_sales(5):
+ self.stdout.write(msg)
+ for msg in create_vouchers():
+ self.stdout.write(msg)
+ for msg in create_users(20):
+ self.stdout.write(msg)
+ for msg in create_orders(20):
+ self.stdout.write(msg)
+ for msg in set_featured_products(16):
+ self.stdout.write(msg)
+ for msg in create_collections_by_schema(self.placeholders_dir):
+ self.stdout.write(msg)
+ for msg in create_page():
+ self.stdout.write(msg)
+ for msg in create_menus():
+ self.stdout.write(msg)
create_translations()
if options['createsuperuser']:
credentials = {'email': '[email protected]', 'password': 'admin'}
diff --git a/saleor/core/templatetags/shop.py b/saleor/core/templatetags/shop.py
index 05f25f1e32..e669dae98c 100644
--- a/saleor/core/templatetags/shop.py
+++ b/saleor/core/templatetags/shop.py
@@ -1,8 +1,8 @@
+import json
+
from django.template import Library
from django.utils.http import urlencode
-from ..context_processors import NAVIGATION_CONTEXT_NAME
-
register = Library()
@@ -17,13 +17,17 @@ def get_sort_by_url(context, field, descending=False):
return '%s?%s' % (request.path, urlencode(request_get))
[email protected]_tag('menu.html', takes_context=True)
-def menu(context, site_menu=None, horizontal=False):
- if not site_menu:
- return
- menus = context[NAVIGATION_CONTEXT_NAME]
- menu = next((menu for menu in menus if menu.pk == site_menu.pk), None)
- if not menu:
- return
- menu_items = [item for item in menu.items.all() if item.parent_id is None]
- return {'menu_items': menu_items, 'horizontal': horizontal}
[email protected]_tag('menu.html')
+def menu(site_menu=None, horizontal=False):
+ menu_items = json.loads(site_menu.json_content) if site_menu else []
+ return {
+ 'menu_items': menu_items,
+ 'horizontal': horizontal}
+
+
+def get_menu_item_name(menu_item, lang_code):
+ translated = menu_item['translations'].get(lang_code)
+ if translated:
+ return translated['name']
+ return menu_item['name']
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 770f66db95..040ce572e7 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -20,6 +20,7 @@ from ...account.utils import store_user_address
from ...checkout import AddressType
from ...core.utils.taxes import get_tax_rate_by_name, get_taxes_for_country
from ...core.utils.text import strip_html_and_truncate
+from ...dashboard.menu.utils import update_menu
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
from ...menu.models import Menu, MenuItem
@@ -634,6 +635,8 @@ def create_menus():
name=page.title,
page=page)
yield 'Created footer menu'
+ update_menu(top_menu)
+ update_menu(bottom_menu)
site = Site.objects.get_current()
site_settings = site.settings
site_settings.top_menu = top_menu
@@ -661,6 +664,7 @@ def create_translations():
from saleor.page.models import PageTranslation
from saleor.menu.models import MenuItemTranslation
from saleor.site.models import SiteSettingsTranslation
+ from saleor.discount.models import Voucher, VoucherTranslation
for i, category in enumerate(Category.objects.all()):
CategoryTranslation.objects.create(
@@ -717,3 +721,9 @@ def create_translations():
site_settings=site_set, language_code='pl',
header_text='Tekst nagłówka po polsku %s' % site_set.pk,
description='Opis strony, tez po polsku %s' % site_set.pk)
+ for voucher in Voucher.objects.all():
+ VoucherTranslation.objects.create(
+ voucher=voucher, name='Nazwa vouchera')
+ from ...dashboard.menu.utils import update_menu
+ for menu in Menu.objects.all():
+ update_menu(menu)
diff --git a/saleor/dashboard/category/views.py b/saleor/dashboard/category/views.py
index 36fe3f4a36..e08f12dd45 100644
--- a/saleor/dashboard/category/views.py
+++ b/saleor/dashboard/category/views.py
@@ -9,6 +9,7 @@ from django.utils.translation import pgettext_lazy
from ...core.utils import get_paginator_items
from ...product.models import Category
+from ..menu.utils import get_menus_that_needs_update, update_menus
from ..views import staff_member_required
from .filters import CategoryFilter
from .forms import CategoryForm
@@ -100,7 +101,11 @@ def category_details(request, pk):
def category_delete(request, pk):
category = get_object_or_404(Category, pk=pk)
if request.method == 'POST':
+ descendants = category.get_descendants()
+ menus = get_menus_that_needs_update(categories=descendants)
category.delete()
+ if menus:
+ update_menus(menus)
messages.success(
request,
pgettext_lazy(
diff --git a/saleor/dashboard/collection/views.py b/saleor/dashboard/collection/views.py
index d5e91c44eb..5b37ef8269 100644
--- a/saleor/dashboard/collection/views.py
+++ b/saleor/dashboard/collection/views.py
@@ -10,6 +10,7 @@ from django.views.decorators.http import require_POST
from ...core.utils import get_paginator_items
from ...product.models import Collection
+from ..menu.utils import get_menus_that_needs_update, update_menus
from ..views import staff_member_required
from .filters import CollectionFilter
from .forms import CollectionForm
@@ -65,7 +66,10 @@ def collection_update(request, pk=None):
def collection_delete(request, pk=None):
collection = get_object_or_404(Collection, pk=pk)
if request.method == 'POST':
+ menus = get_menus_that_needs_update(collection=collection)
collection.delete()
+ if menus:
+ update_menus(menus)
msg = pgettext_lazy('Collection message', 'Deleted collection')
messages.success(request, msg)
if request.is_ajax():
diff --git a/saleor/dashboard/menu/forms.py b/saleor/dashboard/menu/forms.py
index 9d1d44b275..35303240c9 100644
--- a/saleor/dashboard/menu/forms.py
+++ b/saleor/dashboard/menu/forms.py
@@ -26,6 +26,9 @@ class MenuForm(forms.ModelForm):
labels = {
'name': pgettext_lazy('Menu name', 'Menu name')}
+ def save(self, commit=True):
+ return super().save(commit)
+
class MenuItemForm(forms.ModelForm):
"""Add or update menu item.
diff --git a/saleor/dashboard/menu/utils.py b/saleor/dashboard/menu/utils.py
index 5204c9c3ac..5c27229846 100644
--- a/saleor/dashboard/menu/utils.py
+++ b/saleor/dashboard/menu/utils.py
@@ -1,3 +1,8 @@
+import json
+
+from django.db.models import Q
+
+from ...menu.models import Menu, MenuItem
from ...page.models import Page
from ...product.models import Category, Collection
@@ -16,3 +21,74 @@ def update_menu_item_linked_object(menu_item, linked_object):
menu_item.page = linked_object
return menu_item.save()
+
+
+def get_menu_item_as_dict(menu_item):
+ data = {}
+ if menu_item.linked_object:
+ data['url'] = menu_item.linked_object.get_absolute_url()
+ else:
+ data['url'] = menu_item.url
+ data['name'] = menu_item.name
+ data['translations'] = {
+ translated.language_code: {'name': translated.name}
+ for translated in menu_item.translations.all()}
+ return data
+
+
+def get_menu_as_json(menu):
+ """Builds Tree-like structure from top menu items,
+ its children and its grandchildren.
+ """
+ top_items = menu.items.filter(
+ parent=None).prefetch_related(
+ 'category', 'page', 'collection',
+ 'children__category', 'children__page', 'children__collection',
+ 'children__children__category', 'children__children__page',
+ 'children__children__collection', 'translations',
+ 'children__translations', 'children__children__translations')
+ menu_data = []
+ for item in top_items:
+ top_item_data = get_menu_item_as_dict(item)
+ top_item_data['child_items'] = []
+ children = item.children.all()
+ for child in children:
+ child_data = get_menu_item_as_dict(child)
+ grand_children = child.children.all()
+ grand_children_data = [
+ get_menu_item_as_dict(grand_child)
+ for grand_child in grand_children]
+ child_data['child_items'] = grand_children_data
+ top_item_data['child_items'].append(child_data)
+ menu_data.append(top_item_data)
+ return json.dumps(menu_data)
+
+
+def update_menus(menus_pk):
+ menus = Menu.objects.filter(pk__in=menus_pk)
+ for menu in menus:
+ update_menu(menu)
+
+
+def update_menu(menu):
+ menu.json_content = get_menu_as_json(menu)
+ menu.save(update_fields=['json_content'])
+
+
+def get_menus_that_needs_update(collection=None, categories=None, page=None):
+ """Returns PrimaryKeys of Menu instances that will be affected by
+ deleting one of the listed objects, therefore needs to be updated
+ afterwards.
+ """
+ if not any([page, collection, categories]):
+ return []
+ q = Q()
+ if collection is not None:
+ q |= Q(collection=collection)
+ if categories is not None:
+ q |= Q(category__in=categories)
+ if page is not None:
+ q |= Q(page=page)
+ menus_to_be_updated = MenuItem.objects.filter(q).distinct().values_list(
+ 'menu', flat=True)
+ return menus_to_be_updated
diff --git a/saleor/dashboard/menu/views.py b/saleor/dashboard/menu/views.py
index 0b16f1e801..a07afa80ac 100644
--- a/saleor/dashboard/menu/views.py
+++ b/saleor/dashboard/menu/views.py
@@ -15,6 +15,7 @@ from ...product.models import Category, Collection
from ..views import staff_member_required
from .filters import MenuFilter, MenuItemFilter
from .forms import AssignMenuForm, MenuForm, MenuItemForm, ReorderMenuItemsForm
+from .utils import update_menu
@staff_member_required
@@ -62,7 +63,7 @@ def menu_edit(request, pk):
menu = get_object_or_404(Menu, pk=pk)
form = MenuForm(request.POST or None, instance=menu)
if form.is_valid():
- menu = form.save()
+ form.save()
msg = pgettext_lazy('Dashboard message', 'Updated menu %s') % (menu,)
messages.success(request, msg)
return redirect('dashboard:menu-details', pk=menu.pk)
@@ -119,6 +120,7 @@ def menu_item_create(request, menu_pk, root_pk=None):
msg = pgettext_lazy(
'Dashboard message', 'Added menu item %s') % (menu_item,)
messages.success(request, msg)
+ update_menu(menu)
if root_pk:
return redirect(
'dashboard:menu-item-details',
@@ -138,6 +140,7 @@ def menu_item_edit(request, menu_pk, item_pk):
form = MenuItemForm(request.POST or None, instance=menu_item)
if form.is_valid():
menu_item = form.save()
+ update_menu(menu)
msg = pgettext_lazy(
'Dashboard message', 'Saved menu item %s') % (menu_item,)
messages.success(request, msg)
@@ -155,6 +158,7 @@ def menu_item_delete(request, menu_pk, item_pk):
menu_item = get_object_or_404(menu.items.all(), pk=item_pk)
if request.method == 'POST':
menu_item.delete()
+ update_menu(menu)
msg = pgettext_lazy(
'Dashboard message', 'Removed menu item %s') % (menu_item,)
messages.success(request, msg)
@@ -207,6 +211,7 @@ def ajax_reorder_menu_items(request, menu_pk, root_pk=None):
ctx = {}
if form.is_valid():
form.save()
+ update_menu(menu)
elif form.errors:
status = 400
ctx = {'error': form.errors}
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 27b4d5e52f..e38ff40bc2 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -241,6 +241,9 @@ class OrderEditVoucherForm(forms.ModelForm):
decrease_voucher_usage(self.old_voucher)
increase_voucher_usage(voucher)
self.instance.discount_name = voucher.name or ''
+ self.instance.translated_discount_name = (
+ voucher.translated.name
+ if voucher.translated.name != voucher.name else '')
recalculate_order(self.instance)
return super().save(commit)
@@ -535,6 +538,7 @@ class OrderRemoveVoucherForm(forms.ModelForm):
decrease_voucher_usage(self.instance.voucher)
self.instance.discount_amount = 0
self.instance.discount_name = ''
+ self.instance.translated_discount_name = ''
self.instance.voucher = None
recalculate_order(self.instance)
diff --git a/saleor/dashboard/page/views.py b/saleor/dashboard/page/views.py
index e2a3e93a45..7a1fba3403 100644
--- a/saleor/dashboard/page/views.py
+++ b/saleor/dashboard/page/views.py
@@ -7,6 +7,7 @@ from django.utils.translation import pgettext_lazy
from ...core.utils import get_paginator_items
from ...page.models import Page
+from ..menu.utils import get_menus_that_needs_update, update_menus
from ..views import staff_member_required
from .filters import PageFilter
from .forms import PageForm
@@ -57,7 +58,10 @@ def _page_edit(request, page):
def page_delete(request, pk):
page = get_object_or_404(Page, pk=pk)
if request.POST:
+ menus = get_menus_that_needs_update(page=page)
page.delete()
+ if menus:
+ update_menus(menus)
msg = pgettext_lazy(
'Dashboard message', 'Removed page %s') % (page.title,)
messages.success(request, msg)
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index abc01f00c2..516c52567f 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -12,6 +12,7 @@ from django_prices.templatetags.prices_i18n import amount
from prices import Money, fixed_discount, percentage_discount
from . import DiscountValueType, VoucherType
+from ..core.utils.translations import TranslationProxy
class NotApplicable(ValueError):
@@ -62,6 +63,7 @@ class Voucher(models.Model):
categories = models.ManyToManyField('product.Category', blank=True)
objects = VoucherQueryset.as_manager()
+ translated = TranslationProxy()
def __str__(self):
if self.name:
@@ -141,6 +143,13 @@ class SaleQueryset(models.QuerySet):
end_date__gte=date, start_date__lte=date)
+class VoucherTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ name = models.CharField(max_length=255, null=True, blank=True)
+ voucher = models.ForeignKey(
+ Voucher, related_name='translations', on_delete=models.CASCADE)
+
+
class Sale(models.Model):
name = models.CharField(max_length=255)
type = models.CharField(
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index 7f5251ac3f..d7696fa713 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -1,5 +1,6 @@
from django.db import models
from django.utils.translation import pgettext_lazy
+from jsonfield import JSONField
from mptt.managers import TreeManager
from mptt.models import MPTTModel
@@ -11,6 +12,7 @@ from ..product.models import Category, Collection
class Menu(models.Model):
name = models.CharField(max_length=128)
+ json_content = JSONField(blank=True, default='')
class Meta:
permissions = ((
diff --git a/saleor/order/models.py b/saleor/order/models.py
index e56ef6362f..a64a593800 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -88,6 +88,8 @@ class Order(models.Model):
currency=settings.DEFAULT_CURRENCY, max_digits=12,
decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)
discount_name = models.CharField(max_length=255, default='', blank=True)
+ translated_discount_name = models.CharField(
+ max_length=255, default='', blank=True)
display_gross_prices = models.BooleanField(default=True)
objects = OrderQueryset.as_manager()
diff --git a/saleor/settings.py b/saleor/settings.py
index 93ea36c9a6..6a6f13e195 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -138,7 +138,6 @@ context_processors = [
'django.template.context_processors.request',
'saleor.core.context_processors.default_currency',
'saleor.checkout.context_processors.cart_counter',
- 'saleor.core.context_processors.navigation',
'saleor.core.context_processors.search_enabled',
'saleor.site.context_processors.site',
'social_django.context_processors.backends',
diff --git a/templates/base.html b/templates/base.html
index 442c099f54..9eb28938f8 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -1,9 +1,9 @@
<!DOCTYPE html>
{% load i18n %}
-{% load staticfiles %}
-{% load render_bundle from webpack_loader %}
-{% load shop %}
+{% load menu from shop %}
{% load placeholder %}
+{% load render_bundle from webpack_loader %}
+{% load staticfiles %}
{% load translate_url from urls %}
<html lang="{{ LANGUAGE_CODE }}" class="no-js" data-shipping-options-url="{% url 'cart:shipping-options' %}" data-cart-summary-url="{% url 'cart:summary' %}">
diff --git a/templates/checkout/snippets/voucher_form.html b/templates/checkout/snippets/voucher_form.html
index 5bbf90b69e..6635f91f66 100644
--- a/templates/checkout/snippets/voucher_form.html
+++ b/templates/checkout/snippets/voucher_form.html
@@ -8,7 +8,7 @@
method="post"
class="float-left input-btn">
{% csrf_token %}
- <span>{{ cart.discount_name }}</span>
+ <span>{{ cart.translated_discount_name|default:cart.discount_name }}</span>
<button type="submit"
class="btn btn-link btn-voucher-remove"
aria-label="{% trans "Remove" context "Checkout voucher form action" %}">
diff --git a/templates/dashboard/order/pdf/invoice.html b/templates/dashboard/order/pdf/invoice.html
index df12d07214..1f483c24b4 100644
--- a/templates/dashboard/order/pdf/invoice.html
+++ b/templates/dashboard/order/pdf/invoice.html
@@ -135,7 +135,7 @@
{% if order.discount_amount %}
<tr>
<td>
- {% trans "Discount" context "Order voucher header" %} {% if order.discount_name %}({{ order.discount_name }}){% endif %}
+ {% trans "Discount" context "Order voucher header" %} {% if order.discount_name %}({{ order.translated_discount_name|default:order.discount_name }}){% endif %}
</td>
<td class="right-align">
{% discount_as_negative order.discount_amount html=True %}
diff --git a/templates/menu.html b/templates/menu.html
index d4d07bcff3..bc417c2748 100644
--- a/templates/menu.html
+++ b/templates/menu.html
@@ -1,42 +1,44 @@
{% url 'home' as home_url %}
+{% load i18n %}
+{% get_current_language as LANGUAGE_CODE %}
+{% load get_menu_item_name from shop %}
+
<ul class="menu {% if horizontal %}nav mb-4 mb-md-0{% endif %}{% if request.get_full_path == home_url %} no-border{% endif %}">
{% for item in menu_items %}
- {% with children=item.get_children %}
+ {% with children=item.child_items %}
<li class="{% if horizontal %}nav-item{% endif %} {% if children %}nav-item__dropdown{% endif %} menu__item">
- <a class="{% if horizontal %}nav-link{% endif %}" href="{{ item.get_url }}">
- {{ item.translated }}
- </a>
+ <a class="{% if horizontal %}nav-link{% endif %}" href="{{ item.url }}">{% get_menu_item_name lang_code=LANGUAGE_CODE menu_item=item %}</a>
{% if children %}
- <div class="{% if horizontal %}nav-item__dropdown-content{% else %}nav-item__submenu{% endif %}">
- <div class="container">
- <ul>
- {% for child in children %}
- <li>
- <a href="{{ child.get_url }}">
- {% if horizontal %}
- <strong>{{ child.translated }}</strong>
- {% else %}
- {{ child.translated }}
- {% endif %}
- </a>
- </li>
- {% with grandchildren=child.get_children %}
- {% if grandchildren %}
- <ul>
- {% for grandchild in grandchildren %}
- <li>
- <a href="{{ grandchild.get_url }}">
- {{ grandchild.translated }}
- </a>
- </li>
- {% endfor %}
- </ul>
+ <div class="{% if horizontal %}nav-item__dropdown-content{% else %}nav-item__submenu{% endif %}">
+ <div class="container">
+ <ul>
+ {% for child in children %}
+ <li>
+ <a href="{{ child.url }}">
+ {% if horizontal %}
+ <strong>{% get_menu_item_name lang_code=LANGUAGE_CODE menu_item=child %}</strong>
+ {% else %}
+ {% get_menu_item_name lang_code=LANGUAGE_CODE menu_item=child %}
{% endif %}
- {% endwith %}
- {% endfor %}
- </ul>
- </div>
+ </a>
+ </li>
+ {% with grandchildren=child.child_items %}
+ {% if grandchildren %}
+ <ul>
+ {% for grandchild in grandchildren %}
+ <li>
+ <a href="{{ grandchild.url }}">
+ {% get_menu_item_name lang_code=LANGUAGE_CODE menu_item=grandchild %}
+ </a>
+ </li>
+ {% endfor %}
+ </ul>
+ {% endif %}
+ {% endwith %}
+ {% endfor %}
+ </ul>
</div>
+ </div>
{% endif %}
</li>
{% endwith %}
diff --git a/templates/order/_ordered_items_table.html b/templates/order/_ordered_items_table.html
index c53aff1eaa..e54476bdd4 100644
--- a/templates/order/_ordered_items_table.html
+++ b/templates/order/_ordered_items_table.html
@@ -110,7 +110,7 @@
<div class="table__row">
<div class="row">
<div class="col-8 order-details__table-footer">
- <p>{{ order.discount_name }}</p>
+ <p>{{ order.translated_discount_name|default:order.discount_name }}</p>
</div>
<div class="col-4">
<p class="float-right">
diff --git a/tests/conftest.py b/tests/conftest.py
index ac489cb6e9..dbf6e57878 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,7 +3,6 @@ from io import BytesIO
from unittest.mock import MagicMock, Mock
import pytest
-
from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.files import File
@@ -17,19 +16,21 @@ from graphql_jwt.shortcuts import get_token
from payments import FraudStatus, PaymentStatus
from PIL import Image
from prices import Money
+
from saleor.account.models import Address, User
from saleor.checkout import utils
from saleor.checkout.models import Cart
from saleor.checkout.utils import add_variant_to_cart
+from saleor.dashboard.menu.utils import update_menu
from saleor.dashboard.order.utils import fulfill_order_line
-from saleor.discount.models import Sale, Voucher
+from saleor.discount.models import Sale, Voucher, VoucherTranslation
from saleor.menu.models import Menu, MenuItem
from saleor.order import OrderStatus
from saleor.order.models import Order
from saleor.order.utils import recalculate_order
from saleor.page.models import Page
from saleor.product.models import (
- AttributeChoiceValue, AttributeChoiceValueTranslation, Category,
+ AttributeChoiceValue, Category,
Collection, Product, ProductAttribute, ProductAttributeTranslation,
ProductImage, ProductType, ProductVariant)
from saleor.shipping.models import ShippingMethod, ShippingMethodCountry
@@ -626,7 +627,7 @@ def model_form_class():
@pytest.fixture
def menu(db):
# navbar menu object can be already created by default in migration
- return Menu.objects.get_or_create(name='navbar')[0]
+ return Menu.objects.get_or_create(name='navbar', json_content={})[0]
@pytest.fixture
@@ -646,6 +647,7 @@ def menu_with_items(menu, default_category, collection):
parent=menu_item)
menu.items.create(
name=collection.name, collection=collection, parent=menu_item)
+ update_menu(menu)
return menu
@@ -717,8 +719,6 @@ def translated_product_attribute(product):
@pytest.fixture
-def attribute_choice_translation_fr(translated_product_attribute):
- value = translated_product_attribute.product_attribute.values.first()
- return AttributeChoiceValueTranslation.objects.create(
- language_code='fr', attribute_choice_value=value,
- name='French name')
+def voucher_translation_fr(voucher):
+ return VoucherTranslation.objects.create(
+ language_code='fr', voucher=voucher, name='French name')
diff --git a/tests/dashboard/test_category.py b/tests/dashboard/test_category.py
index 11d94f8046..e860ba31b5 100644
--- a/tests/dashboard/test_category.py
+++ b/tests/dashboard/test_category.py
@@ -1,5 +1,6 @@
-from django.urls import reverse
+from unittest.mock import patch
+from django.urls import reverse
from saleor.product.models import Category
@@ -60,10 +61,29 @@ def test_category_details(admin_client, default_category):
assert response.status_code == 200
-def test_category_delete(admin_client, default_category):
+@patch('saleor.dashboard.category.views.get_menus_that_needs_update')
+@patch('saleor.dashboard.category.views.update_menus')
+def test_category_delete(
+ mock_update_menus, mock_get_menus, admin_client, default_category):
assert Category.objects.count() == 1
+ mock_get_menus.return_value = [1]
url = reverse('dashboard:category-delete',
kwargs={'pk': default_category.pk})
response = admin_client.post(url, follow=True)
+ assert mock_update_menus.called
+
assert response.status_code == 200
assert Category.objects.count() == 0
+
+
+@patch('saleor.dashboard.category.views.get_menus_that_needs_update')
+@patch('saleor.dashboard.category.views.update_menus')
+def test_category_delete_menus_not_updated(
+ mock_update_menus, mock_get_menus, admin_client, default_category):
+ url = reverse('dashboard:category-delete',
+ kwargs={'pk': default_category.pk})
+ mock_get_menus.return_value = []
+ response = admin_client.post(url, follow=True)
+ assert response.status_code == 200
+ assert mock_get_menus.called
+ assert not mock_update_menus.called
diff --git a/tests/dashboard/test_collection.py b/tests/dashboard/test_collection.py
index 7a2491212b..b08f6338e3 100644
--- a/tests/dashboard/test_collection.py
+++ b/tests/dashboard/test_collection.py
@@ -1,7 +1,7 @@
import json
-import pytest
-from django.urls import reverse
+from unittest import mock
+from django.urls import reverse
from saleor.dashboard.collection.forms import CollectionForm
from saleor.product.models import Collection
@@ -63,7 +63,10 @@ def test_collection_update_view(admin_client, collection, product):
assert list(collection.products.all()) == [product]
-def test_collection_delete_view(admin_client, collection):
[email protected]('saleor.dashboard.collection.views.get_menus_that_needs_update')
[email protected]('saleor.dashboard.collection.views.update_menus')
+def test_collection_delete_view(
+ mock_update_menus, mock_get_menus, admin_client, collection):
# Test Http404 when collection doesn't exist
url404 = reverse('dashboard:collection-delete', kwargs={'pk': 123123})
response404 = admin_client.post(url404)
@@ -72,11 +75,26 @@ def test_collection_delete_view(admin_client, collection):
# Test deleting object
collections_count = Collection.objects.count()
url = reverse('dashboard:collection-delete', kwargs={'pk': collection.id})
+ mock_get_menus.return_value = [collection.id]
response = admin_client.post(url)
assert response.status_code == 302
+ mock_update_menus.assert_called_once_with([collection.pk])
+
assert Collection.objects.count() == (collections_count - 1)
[email protected]('saleor.dashboard.collection.views.get_menus_that_needs_update')
[email protected]('saleor.dashboard.collection.views.update_menus')
+def test_collection_delete_view_menus_not_updated(
+ mock_update_menus, mock_get_menus, admin_client, collection):
+ url = reverse('dashboard:collection-delete', kwargs={'pk': collection.id})
+ mock_get_menus.return_value = []
+ response = admin_client.post(url)
+ assert response.status_code == 302
+ assert mock_get_menus.called
+ assert not mock_update_menus.called
+
+
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)
diff --git a/tests/dashboard/test_menu.py b/tests/dashboard/test_menu.py
index abc3cde7cd..141f2515d8 100644
--- a/tests/dashboard/test_menu.py
+++ b/tests/dashboard/test_menu.py
@@ -1,11 +1,13 @@
import json
-
+from unittest import mock
import pytest
from django.urls import reverse
from saleor.dashboard.menu.forms import AssignMenuForm
-from saleor.dashboard.menu.utils import update_menu_item_linked_object
-from saleor.menu.models import Menu, MenuItem
+from saleor.dashboard.menu.utils import (
+ get_menu_as_json, get_menu_item_as_dict, get_menus_that_needs_update,
+ update_menu, update_menu_item_linked_object, update_menus)
+from saleor.menu.models import Menu, MenuItem, MenuItemTranslation
from ..utils import get_redirect_location
@@ -289,3 +291,76 @@ def test_update_menu_item_linked_object(menu, default_category, page):
assert menu_item.get_url() == page.get_absolute_url()
assert not menu_item.category
assert not menu_item.collection
+
+
+def test_get_menu_item_as_dict(menu):
+ item = MenuItem.objects.create(
+ name='Name', menu=menu, url='http://url.com')
+ result = get_menu_item_as_dict(item)
+ assert result == {
+ 'name': 'Name', 'url': 'http://url.com', 'translations': {}}
+
+
+def test_get_menu_item_as_dict_with_translations(menu, collection):
+ item = MenuItem.objects.create(
+ name='Name', menu=menu, collection=collection)
+ MenuItemTranslation.objects.create(
+ menu_item=item, name='Polish Name', language_code='pl')
+ result = get_menu_item_as_dict(item)
+ assert result == {
+ 'name': 'Name', 'url': collection.get_absolute_url(),
+ 'translations': {'pl': {'name': 'Polish Name'}}}
+
+
+def test_get_menu_as_json(menu):
+ top_item = MenuItem.objects.create(
+ menu=menu, name='top item', url='http://topitem.pl')
+ child_item = MenuItem.objects.create(
+ menu=menu, parent=top_item, name='child item',
+ url='http://childitem.pl')
+ grand_child_item = MenuItem.objects.create(
+ menu=menu, parent=child_item, name='grand child item',
+ url='http://grandchilditem.pl')
+ top_item_data = get_menu_item_as_dict(top_item)
+ child_item_data = get_menu_item_as_dict(child_item)
+ grand_child_data = get_menu_item_as_dict(grand_child_item)
+
+ child_item_data['child_items'] = [grand_child_data]
+ top_item_data['child_items'] = [child_item_data]
+ proper_data = [top_item_data]
+ proper_data = json.dumps(proper_data)
+ assert proper_data == get_menu_as_json(menu)
+
+
[email protected]('saleor.dashboard.menu.utils.update_menu')
+def test_update_menus(mock_update_menu, menu):
+ update_menus([menu.pk])
+ mock_update_menu.assert_called_once_with(menu)
+
+
[email protected]('saleor.dashboard.menu.utils.get_menu_as_json')
+def test_update_menu(mock_json_menu, menu):
+ mock_json_menu.return_value = 'Return value'
+ update_menu(menu)
+
+ mock_json_menu.assert_called_once_with(menu)
+ menu.refresh_from_db()
+ assert menu.json_content == 'Return value'
+
+
+def test_get_menus_that_needs_update(default_category, collection, page):
+ assert not get_menus_that_needs_update()
+
+ menus = Menu.objects.bulk_create([
+ Menu(name='category'),
+ Menu(name='collection'),
+ Menu(name='page')])
+
+ MenuItem.objects.create(
+ name='item', menu=menus[0], category=default_category),
+ MenuItem.objects.create(name='item', menu=menus[1], collection=collection),
+ MenuItem.objects.create(name='item', menu=menus[2], page=page)
+
+ result = get_menus_that_needs_update(
+ categories=[default_category], collection=collection, page=page)
+ assert sorted(list(result)) == sorted([m.pk for m in menus])
diff --git a/tests/dashboard/test_page.py b/tests/dashboard/test_page.py
index 01473115b7..60bbeb8732 100644
--- a/tests/dashboard/test_page.py
+++ b/tests/dashboard/test_page.py
@@ -1,7 +1,8 @@
-from django.urls import reverse
+from unittest import mock
-from saleor.dashboard.page.forms import PageForm
from django.forms.models import model_to_dict
+from django.urls import reverse
+from saleor.dashboard.page.forms import PageForm
def test_page_list(admin_client):
@@ -42,14 +43,31 @@ def test_page_add(admin_client):
assert response.status_code == 302
-def test_page_delete(admin_client, page):
[email protected]('saleor.dashboard.page.views.get_menus_that_needs_update')
[email protected]('saleor.dashboard.page.views.update_menus')
+def test_page_delete(mock_update_menus, mock_get_menus, admin_client, page):
url = reverse('dashboard:page-delete', args=[page.pk])
response = admin_client.get(url)
assert response.status_code == 200
+ mock_get_menus.return_value = [page.pk]
+ response = admin_client.post(url, data={'a': 'b'})
+ assert response.status_code == 302
+ assert mock_get_menus.called
+ mock_update_menus.assert_called_once_with([page.pk])
+
+
[email protected]('saleor.dashboard.page.views.get_menus_that_needs_update')
[email protected]('saleor.dashboard.page.views.update_menus')
+def test_page_delete_menu_not_updated(
+ mock_update_menus, mock_get_menus, admin_client, page):
+ url = reverse('dashboard:page-delete', args=[page.pk])
+ mock_get_menus.return_value = []
response = admin_client.post(url, data={'a': 'b'})
assert response.status_code == 302
+ assert mock_get_menus.called
+ assert not mock_update_menus.called
def test_sanitize_page_content(page, default_category):
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index eee1848405..f1ea095347 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -739,21 +739,24 @@ def test_get_voucher_for_cart_no_voucher_code(cart):
assert cart_voucher is None
-def test_remove_voucher_from_cart(cart_with_voucher):
+def test_remove_voucher_from_cart(cart_with_voucher, voucher_translation_fr):
cart = cart_with_voucher
remove_voucher_from_cart(cart)
assert not cart.voucher_code
assert not cart.discount_name
+ assert not cart.translated_discount_name
assert cart.discount_amount == ZERO_MONEY
-def test_recalculate_cart_discount(cart_with_voucher, voucher):
+def test_recalculate_cart_discount(
+ cart_with_voucher, voucher, voucher_translation_fr, settings):
+ settings.LANGUAGE_CODE = 'fr'
voucher.discount_value = 10
voucher.save()
recalculate_cart_discount(cart_with_voucher, None, None)
-
+ assert cart_with_voucher.translated_discount_name == voucher_translation_fr.name # noqa
assert cart_with_voucher.discount_amount == Money('10.00', 'USD')
diff --git a/tests/test_product.py b/tests/test_product.py
index 03d378153c..ca948ce01e 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -19,6 +19,8 @@ from saleor.product.utils import (
from saleor.product.utils.attributes import get_product_attributes_data
from saleor.product.utils.availability import get_product_availability_status
from saleor.product.utils.variants_picker import get_variant_picker_data
+from saleor.menu.models import MenuItemTranslation
+from saleor.dashboard.menu.utils import update_menu
from .utils import filter_products_by_attribute
@@ -103,11 +105,33 @@ def test_filtering_by_attribute(db, color_attribute, default_category):
assert product_b not in list(filtered)
-def test_render_home_page(client, product):
+def test_render_home_page(client, product, site_settings, settings):
+ # Tests if menu renders properly if none is assigned
+ settings.LANGUAGE_CODE = 'fr'
+ site_settings.top_menu = None
+ site_settings.save()
+
response = client.get(reverse('home'))
assert response.status_code == 200
+def test_render_home_page_with_translated_menu_items(
+ client, product, menu_with_items, site_settings, settings):
+ settings.LANGUAGE_CODE = 'fr'
+ site_settings.top_menu = menu_with_items
+ site_settings.save()
+
+ for item in menu_with_items.items.all():
+ MenuItemTranslation.objects.create(
+ menu_item=item, language_code='fr',
+ name='Translated name in French')
+ update_menu(menu_with_items)
+
+ response = client.get(reverse('home'))
+ assert response.status_code == 200
+ assert 'Translated name in French' in str(response.content)
+
+
def test_render_home_page_with_sale(client, product, sale):
response = client.get(reverse('home'))
assert response.status_code == 200
@@ -623,13 +647,3 @@ def test_get_product_attributes_data_translation(
attributes_data = get_product_attributes_data(product)
attributes_keys = [attr.name for attr in attributes_data.keys()]
assert translated_product_attribute.name in attributes_keys
-
-
-def test_attribute_choice_value_translation_fr(
- settings, product, attribute_choice_translation_fr):
- attribute = product.product_type.product_attributes.first()
- choice = attribute.values.first()
- assert choice.translated.name == 'Red'
-
- settings.LANGUAGE_CODE = 'fr'
- assert choice.translated.name == 'French name'
diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py
index 1837389d41..e791d9c11e 100644
--- a/tests/test_templatetags.py
+++ b/tests/test_templatetags.py
@@ -1,5 +1,6 @@
-from django.urls import reverse
+import json
+from django.urls import reverse
from saleor.core.templatetags.shop import get_sort_by_url, menu
@@ -23,7 +24,9 @@ def test_sort_by_url_descending(admin_client, default_category):
assert result == expected
-def test_menu(client, menu_with_items):
- response = client.get(reverse('home'))
- result = menu(response.context, menu_with_items)
- assert all((i for i in result['menu_items'] if i.parent_id is None))
+def test_menu(menu_with_items):
+ result = menu()
+ assert result == {'horizontal': False, 'menu_items': []}
+
+ result = menu(menu_with_items)
+ assert result['menu_items'] == json.loads(menu_with_items.json_content)
diff --git a/tests/test_translation.py b/tests/test_translation.py
index 6e86b081ee..633ac7f8f2 100644
--- a/tests/test_translation.py
+++ b/tests/test_translation.py
@@ -1,24 +1,34 @@
import pytest
+from saleor.discount.models import VoucherTranslation
from saleor.product.models import (
- CategoryTranslation, CollectionTranslation, ProductTranslation,
- ProductVariantTranslation, ProductAttributeTranslation)
+ AttributeChoiceValueTranslation, CategoryTranslation,
+ CollectionTranslation, ProductAttributeTranslation, ProductTranslation,
+ ProductVariantTranslation)
@pytest.fixture
-def product_translation_fr(db, product):
+def product_translation_fr(product):
return ProductTranslation.objects.create(
language_code='fr', product=product, name='French name',
description='French description')
@pytest.fixture
-def product_translation_pl(db, product):
+def product_translation_pl(product):
return ProductTranslation.objects.create(
language_code='pl', product=product, name='Polish name',
description="Polish description")
+def attribute_choice_translation_fr(translated_product_attribute):
+ value = translated_product_attribute.product_attribute.values.first()
+ return AttributeChoiceValueTranslation.objects.create(
+ language_code='fr', attribute_choice_value=value,
+ name='French name')
+
+
def test_translation(product, settings, product_translation_fr):
assert product.translated.name == 'Test product'
assert not product.translated.description
@@ -103,3 +113,9 @@ def test_attribute_choice_value_translation(
assert not attribute.translated.name == 'French name'
settings.LANGUAGE_CODE = 'fr'
assert attribute.translated.name == 'French name'
+
+
+def test_voucher_translation(settings, voucher, voucher_translation_fr):
+ assert not voucher.translated.name == 'French name'
+ settings.LANGUAGE_CODE = 'fr'
+ assert voucher.translated.name == 'French name'