Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor voucher validation
fowczarekd777ddc08ebf
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex efa1bb3d9f..7cc6f9d08d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -37,9 +37,8 @@ from ..discount.models import NotApplicable, Voucherfrom ..discount.utils import (decrease_voucher_usage,get_products_voucher_discount,- get_shipping_voucher_discount,- get_value_voucher_discount,increase_voucher_usage,+ validate_voucher_for_checkout,)from ..giftcard.utils import (add_gift_card_code_to_checkout,@@ -767,12 +766,8 @@ def _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts=Non)raise NotApplicable(msg)- return get_shipping_voucher_discount(- voucher,- calculate_checkout_subtotal(checkout, discounts).gross,- calculate_checkout_shipping(checkout, discounts).gross,- checkout.quantity,- )+ shipping_price = calculate_checkout_shipping(checkout, discounts).gross+ return voucher.get_discount_amount_for(shipping_price)def _get_products_voucher_discount(checkout, voucher, discounts=None):@@ -798,8 +793,7 @@ def _get_products_voucher_discount(checkout, voucher, discounts=None):"Voucher not applicable", "This offer is only valid for selected items.")raise NotApplicable(msg)- subtotal = calculate_checkout_subtotal(checkout, discounts).gross- return get_products_voucher_discount(voucher, prices, subtotal, checkout.quantity)+ return get_products_voucher_discount(voucher, prices)def get_voucher_discount_for_checkout(voucher, checkout, discounts=None):@@ -807,9 +801,10 @@ def get_voucher_discount_for_checkout(voucher, checkout, discounts=None):Raise NotApplicable if voucher of given type cannot be applied."""+ validate_voucher_for_checkout(voucher, checkout, discounts)if voucher.type == VoucherType.ENTIRE_ORDER:subtotal = calculate_checkout_subtotal(checkout, discounts).gross- return get_value_voucher_discount(voucher, subtotal, checkout.quantity)+ return voucher.get_discount_amount_for(subtotal)if voucher.type == VoucherType.SHIPPING:return _get_shipping_voucher_discount_for_checkout(voucher, checkout, discounts)if voucher.type in (diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.pyindex e2c8ed0915..eb232449fd 100644--- a/saleor/dashboard/order/utils.py+++ b/saleor/dashboard/order/utils.py@@ -8,11 +8,7 @@ from ...checkout import AddressTypefrom ...core.taxes import zero_moneyfrom ...discount import VoucherTypefrom ...discount.models import NotApplicable-from ...discount.utils import (- get_products_voucher_discount,- get_shipping_voucher_discount,- get_value_voucher_discount,-)+from ...discount.utils import get_products_voucher_discount, validate_voucher_in_orderINVOICE_TEMPLATE = "dashboard/order/pdf/invoice.html"PACKING_SLIP_TEMPLATE = "dashboard/order/pdf/packing_slip.html"@@ -140,9 +136,7 @@ def get_products_voucher_discount_for_order(order, voucher):"Voucher not applicable", "This offer is only valid for selected items.")raise NotApplicable(msg)- return get_products_voucher_discount(- voucher, prices, order.get_subtotal().gross, order.get_total_quantity()- )+ return get_products_voucher_discount(voucher, prices)def get_voucher_discount_for_order(order):@@ -152,18 +146,12 @@ def get_voucher_discount_for_order(order):"""if not order.voucher:return zero_money()+ validate_voucher_in_order(order)subtotal = order.get_subtotal()if order.voucher.type == VoucherType.ENTIRE_ORDER:- return get_value_voucher_discount(- order.voucher, subtotal.gross, order.get_total_quantity()- )+ return order.voucher.get_discount_amount_for(subtotal.gross)if order.voucher.type == VoucherType.SHIPPING:- return get_shipping_voucher_discount(- order.voucher,- subtotal.gross,- order.shipping_price,- order.get_total_quantity(),- )+ return order.voucher.get_discount_amount_for(order.shipping_price)if order.voucher.type in (VoucherType.PRODUCT,VoucherType.COLLECTION,diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 674293e01d..69dd5ba86b 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -6,6 +6,7 @@ from django.db.models import Ffrom django.utils.translation import pgettextfrom ..core.taxes import zero_money+from ..core.taxes.interface import calculate_checkout_subtotalfrom . import DiscountInfofrom .models import NotApplicable, Sale@@ -61,24 +62,23 @@ def calculate_discounted_price(product, price, discounts: Iterable[DiscountInfo]return price-def get_value_voucher_discount(voucher, total_price, quantity):- """Calculate discount value for a voucher of value type."""- voucher.validate_min_amount_spent(total_price)- voucher.validate_min_checkout_items_quantity(quantity)- return voucher.get_discount_amount_for(total_price)+def validate_voucher_for_checkout(voucher, checkout, discounts):+ subtotal = calculate_checkout_subtotal(checkout, discounts)+ validate_voucher(voucher, subtotal.gross, checkout.quantity)++def validate_voucher_in_order(order):+ subtotal = order.get_subtotal()+ validate_voucher(order.voucher, subtotal.gross, order.get_total_quantity())-def get_shipping_voucher_discount(voucher, total_price, shipping_price, quantity):- """Calculate discount value for a voucher of shipping type."""++def validate_voucher(voucher, total_price, quantity):voucher.validate_min_amount_spent(total_price)voucher.validate_min_checkout_items_quantity(quantity)- return voucher.get_discount_amount_for(shipping_price)-def get_products_voucher_discount(voucher, prices, total_price, quantity):+def get_products_voucher_discount(voucher, prices):"""Calculate discount value for a voucher of product or category type."""- voucher.validate_min_amount_spent(total_price)- voucher.validate_min_checkout_items_quantity(quantity)if voucher.apply_once_per_order:return voucher.get_discount_amount_for(min(prices))discounts = (voucher.get_discount_amount_for(price) for price in prices)diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex d6162098f5..84b5ab3fe1 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -31,7 +31,7 @@ from saleor.checkout.utils import ()from saleor.core.exceptions import InsufficientStockfrom saleor.core.taxes import zero_money, zero_taxed_money-from saleor.core.taxes.interface import taxes_are_enabled+from saleor.core.taxes.interface import calculate_checkout_subtotal, taxes_are_enabledfrom saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Voucherfrom saleor.order import OrderEvents, OrderEventsEmails@@ -825,27 +825,50 @@ def test_note_in_created_order(request_checkout_with_item, address, customer_use@pytest.mark.parametrize(- "total, discount_value, discount_type, min_amount_spent, discount_amount",+ "total, min_amount_spent, total_quantity, min_checkout_items_quantity, "+ "discount_value, discount_value_type, expected_value",[- ("100", 10, DiscountValueType.FIXED, None, 10),- ("100.05", 10, DiscountValueType.PERCENTAGE, 100, 10),+ (20, 20, 2, 2, 50, DiscountValueType.PERCENTAGE, 10),+ (20, None, 2, None, 50, DiscountValueType.PERCENTAGE, 10),+ (20, 20, 2, 2, 5, DiscountValueType.FIXED, 5),+ (20, None, 2, None, 5, DiscountValueType.FIXED, 5),],)def test_get_discount_for_checkout_value_voucher(- total, discount_value, discount_type, min_amount_spent, discount_amount+ total,+ min_amount_spent,+ total_quantity,+ min_checkout_items_quantity,+ discount_value,+ discount_value_type,+ expected_value,):voucher = Voucher(code="unique",type=VoucherType.ENTIRE_ORDER,- discount_value_type=discount_type,+ discount_value_type=discount_value_type,discount_value=discount_value,min_amount_spent=(Money(min_amount_spent, "USD") if min_amount_spent is not None else None),+ min_checkout_items_quantity=min_checkout_items_quantity,+ )+ checkout = Mock(+ get_subtotal=Mock(return_value=Money(total, "USD")), quantity=total_quantity)- checkout = Mock(get_subtotal=Mock(return_value=Money(total, "USD")))discount = get_voucher_discount_for_checkout(voucher, checkout)- assert discount == Money(discount_amount, "USD")+ assert discount == Money(expected_value, "USD")+++@patch("saleor.discount.utils.validate_voucher")+def test_get_voucher_discount_for_checkout_voucher_validation(+ mock_validate_voucher, voucher, checkout_with_voucher+):+ get_voucher_discount_for_checkout(voucher, checkout_with_voucher)+ subtotal = calculate_checkout_subtotal(checkout_with_voucher, [])+ mock_validate_voucher.assert_called_once_with(+ voucher, subtotal.gross, checkout_with_voucher.quantity+ )@pytest.mark.parametrize(@@ -1018,9 +1041,12 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries():assert discount == Money(5, "USD")-def test_get_discount_for_checkout_shipping_voucher_limited_countries():+def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatch):subtotal = TaxedMoney(net=Money(100, "USD"), gross=Money(100, "USD"))shipping_total = TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))+ monkeypatch.setattr(+ "saleor.discount.utils.calculate_checkout_subtotal", Mock(return_value=subtotal)+ )checkout = Mock(get_subtotal=Mock(return_value=subtotal),is_shipping_required=Mock(return_value=True),@@ -1155,6 +1181,10 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(def test_get_discount_for_checkout_product_voucher_not_applicable(monkeypatch):discounts = []+ monkeypatch.setattr(+ "saleor.discount.utils.calculate_checkout_subtotal",+ Mock(return_value=TaxedMoney(net=Money("1", "USD"), gross=Money("1", "USD"))),+ )monkeypatch.setattr("saleor.checkout.utils.get_prices_of_discounted_products",lambda checkout, discounts, product: [],@@ -1175,6 +1205,10 @@ def test_get_discount_for_checkout_product_voucher_not_applicable(monkeypatch):def test_get_discount_for_checkout_collection_voucher_not_applicable(monkeypatch):discounts = []+ monkeypatch.setattr(+ "saleor.discount.utils.calculate_checkout_subtotal",+ Mock(return_value=TaxedMoney(net=Money("1", "USD"), gross=Money("1", "USD"))),+ )monkeypatch.setattr("saleor.checkout.utils.get_prices_of_products_in_discounted_collections", # noqalambda checkout, discounts, product: [],diff --git a/tests/test_discounts.py b/tests/test_discounts.pyindex d9d76f17ed..9fa270e701 100644--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@ -10,10 +10,8 @@ from saleor.discount.models import NotApplicable, Sale, Voucherfrom saleor.discount.utils import (decrease_voucher_usage,get_product_discount_on_sale,- get_products_voucher_discount,- get_shipping_voucher_discount,- get_value_voucher_discount,increase_voucher_usage,+ validate_voucher,)from saleor.product.models import Product, ProductVariant@@ -189,36 +187,32 @@ def test_decrease_voucher_usage():@pytest.mark.parametrize(- "total, min_amount_spent, total_quantity, min_checkout_items_quantity, "- "discount_value, discount_value_type, expected_value",+ "total, min_amount_spent, total_quantity, min_checkout_items_quantity,"+ "discount_value_type",[- (20, 20, 2, 2, 50, DiscountValueType.PERCENTAGE, 10),- (20, None, 2, None, 50, DiscountValueType.PERCENTAGE, 10),- (20, 20, 2, 2, 5, DiscountValueType.FIXED, 5),- (20, None, 2, None, 5, DiscountValueType.FIXED, 5),+ (20, 20, 2, 2, DiscountValueType.PERCENTAGE),+ (20, None, 2, None, DiscountValueType.PERCENTAGE),+ (20, 20, 2, 2, DiscountValueType.FIXED),+ (20, None, 2, None, DiscountValueType.FIXED),],)-def test_get_value_voucher_discount(+def test_validate_voucher(total,min_amount_spent,total_quantity,min_checkout_items_quantity,- discount_value,discount_value_type,- expected_value,):- voucher = Voucher(+ voucher = Voucher.objects.create(code="unique",type=VoucherType.ENTIRE_ORDER,discount_value_type=discount_value_type,- discount_value=discount_value,+ discount_value=50,min_amount_spent=get_min_amount_spent(min_amount_spent),min_checkout_items_quantity=min_checkout_items_quantity,)- voucher.save()total_price = Money(total, "USD")- discount = get_value_voucher_discount(voucher, total_price, total_quantity)- assert discount == Money(expected_value, "USD")+ validate_voucher(voucher, total_price, total_quantity)@pytest.mark.parametrize(@@ -230,7 +224,7 @@ def test_get_value_voucher_discount((20, None, 2, 10, 50, DiscountValueType.FIXED),],)-def test_get_value_voucher_discount_not_applicable(+def test_validate_voucher_not_applicable(total,min_amount_spent,total_quantity,@@ -249,237 +243,7 @@ def test_get_value_voucher_discount_not_applicable(voucher.save()total_price = Money(total, "USD")with pytest.raises(NotApplicable):- get_value_voucher_discount(voucher, total_price, total_quantity)--- "total, min_amount_spent, total_quantity, min_checkout_items_quantity, "- "shipping_price, discount_value, discount_value_type, expected_value",- [- (20, 20, 2, 2, 10, 50, DiscountValueType.PERCENTAGE, 5),- (20, None, 2, None, 10, 50, DiscountValueType.PERCENTAGE, 5),- (20, 20, 2, 2, 10, 5, DiscountValueType.FIXED, 5),- (20, None, 2, None, 10, 5, DiscountValueType.FIXED, 5),- ],-)-def test_get_shipping_voucher_discount(- total,- min_amount_spent,- total_quantity,- min_checkout_items_quantity,- shipping_price,- discount_value,- discount_value_type,- expected_value,-):- voucher = Voucher(- code="unique",- type=VoucherType.ENTIRE_ORDER,- discount_value_type=discount_value_type,- discount_value=discount_value,- min_amount_spent=get_min_amount_spent(min_amount_spent),- min_checkout_items_quantity=min_checkout_items_quantity,- )- voucher.save()- total = Money(total, "USD")- shipping_price = Money(shipping_price, "USD")- discount = get_shipping_voucher_discount(- voucher, total, shipping_price, total_quantity- )- assert discount == Money(expected_value, "USD")--- "total, min_amount_spent, total_quantity, min_checkout_items_quantity, "- "shipping_price, discount_value, discount_value_type",- [- (20, 50, 2, 10, 10, 50, DiscountValueType.PERCENTAGE),- (20, 50, 2, None, 10, 50, DiscountValueType.PERCENTAGE),- (20, None, 2, 10, 10, 5, DiscountValueType.FIXED),- ],-)-def test_get_shipping_voucher_discount_not_applicable(- total,- min_amount_spent,- total_quantity,- min_checkout_items_quantity,- shipping_price,- discount_value,- discount_value_type,-):- voucher = Voucher(- code="unique",- type=VoucherType.ENTIRE_ORDER,- discount_value_type=discount_value_type,- discount_value=discount_value,- min_amount_spent=get_min_amount_spent(min_amount_spent),- min_checkout_items_quantity=min_checkout_items_quantity,- )- voucher.save()- total = Money(total, "USD")- shipping_price = Money(shipping_price, "USD")- with pytest.raises(NotApplicable):- get_shipping_voucher_discount(voucher, total, shipping_price, total_quantity)--- "prices, total, min_amount_spent, total_quantity, min_checkout_items_quantity, "- "discount_value_type, discount_value, voucher_type, apply_once_per_order, "- "expected_value",- [ # noqa- (- [5, 10, 15],- 20,- 20,- 4,- 4,- DiscountValueType.PERCENTAGE,- 10,- VoucherType.PRODUCT,- False,- 3,- ),- (- [5, 10, 15],- 20,- None,- 4,- None,- DiscountValueType.PERCENTAGE,- 20,- VoucherType.PRODUCT,- True,- 1,- ),- (- [5, 10, 15],- 20,- 20,- 4,- 4,- DiscountValueType.FIXED,- 2,- VoucherType.SPECIFIC_PRODUCT,- False,- 6,- ),- (- [5, 10, 15],- 20,- None,- 4,- None,- DiscountValueType.FIXED,- 2,- VoucherType.COLLECTION,- True,- 2,- ),- ],-)-def test_get_voucher_discount_all_products(- prices,- total,- min_amount_spent,- total_quantity,- min_checkout_items_quantity,- discount_value_type,- discount_value,- voucher_type,- apply_once_per_order,- expected_value,-):- prices = [Money(price, "USD") for price in prices]- voucher = Voucher(- code="unique",- type=voucher_type,- discount_value_type=discount_value_type,- discount_value=discount_value,- apply_once_per_order=apply_once_per_order,- min_amount_spent=get_min_amount_spent(min_amount_spent),- min_checkout_items_quantity=min_checkout_items_quantity,- )- voucher.save()- total = Money(total, "USD")- discount = get_products_voucher_discount(voucher, prices, total, total_quantity)- assert discount == Money(expected_value, "USD")--- "prices, total, min_amount_spent, total_quantity, min_checkout_items_quantity, "- "discount_value_type, discount_value, voucher_type, apply_once_per_order, ",- [ # noqa- (- [5, 10, 15],- 20,- 50,- 4,- 10,- DiscountValueType.PERCENTAGE,- 10,- VoucherType.PRODUCT,- False,- ),- (- [5, 10, 15],- 20,- 50,- 4,- None,- DiscountValueType.PERCENTAGE,- 10,- VoucherType.PRODUCT,- True,- ),- (- [5, 10, 15],- 20,- None,- 4,- 10,- DiscountValueType.FIXED,- 2,- VoucherType.SPECIFIC_PRODUCT,- False,- ),- (- [5, 10, 15],- 20,- 50,- 4,- 10,- DiscountValueType.FIXED,- 2,- VoucherType.COLLECTION,- True,- ),- ],-)-def test_get_voucher_discount_all_products_not_applicable(- prices,- total,- min_amount_spent,- total_quantity,- min_checkout_items_quantity,- discount_value_type,- discount_value,- voucher_type,- apply_once_per_order,-):- prices = [Money(price, "USD") for price in prices]- voucher = Voucher(- code="unique",- type=voucher_type,- discount_value_type=discount_value_type,- discount_value=discount_value,- apply_once_per_order=apply_once_per_order,- min_amount_spent=get_min_amount_spent(min_amount_spent),- min_checkout_items_quantity=min_checkout_items_quantity,- )- voucher.save()- total = Money(total, "USD")- with pytest.raises(NotApplicable):- get_products_voucher_discount(voucher, prices, total, total_quantity)+ validate_voucher(voucher, total_price, total_quantity)date_time_now = timezone.now()diff --git a/tests/test_order.py b/tests/test_order.pyindex ec7fabacfc..e281e22620 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -10,6 +10,7 @@ from saleor.account.models import Userfrom saleor.checkout.utils import create_order, prepare_order_datafrom saleor.core.exceptions import InsufficientStockfrom saleor.core.weight import zero_weight+from saleor.discount.utils import validate_voucher_in_orderfrom saleor.order import FulfillmentStatus, OrderStatus, events as order_events, modelsfrom saleor.order.models import Fulfillment, Orderfrom saleor.order.utils import (@@ -702,3 +703,16 @@ def test_fulfill_order_line_without_inventory_tracking(order_with_lines):variant.refresh_from_db()assert variant.quantity == stock_quantity_afterassert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity+++@patch("saleor.discount.utils.validate_voucher")+def test_get_voucher_discount_for_order_voucher_validation(+ mock_validate_voucher, voucher, order_with_lines+):+ order_with_lines.voucher = voucher+ order_with_lines.save()+ validate_voucher_in_order(order_with_lines)+ subtotal = order_with_lines.get_subtotal()+ mock_validate_voucher.assert_called_once_with(+ voucher, subtotal.gross, order_with_lines.get_total_quantity()+ )