Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Reapply voucher on order state change
Anna Siwik3557251ce8d5
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 377c191067..cbbd2cdaec 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -5,6 +5,7 @@ from django.urls import reverse, reverse_lazyfrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.forms import MoneyFieldfrom payments import PaymentError, PaymentStatus+from prices import Moneyfrom ...account.i18n import (AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)@@ -47,20 +48,18 @@ class ConfirmDraftOrderForm(forms.ModelForm):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.discount_amount = get_voucher_discount_for_order(self.instance)+ if self.instance.discount_amount != self.discount_amount: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)}+ 'old_amount': format_money(+ self.instance.discount_amount or+ Money(0, settings.DEFAULT_CURRENCY)),+ 'new_amount': format_money(+ self.discount_amount or+ Money(0, settings.DEFAULT_CURRENCY))}else:self.fields.pop('reapply_voucher')@@ -112,6 +111,8 @@ class ConfirmDraftOrderForm(forms.ModelForm):email = self.instance.get_user_current_email()if email:send_order_confirmation.delay(self.instance.pk)+ if self.cleaned_data.get('reapply_voucher'):+ recalculate_order(self.instance, self.discount_amount)return super().save(commit)@@ -198,7 +199,8 @@ class OrderShippingForm(forms.ModelForm):method = self.instance.shipping_methodself.instance.shipping_method_name = method.shipping_method.nameself.instance.shipping_price = method.get_total_price()- recalculate_order(self.instance)+ recalculate_order(+ self.instance, get_voucher_discount_for_order(self.instance))return super().save(commit)@@ -213,7 +215,8 @@ class OrderRemoveShippingForm(forms.ModelForm):self.instance.shipping_method = Noneself.instance.shipping_method_name = Noneself.instance.shipping_price = ZERO_TAXED_MONEY- recalculate_order(self.instance)+ recalculate_order(+ self.instance, get_voucher_discount_for_order(self.instance))return super().save(commit)@@ -257,10 +260,9 @@ class OrderEditVoucherForm(forms.ModelForm):if self.old_voucher:decrease_voucher_usage(self.old_voucher)increase_voucher_usage(voucher)- self.instance.discount_name = voucher.name- self.instance.discount_amount = get_voucher_discount_for_order(- self.instance.voucher, self.instance)- recalculate_order(self.instance)+ self.instance.discount_name = voucher.name or ''+ recalculate_order(+ self.instance, get_voucher_discount_for_order(self.instance))return super().save(commit)@@ -370,7 +372,7 @@ class CancelOrderLineForm(forms.Form):deallocate_stock(self.line.stock, self.line.quantity)order = self.line.orderself.line.delete()- recalculate_order(order)+ recalculate_order(order, get_voucher_discount_for_order(order))class ChangeQuantityForm(forms.ModelForm):@@ -412,7 +414,8 @@ class ChangeQuantityForm(forms.ModelForm):delta = quantity - self.initial_quantityallocate_stock(stock, delta)change_order_line_quantity(self.instance, quantity)- recalculate_order(self.instance.order)+ order = self.instance.order+ recalculate_order(order, get_voucher_discount_for_order(order))return self.instance@@ -613,7 +616,8 @@ class AddVariantToOrderForm(forms.Form):quantity = self.cleaned_data.get('quantity')add_variant_to_order(self.order, variant, quantity, self.discounts)- recalculate_order(self.order)+ recalculate_order(+ self.order, get_voucher_discount_for_order(self.order))class AddressForm(StorefrontAddressForm):diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex 3f3b7c4182..f50f652d51 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -3,7 +3,9 @@ from django.contrib.sites.shortcuts import get_current_sitefrom django.template.loader import get_templatefrom prices import Money+from saleor.product.models import ProductVariantfrom ...discount import VoucherType+from ...discount.models import NotApplicablefrom ...discount.utils import (get_product_or_category_voucher_discount, get_shipping_voucher_discount,get_value_voucher_discount)@@ -75,8 +77,9 @@ def get_product_variants_and_prices(order, product):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()+ variant = line.product.variants.get(sku=line.product_sku)+ if variant:+ yield variant, variant.get_price_per_item()def get_category_variants_and_prices(order, root_category):@@ -95,42 +98,52 @@ def get_category_variants_and_prices(order, root_category):yield line-def _get_value_voucher_discount_for_order(voucher, order):+def _get_value_voucher_discount_for_order(order):"""Calculate discount value for a voucher of value type."""- return get_value_voucher_discount(voucher, order.get_subtotal())+ try:+ discount_amount = get_value_voucher_discount(+ order.voucher, order.get_subtotal())+ except NotApplicable:+ discount_amount = Money(0, settings.DEFAULT_CURRENCY)+ return discount_amount-def _get_shipping_voucher_discount_for_order(voucher, order):+def _get_shipping_voucher_discount_for_order(order):"""Calculate discount value for a voucher of shipping type."""- return get_shipping_voucher_discount(- voucher, order.get_subtotal(), order.shipping_price)+ try:+ discount_amount = get_shipping_voucher_discount(+ order.voucher, order.get_subtotal(), order.shipping_price)+ except NotApplicable:+ discount_amount = Money(0, settings.DEFAULT_CURRENCY)+ return discount_amount-def _get_product_or_category_voucher_discount_for_order(voucher, order):+def _get_product_or_category_voucher_discount_for_order(order):"""Calculate discount value for a voucher of product or category type."""- if voucher.type == VoucherType.PRODUCT:+ if order.voucher.type == VoucherType.PRODUCT:prices = [item[1] for item in get_product_variants_and_prices(- order, voucher.product)]+ order, order.voucher.product)]else:prices = [item[1] for item in get_category_variants_and_prices(- order, voucher.category)]+ order, order.voucher.category)]if not prices:return Money(0, settings.DEFAULT_CURRENCY)- return get_product_or_category_voucher_discount(voucher, prices)+ return get_product_or_category_voucher_discount(order.voucher, prices)-def get_voucher_discount_for_order(voucher, order):+def get_voucher_discount_for_order(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)+ if not order.voucher:+ return None+ if order.voucher.type == VoucherType.VALUE:+ return _get_value_voucher_discount_for_order(order)+ if order.voucher.type == VoucherType.SHIPPING:+ return _get_shipping_voucher_discount_for_order(order)+ if order.voucher.type in (VoucherType.PRODUCT, VoucherType.CATEGORY):+ return _get_product_or_category_voucher_discount_for_order(order)raise NotImplementedError('Unknown discount type')diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex e74df70928..9457f2cf79 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -29,7 +29,7 @@ def check_order_status(func):return decorator-def recalculate_order(order):+def recalculate_order(order, discount_amount=None):"""Recalculate and assign total price of order.Total price is a sum of items in order and order shipping price minus@@ -37,6 +37,8 @@ def recalculate_order(order):"""prices = [line.get_total() for line in order]total = sum(prices, order.shipping_price)+ if discount_amount is not None:+ order.discount_amount = discount_amountif order.discount_amount:total -= order.discount_amountorder.total = total