Skip to content

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

Apply voucher for an order functionality

Anna Siwik48119b7c3080
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 4bc4914e7e..d2e105b97e 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -11,8 +11,7 @@ from ..discount.utils import (
def _get_value_voucher_discount_for_checkout(voucher, checkout):
"""Calculate discount value for a voucher of value type."""
- return get_value_voucher_discount(
- voucher, checkout.get_subtotal())
+ return get_value_voucher_discount(voucher, checkout.get_subtotal())
def _get_shipping_voucher_discount_for_checkout(voucher, checkout):
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index d2d8f3e379..377c191067 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -6,14 +6,13 @@ from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_prices.forms import MoneyField
from payments import PaymentError, PaymentStatus
-from saleor.discount.models import Voucher
-
from ...account.i18n import (
AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)
from ...account.models import User
from ...cart.forms import QuantityField
from ...core.exceptions import InsufficientStock
-from ...core.utils import ZERO_TAXED_MONEY
+from ...core.utils import ZERO_TAXED_MONEY, format_money
+from ...discount.models import Voucher
from ...discount.utils import decrease_voucher_usage, increase_voucher_usage
from ...order import OrderStatus
from ...order.emails import send_note_confirmation, send_order_confirmation
@@ -28,7 +27,9 @@ from ...product.utils import allocate_stock, deallocate_stock
from ...shipping.models import ANY_COUNTRY, ShippingMethodCountry
from ..forms import AjaxSelect2ChoiceField
from ..widgets import PhonePrefixWidget
-from .utils import fulfill_order_line, update_order_with_user_addresses
+from .utils import (
+ fulfill_order_line, get_voucher_discount_for_order,
+ update_order_with_user_addresses)
class ConfirmDraftOrderForm(forms.ModelForm):
@@ -38,11 +39,31 @@ class ConfirmDraftOrderForm(forms.ModelForm):
'Send email to customer about order created by staff users',
'Notify customer'),
required=False, initial=True)
+ reapply_voucher = forms.BooleanField(required=False, initial=True)
class Meta:
model = Order
fields = []
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.discount_amount = (
+ get_voucher_discount_for_order(
+ self.instance.voucher, self.instance)
+ if self.instance.voucher else None)
+ discount_amount_differs = (
+ self.instance.voucher and
+ self.instance.discount_amount != self.discount_amount)
+ if discount_amount_differs:
+ self.fields['reapply_voucher'].label = pgettext_lazy(
+ 'Recalculate discount amount on draft order confirmation',
+ 'Update discount amount from %(old_amount)s '
+ 'to %(new_amount)s') % {
+ 'old_amount': format_money(self.instance.discount_amount),
+ 'new_amount': format_money(self.discount_amount)}
+ else:
+ self.fields.pop('reapply_voucher')
+
def clean(self):
super().clean()
errors = []
@@ -237,7 +258,8 @@ class OrderEditVoucherForm(forms.ModelForm):
decrease_voucher_usage(self.old_voucher)
increase_voucher_usage(voucher)
self.instance.discount_name = voucher.name
- # TODO: update discount amount
+ self.instance.discount_amount = get_voucher_discount_for_order(
+ self.instance.voucher, self.instance)
recalculate_order(self.instance)
return super().save(commit)
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index ce14141f30..3f3b7c4182 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -1,7 +1,12 @@
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import get_template
+from prices import Money
+from ...discount import VoucherType
+from ...discount.utils import (
+ get_product_or_category_voucher_discount, get_shipping_voucher_discount,
+ get_value_voucher_discount)
from ...product.utils import decrease_stock
INVOICE_TEMPLATE = 'dashboard/order/pdf/invoice.html'
@@ -62,3 +67,70 @@ def update_order_with_user_addresses(order):
order.user.default_shipping_address.get_copy()
if order.user.default_shipping_address else None)
order.save()
+
+
+def get_product_variants_and_prices(order, product):
+ """Get variants and unit prices from order lines matching the product."""
+ lines = (
+ line for line in order.lines.all() if line.product == product)
+ for line in lines:
+ for dummy_i in range(line.quantity):
+ variant = line.product.variants.filter(sku=line.product_sku)
+ yield variant, line.get_price_per_item()
+
+
+def get_category_variants_and_prices(order, root_category):
+ """Get variants and unit prices from cart lines matching the category.
+
+ Product is assumed to be in the category if it belongs to any of its
+ descendant subcategories.
+ """
+ products = {line.product for line in order.lines.all() if line.product}
+ matching_products = set()
+ for product in products:
+ if product.category.is_descendant_of(root_category, include_self=True):
+ matching_products.add(product)
+ for product in matching_products:
+ for line in get_product_variants_and_prices(order, product):
+ yield line
+
+
+def _get_value_voucher_discount_for_order(voucher, order):
+ """Calculate discount value for a voucher of value type."""
+ return get_value_voucher_discount(voucher, order.get_subtotal())
+
+
+def _get_shipping_voucher_discount_for_order(voucher, order):
+ """Calculate discount value for a voucher of shipping type."""
+ return get_shipping_voucher_discount(
+ voucher, order.get_subtotal(), order.shipping_price)
+
+
+def _get_product_or_category_voucher_discount_for_order(voucher, order):
+ """Calculate discount value for a voucher of product or category type."""
+ if voucher.type == VoucherType.PRODUCT:
+ prices = [
+ item[1] for item in get_product_variants_and_prices(
+ order, voucher.product)]
+ else:
+ prices = [
+ item[1] for item in get_category_variants_and_prices(
+ order, voucher.category)]
+ if not prices:
+ return Money(0, settings.DEFAULT_CURRENCY)
+ return get_product_or_category_voucher_discount(voucher, prices)
+
+
+def get_voucher_discount_for_order(voucher, order):
+ """Calculate discount value depending on voucher and discount types.
+
+ Raise NotApplicable if voucher of given type cannot be applied.
+ """
+ if voucher.type == VoucherType.VALUE:
+ return _get_value_voucher_discount_for_order(voucher, order)
+ if voucher.type == VoucherType.SHIPPING:
+ return _get_shipping_voucher_discount_for_order(voucher, order)
+ if voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):
+ return _get_product_or_category_voucher_discount_for_order(
+ voucher, order)
+ raise NotImplementedError('Unknown discount type')
diff --git a/templates/dashboard/order/modal/confirm_order.html b/templates/dashboard/order/modal/confirm_order.html
index 25ee79b76e..b00be1e869 100644
--- a/templates/dashboard/order/modal/confirm_order.html
+++ b/templates/dashboard/order/modal/confirm_order.html
@@ -17,6 +17,9 @@
Are you sure you want confirm order {{ order }}? Once the order has been confirmed, you will not be able to make changes.
{% endblocktrans %}
{{ form.notify_customer|materializecss }}
+ {% if form.reapply_voucher %}
+ {{ form.reapply_voucher|materializecss }}
+ {% endif %}
</div>
{% endblock %}