Skip to content

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

Add vouchers dashboard panel

Michał Ociepka7676fb6a2eed
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index 5da064af76..429b442ea8 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -1,15 +1,17 @@
from django import forms
+from django.conf import settings
from django.utils.translation import pgettext_lazy
+from django_prices.forms import PriceField
-from ...discount.models import Sale
+from ...discount.models import Sale, Voucher
+from ...shipping.models import ShippingMethodCountry
class SaleForm(forms.ModelForm):
+
class Meta:
model = Sale
exclude = []
- widgets = {
- 'type': forms.RadioSelect()}
def clean(self):
cleaned_data = super(SaleForm, self).clean()
@@ -20,3 +22,111 @@ class SaleForm(forms.ModelForm):
'sale error',
'Sale cannot exceed 100%'))
return cleaned_data
+
+
+class VoucherForm(forms.ModelForm):
+
+ ALL_BASKETS = 'all_baskets'
+ DISCOUNT_TYPES = (
+ (ALL_BASKETS, 'All baskets'),
+ ) + Voucher.TYPE_CHOICES
+ type = forms.ChoiceField(
+ choices=DISCOUNT_TYPES, initial=ALL_BASKETS,
+ label=pgettext_lazy('voucher_form', 'Discount for'))
+
+ class Meta:
+ model = Voucher
+ exclude = ['limit', 'apply_to', 'product', 'category']
+
+ def __init__(self, *args, **kwargs):
+ initial = kwargs.get('initial', {})
+ instance = kwargs.get('instance')
+ if instance and instance.type == Voucher.BASKET_TYPE and instance.limit is None:
+ initial['type'] = VoucherForm.ALL_BASKETS
+ kwargs['initial'] = initial
+ super(VoucherForm, self).__init__(*args, **kwargs)
+
+ def clean(self):
+ cleaned_data = super(VoucherForm, self).clean()
+ if cleaned_data['type'] == VoucherForm.ALL_BASKETS:
+ cleaned_data['type'] = Voucher.BASKET_TYPE
+ return cleaned_data
+
+
+class CountriesField(forms.ChoiceField):
+
+ def __init__(self, *args, **kwargs):
+ country_codes = ShippingMethodCountry.objects.all()
+ country_codes = country_codes.values_list('country_code', flat=True)
+ country_codes = country_codes.distinct()
+ country_dict = dict(ShippingMethodCountry.COUNTRY_CODE_CHOICES)
+ kwargs['choices'] = [
+ (country_code, country_dict[country_code]) for country_code in country_codes]
+ super(CountriesField, self).__init__(*args, **kwargs)
+
+
+class ShippingVoucherForm(forms.ModelForm):
+
+ limit = PriceField(
+ min_value=0, required=False, currency=settings.DEFAULT_CURRENCY,
+ label=pgettext_lazy('voucher_form', 'Shipping cost equal or less than'),
+ help_text=pgettext_lazy('voucher_form', 'Any shipping if empty'))
+ apply_to = CountriesField(label='Country')
+
+ class Meta:
+ model = Voucher
+ fields = ['apply_to', 'limit']
+
+ def save(self, commit=True):
+ self.instance.category = None
+ self.instance.product = None
+ return super(ShippingVoucherForm, self).save(commit)
+
+
+class BasketVoucherForm(forms.ModelForm):
+
+ limit = PriceField(
+ min_value=0, required=True, currency = settings.DEFAULT_CURRENCY,
+ label=pgettext_lazy('voucher_form', 'Basket total equals or greater than'))
+
+ class Meta:
+ model = Voucher
+ fields = ['limit']
+
+ def save(self, commit=True):
+ self.instance.category = None
+ self.instance.limit = None
+ self.instance.product = None
+ return super(BasketVoucherForm, self).save(commit)
+
+
+class ProductVoucherForm(forms.ModelForm):
+
+ APPLY_TO_PRODUCT_CHOICES = (
+ (Voucher.APPLY_TO_ONE_PRODUCT,
+ pgettext_lazy('voucher_form', 'Apply only once')),
+ (Voucher.APPLY_TO_ALL_PRODUCTS,
+ pgettext_lazy('voucher_form', 'Apply to all matching products')))
+
+ apply_to = forms.ChoiceField(choices=APPLY_TO_PRODUCT_CHOICES, required=False)
+
+ class Meta:
+ model = Voucher
+ fields = ['product', 'apply_to']
+
+ def save(self, commit=True):
+ self.instance.category = None
+ self.instance.limit = None
+ return super(ProductVoucherForm, self).save(commit)
+
+
+class CategoryVoucherForm(ProductVoucherForm):
+
+ class Meta:
+ model = Voucher
+ fields = ['category', 'apply_to']
+
+ def save(self, commit=True):
+ self.instance.limit = None
+ self.instance.product = None
+ return super(CategoryVoucherForm, self).save(commit)
diff --git a/saleor/dashboard/discount/urls.py b/saleor/dashboard/discount/urls.py
index 82d519d6c7..10eb61b556 100644
--- a/saleor/dashboard/discount/urls.py
+++ b/saleor/dashboard/discount/urls.py
@@ -3,8 +3,13 @@ from django.conf.urls import url
from . import views
urlpatterns = [
- url(r'^$', views.sale_list, name='sale-list'),
- url(r'(?P<pk>[0-9]+)/$', views.sale_edit, name='sale-update'),
- url(r'add/$', views.sale_edit, name='sale-add'),
- url(r'(?P<pk>[0-9]+)/delete/$', views.sale_delete, name='sale-delete'),
+ url(r'sale/$', views.sale_list, name='sale-list'),
+ url(r'sale/(?P<pk>[0-9]+)/$', views.sale_edit, name='sale-update'),
+ url(r'sale/add/$', views.sale_edit, name='sale-add'),
+ url(r'sale/(?P<pk>[0-9]+)/delete/$', views.sale_delete, name='sale-delete'),
+
+ url(r'voucher/$', views.voucher_list, name='voucher-list'),
+ url(r'voucher/(?P<pk>[0-9]+)/$', views.voucher_edit, name='voucher-update'),
+ url(r'voucher/add/$', views.voucher_edit, name='voucher-add'),
+ url(r'voucher/(?P<pk>[0-9]+)/delete/$', views.voucher_delete, name='voucher-delete'),
]
diff --git a/saleor/dashboard/discount/views.py b/saleor/dashboard/discount/views.py
index 1e4362772c..3db73c01aa 100644
--- a/saleor/dashboard/discount/views.py
+++ b/saleor/dashboard/discount/views.py
@@ -1,9 +1,10 @@
+from django.conf import settings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _
-from ...discount.models import Sale
+from ...discount.models import Sale, Voucher
from . import forms
@@ -42,3 +43,55 @@ def sale_delete(request, pk):
ctx = {'sale': instance}
return TemplateResponse(
request, 'dashboard/discount/sale_modal_confirm_delete.html', ctx)
+
+
+@staff_member_required
+def voucher_list(request):
+ vouchers = Voucher.objects.select_related('product', 'category')
+ ctx = {'vouchers': vouchers}
+ return TemplateResponse(request, 'dashboard/discount/voucher_list.html', ctx)
+
+
+@staff_member_required
+def voucher_edit(request, pk=None):
+ instance = get_object_or_404(Voucher, pk=pk) if pk is not None else Voucher()
+ voucher_form = forms.VoucherForm(request.POST or None, instance=instance)
+ type_base_forms = {
+ Voucher.SHIPPING_TYPE: forms.ShippingVoucherForm(
+ request.POST or None, instance=instance, prefix=Voucher.SHIPPING_TYPE),
+ Voucher.BASKET_TYPE: forms.BasketVoucherForm(
+ request.POST or None, instance=instance, prefix=Voucher.BASKET_TYPE),
+ Voucher.PRODUCT_TYPE: forms.ProductVoucherForm(
+ request.POST or None, instance=instance, prefix=Voucher.PRODUCT_TYPE),
+ Voucher.CATEGORY_TYPE: forms.CategoryVoucherForm(
+ request.POST or None, instance=instance, prefix=Voucher.CATEGORY_TYPE),
+ }
+ if voucher_form.is_valid():
+ voucher_type = voucher_form.cleaned_data['type']
+ form_type = type_base_forms.get(voucher_type)
+ if form_type is None:
+ instance = voucher_form.save()
+ elif form_type.is_valid():
+ instance = form_type.save()
+
+ if form_type is None or form_type.is_valid():
+ msg = _('Updated voucher') if pk else _('Added voucher')
+ messages.success(request, msg)
+ return redirect('dashboard:voucher-update', pk=instance.pk)
+ ctx = {
+ 'voucher': instance, 'default_currency': settings.DEFAULT_CURRENCY,
+ 'form': voucher_form, 'type_base_forms': type_base_forms}
+ return TemplateResponse(request, 'dashboard/discount/voucher_form.html', ctx)
+
+
+@staff_member_required
+def voucher_delete(request, pk):
+ instance = get_object_or_404(Voucher, pk=pk)
+ if request.method == 'POST':
+ instance.delete()
+ messages.success(
+ request, _('Deleted voucher %s') % (instance,))
+ return redirect('dashboard:voucher-list')
+ ctx = {'voucher': instance}
+ return TemplateResponse(
+ request, 'dashboard/discount/voucher_modal_confirm_delete.html', ctx)
diff --git a/saleor/dashboard/templates/dashboard/base.html b/saleor/dashboard/templates/dashboard/base.html
index 67e77dd760..5a8b7299f1 100644
--- a/saleor/dashboard/templates/dashboard/base.html
+++ b/saleor/dashboard/templates/dashboard/base.html
@@ -74,7 +74,7 @@
<div class="collapsible-body">
<ul>
<li class="subnav-sales"><a href="{% url 'dashboard:sale-list' %}">{% trans "Sales" %}</a></li>
- <li class="subnav-cupons"><a href="{% url 'dashboard:sale-list' %}">{% trans "Cupons" %}</a></li>
+ <li class="subnav-vouchers"><a href="{% url 'dashboard:voucher-list' %}">{% trans "Vouchers" %}</a></li>
</ul>
</div>
</li>
diff --git a/saleor/dashboard/templates/dashboard/discount/voucher_form.html b/saleor/dashboard/templates/dashboard/discount/voucher_form.html
new file mode 100644
index 0000000000..378def9fc3
--- /dev/null
+++ b/saleor/dashboard/templates/dashboard/discount/voucher_form.html
@@ -0,0 +1,91 @@
+{% extends "dashboard/base.html" %}
+{% load i18n %}
+{% load materializecss %}
+{% load static %}
+
+{% block title %}{% if voucher.pk %}{{ voucher }}{% else %}{% trans 'Add new voucher' %}
+{% endif %} - {% trans "Vouchers" %} - {{ block.super }}{% endblock %}
+
+{% block body_class %}body-vouchers{% endblock %}
+
+{% block header_menu %}
+ {% url "dashboard:voucher-list" as url %}
+ {% include "dashboard/includes/_back-link.html" with url=url %}
+{% endblock %}
+
+{% block header_extra %}
+ {% if voucher.pk %}
+ <a class="dropdown-button" href="#" data-activates="voucher-delete"
+ data-constrainwidth="false">
+ <i class="mdi-navigation-more-vert"></i>
+ </a>
+ <ul id="voucher-delete" class="dropdown-content">
+ <li>
+ <a class="modal-trigger-custom" href="#base-modal"
+ data-href="{% url 'dashboard:voucher-delete' pk=voucher.pk %}">
+ {% trans "Remove voucher" %}
+ </a>
+ </li>
+ </ul>
+ {% endif %}
+{% endblock %}
+
+{% block breadcrumbs %}
+ <ul class="breadcrumbs breadcrumbs--with-menu">
+ <li><a href="{% url 'dashboard:voucher-list' %}"
+ class="breadcrumbs--ellipsed-item">{% trans "Vouchers" %}</a></li>
+ <li><span class="breadcrumbs--ellipsed-item">{% if voucher.pk %}
+ {{ voucher }}{% else %}{% trans 'Add new voucher' %}{% endif %}</span></li>
+ </ul>
+{% endblock %}
+
+{% block menu_discounts_class %} active{% endblock %}
+
+{% block content %}
+ <form method="post" enctype="multipart/form-data" id="form-vouchers">
+ {% csrf_token %}
+ {% if form.non_field_errors %}
+ <blockquote>
+ {% for non_field_error in form.non_field_errors %}
+ {{ non_field_error }}
+ {% endfor %}
+ </blockquote>
+ {% endif %}
+ <div class="row">
+ <div class="col s12 l8">
+ <div class="row">
+ {{ form.code|materializecss }}
+ {{ form.usage_limit|materializecss }}
+ {{ form.name|materializecss }}
+ {{ form.discount_value|materializecss:"s12 m8" }}
+ {{ form.discount_value_type|materializecss:"s12 m4" }}
+ {{ form.type|materializecss }}
+ </div>
+ {% for form_type, form in type_base_forms.items %}
+ <div class="row voucher-form" data-type="{{ form_type }}">
+ {% for field in form %}
+ {{ field|materializecss:"s12 m6" }}
+ {% endfor %}
+ </div>
+ {% endfor %}
+ </div>
+
+ <div class="col s12 l4">
+ <div class="row">
+ {{ form.start_date|materializecss:"input-field s12" }}
+ {{ form.end_date|materializecss:"input-field s12" }}
+ </div>
+ </div>
+ </div>
+
+ <div class="row">
+ <div class="col l8 right-align">
+ {% if voucher.pk %}
+ <button type="submit" class="btn">{% trans "Update" %}</button>
+ {% else %}
+ <button type="submit" class="btn">{% trans "Create" %}</button>
+ {% endif %}
+ </div>
+ </div>
+ </form>
+{% endblock %}
diff --git a/saleor/dashboard/templates/dashboard/discount/voucher_list.html b/saleor/dashboard/templates/dashboard/discount/voucher_list.html
new file mode 100644
index 0000000000..93b4e549fc
--- /dev/null
+++ b/saleor/dashboard/templates/dashboard/discount/voucher_list.html
@@ -0,0 +1,64 @@
+{% extends "dashboard/base.html" %}
+{% load i18n %}
+{% load prices_i18n %}
+{% load materializecss %}
+
+{% block title %}{% trans "Vouchers" %} - {{ block.super }}{% endblock %}
+
+{% block body_class %}body-vouchers{% endblock %}
+
+{% block header_extra %}
+ <div class="fixed-action-btn">
+ <a class="btn-fab btn-floating btn-large waves-effect waves-light teal"
+ href="{% url 'dashboard:voucher-add' %}" title="{% trans "Add voucher" %}">
+ <i class="mdi-content-add"></i>
+ </a>
+ </div>
+{% endblock %}
+
+{% block breadcrumbs %}
+ <ul class="breadcrumbs">
+ <li>{% trans "Vouchers" %}</li>
+ </ul>
+{% endblock %}
+
+{% block menu_discounts_class %} active{% endblock %}
+
+{% block content %}
+ {% if vouchers %}
+ <div class="card">
+ <div class="data-table-container">
+ <table class="bordered hoverable responsive data-table">
+ <thead>
+ <tr>
+ <th class="wide">{% trans "Name" %}</th>
+ <th>{% trans "Discount" %}</th>
+ <th>{% trans "Start date" %}</th>
+ <th>{% trans "End date" %}</th>
+ <th>{% trans "Usage limit" %}</th>
+ <th>{% trans "Used" %}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for voucher in vouchers %}
+ <tr>
+ <td>
+ <a href="{% url 'dashboard:voucher-update' pk=voucher.pk %}">{{ voucher }}</a>
+ </td>
+ <td>{{ voucher.discount_value }}{{ voucher.get_discount_value_type_display }}</td>
+ <td>{{ voucher.start_date }}</td>
+ <td>{{ voucher.end_date|default:"-" }}</td>
+ <td>{{ voucher.usage_limit|default:_("unlimited") }}</td>
+ <td>{{ voucher.used }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ {% include "dashboard/includes/_pagination.html" %}
+ {% else %}
+ <p>{% trans "No vouchers found." %}</p>
+ {% endif %}
+{% endblock %}
diff --git a/saleor/dashboard/templates/dashboard/discount/voucher_modal_confirm_delete.html b/saleor/dashboard/templates/dashboard/discount/voucher_modal_confirm_delete.html
new file mode 100644
index 0000000000..42a6b7408a
--- /dev/null
+++ b/saleor/dashboard/templates/dashboard/discount/voucher_modal_confirm_delete.html
@@ -0,0 +1,17 @@
+{% load i18n %}
+
+<form action="{% url "dashboard:voucher-delete" pk=voucher.pk %}" method="post">
+ {% csrf_token %}
+ <div class="modal-content">
+ <h5>{% trans "Are you sure?" %}</h5>
+
+ <p>
+ {% blocktrans %}You are about to delete <strong>{{ voucher }}</strong>.{% endblocktrans %}
+ </p>
+ </div>
+
+ <div class="modal-footer">
+ <button type="submit" class="modal-action btn-flat blue-text">{% trans "Delete" %}</button>
+ <a href="#!" class="modal-action modal-close btn-flat blue-text">{% trans "Cancel" %}</a>
+ </div>
+</form>
diff --git a/saleor/static/js_src/dashboard.jsx b/saleor/static/js_src/dashboard.jsx
index 905f265d77..25f8a7c7bf 100644
--- a/saleor/static/js_src/dashboard.jsx
+++ b/saleor/static/js_src/dashboard.jsx
@@ -181,3 +181,21 @@ function initSelects() {
$('select:not(.browser-default):not([multiple])').material_select();
$('select[multiple]').addClass('browser-default').select2();
}
+
+// Coupon dynamic forms
+$(document).ready(() => {
+ let $voucherTypeInput = $('.body-vouchers [name="type"]');
+ if ($voucherTypeInput.length) {
+ let $discountValueType = $('[name="discount_value_type"]');
+ let $voucherForms = $('.voucher-form');
+ $voucherTypeInput.on('change', () => {
+ let type = $voucherTypeInput.val();
+ $voucherForms.each((index, form) => {
+ let $form = $(form);
+ let hideForm = $form.data('type') !== type;
+ $form.toggleClass('hide', hideForm);
+ });
+ });
+ $voucherTypeInput.trigger('change');
+ }
+});
diff --git a/saleor/static/scss/_app_dashboard.scss b/saleor/static/scss/_app_dashboard.scss
index 78f36a8b31..b4698da762 100644
--- a/saleor/static/scss/_app_dashboard.scss
+++ b/saleor/static/scss/_app_dashboard.scss
@@ -79,7 +79,7 @@ $transition-duration: .2s;
@extend .active;
}
- @each $submodule in (products, attributes, categories, orders, payments, customers, discounts) {
+ @each $submodule in (products, attributes, categories, orders, payments, customers, discounts, vouchers, sales) {
.body-#{$submodule} &.subnav-#{$submodule} {
@extend .active;