Skip to content

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

Add logic to handle staff discounts (#7494)

Maciej Korycinskia80890f7009c
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 722bd57072..0380c0ea07 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -181,7 +181,12 @@ def test_get_voucher_discount_for_checkout_voucher_validation(
subtotal = manager.calculate_checkout_subtotal(checkout_info, lines, address, [])
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
- voucher, subtotal, quantity, customer_email, checkout_with_voucher.channel
+ voucher,
+ subtotal,
+ quantity,
+ customer_email,
+ checkout_with_voucher.channel,
+ checkout_info.user,
)
@@ -985,6 +990,48 @@ def test_add_voucher_to_checkout(checkout_with_item, voucher):
assert checkout_with_item.voucher_code == voucher.code
+def test_add_staff_voucher_to_anonymous_checkout(checkout_with_item, voucher):
+ voucher.only_for_staff = True
+ voucher.save()
+
+ assert checkout_with_item.voucher_code is None
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ with pytest.raises(NotApplicable):
+ add_voucher_to_checkout(manager, checkout_info, lines, voucher)
+
+
+def test_add_staff_voucher_to_customer_checkout(
+ checkout_with_item, voucher, customer_user
+):
+ checkout_with_item.user = customer_user
+ checkout_with_item.save()
+ voucher.only_for_staff = True
+ voucher.save()
+
+ assert checkout_with_item.voucher_code is None
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ with pytest.raises(NotApplicable):
+ add_voucher_to_checkout(manager, checkout_info, lines, voucher)
+
+
+def test_add_staff_voucher_to_staff_checkout(checkout_with_item, voucher, staff_user):
+ checkout_with_item.user = staff_user
+ checkout_with_item.save()
+ voucher.only_for_staff = True
+ voucher.save()
+
+ assert checkout_with_item.voucher_code is None
+ manager = get_plugins_manager()
+ lines = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+
+ add_voucher_to_checkout(manager, checkout_info, lines, voucher)
+
+
def test_add_voucher_to_checkout_fail(
checkout_with_item, voucher_with_high_min_spent_amount
):
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
index 1d2e9cf877..2fd4ae9823 100644
--- a/saleor/core/jwt.py
+++ b/saleor/core/jwt.py
@@ -167,11 +167,15 @@ def get_user_from_access_payload(payload: dict) -> Optional[User]:
)
permissions = payload.get(PERMISSIONS_FIELD, None)
user = get_user_from_payload(payload)
- if user and permissions is not None:
- token_permissions = get_permissions_from_names(permissions)
- token_codenames = [perm.codename for perm in token_permissions]
- user.effective_permissions = get_permissions_from_codenames(token_codenames)
- user.is_staff = True if user.effective_permissions else False
+ if user:
+ if permissions is not None:
+ token_permissions = get_permissions_from_names(permissions)
+ token_codenames = [perm.codename for perm in token_permissions]
+ user.effective_permissions = get_permissions_from_codenames(token_codenames)
+ user.is_staff = True if user.effective_permissions else False
+
+ if payload.get("is_staff"):
+ user.is_staff = True
return user
diff --git a/saleor/discount/migrations/0026_voucher_only_for_staff.py b/saleor/discount/migrations/0026_voucher_only_for_staff.py
new file mode 100644
index 0000000000..d9ce28d01e
--- /dev/null
+++ b/saleor/discount/migrations/0026_voucher_only_for_staff.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.2 on 2021-06-17 16:50
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0025_auto_20210506_0831"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="voucher",
+ name="only_for_staff",
+ field=models.BooleanField(default=False),
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 288b96ca6d..a71ffda229 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -1,5 +1,6 @@
from decimal import Decimal
from functools import partial
+from typing import TYPE_CHECKING, Optional
from django.conf import settings
from django.contrib.postgres.indexes import GinIndex
@@ -17,6 +18,9 @@ from ..core.taxes import display_gross_prices
from ..core.utils.translations import TranslationProxy
from . import DiscountValueType, OrderDiscountType, VoucherType
+if TYPE_CHECKING:
+ from ..account.models import User
+
class NotApplicable(ValueError):
"""Exception raised when a discount is not applicable to a checkout.
@@ -68,6 +72,8 @@ class Voucher(models.Model):
apply_once_per_order = models.BooleanField(default=False)
apply_once_per_customer = models.BooleanField(default=False)
+ only_for_staff = models.BooleanField(default=False)
+
discount_value_type = models.CharField(
max_length=10,
choices=DiscountValueType.CHOICES,
@@ -146,6 +152,14 @@ class Voucher(models.Model):
msg = "This offer is valid only once per customer."
raise NotApplicable(msg)
+ def validate_only_for_staff(self, customer: Optional["User"]):
+ if not self.only_for_staff:
+ return
+
+ if not customer or not customer.is_staff:
+ msg = "This offer is valid only for staff customers."
+ raise NotApplicable(msg)
+
class VoucherChannelListing(models.Model):
voucher = models.ForeignKey(
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 018a005744..325e53ee89 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -415,7 +415,67 @@ def test_validate_voucher(
)
total_price = Money(total, "USD")
price = TaxedMoney(gross=total_price, net=total_price)
- validate_voucher(voucher, price, total_quantity, "[email protected]", channel_USD)
+ validate_voucher(
+ voucher, price, total_quantity, "[email protected]", channel_USD, None
+ )
+
+
+def test_validate_staff_voucher_for_anonymous(
+ channel_USD,
+):
+ voucher = Voucher.objects.create(
+ code="unique",
+ type=VoucherType.ENTIRE_ORDER,
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ only_for_staff=True,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ )
+ total_price = Money(100, "USD")
+ price = TaxedMoney(gross=total_price, net=total_price)
+ with pytest.raises(NotApplicable):
+ validate_voucher(voucher, price, 2, "[email protected]", channel_USD, None)
+
+
+def test_validate_staff_voucher_for_normal_customer(channel_USD, customer_user):
+ voucher = Voucher.objects.create(
+ code="unique",
+ type=VoucherType.ENTIRE_ORDER,
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ only_for_staff=True,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ )
+ total_price = Money(100, "USD")
+ price = TaxedMoney(gross=total_price, net=total_price)
+ with pytest.raises(NotApplicable):
+ validate_voucher(
+ voucher, price, 2, customer_user.email, channel_USD, customer_user
+ )
+
+
+def test_validate_staff_voucher_for_staff_customer(channel_USD, staff_user):
+ voucher = Voucher.objects.create(
+ code="unique",
+ type=VoucherType.ENTIRE_ORDER,
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ only_for_staff=True,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ )
+ total_price = Money(100, "USD")
+ price = TaxedMoney(gross=total_price, net=total_price)
+
+ validate_voucher(voucher, price, 2, staff_user.email, channel_USD, staff_user)
@pytest.mark.parametrize(
@@ -453,7 +513,7 @@ def test_validate_voucher_not_applicable(
with pytest.raises(NotApplicable):
validate_voucher(
- voucher, price, total_quantity, "[email protected]", channel_USD
+ voucher, price, total_quantity, "[email protected]", channel_USD, None
)
@@ -466,7 +526,9 @@ def test_validate_voucher_not_applicable_once_per_customer(
price = Money(0, "USD")
total_price = TaxedMoney(net=price, gross=price)
with pytest.raises(NotApplicable):
- validate_voucher(voucher, total_price, 0, customer_user.email, channel_USD)
+ validate_voucher(
+ voucher, total_price, 0, customer_user.email, channel_USD, customer_user
+ )
date_time_now = timezone.now()
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index de7b768635..64ae3d65cc 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -14,6 +14,7 @@ from .models import NotApplicable, Sale, SaleChannelListing, VoucherCustomer
if TYPE_CHECKING:
# flake8: noqa
+ from ..account.models import User
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..order.models import Order
from ..plugins.manager import PluginsManager
@@ -135,6 +136,7 @@ def validate_voucher_for_checkout(
quantity,
customer_email,
checkout_info.channel,
+ checkout_info.user,
)
@@ -144,7 +146,9 @@ def validate_voucher_in_order(order: "Order"):
customer_email = order.get_customer_email()
if not order.voucher:
return
- validate_voucher(order.voucher, subtotal, quantity, customer_email, order.channel)
+ validate_voucher(
+ order.voucher, subtotal, quantity, customer_email, order.channel, order.user
+ )
def validate_voucher(
@@ -153,11 +157,14 @@ def validate_voucher(
quantity: int,
customer_email: str,
channel: Channel,
+ customer: Optional["User"],
) -> None:
voucher.validate_min_spent(total_price, channel)
voucher.validate_min_checkout_items_quantity(quantity)
if voucher.apply_once_per_customer:
voucher.validate_once_per_customer(customer_email)
+ if voucher.only_for_staff:
+ voucher.validate_only_for_staff(customer)
def get_products_voucher_discount(
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 148ab0b9e6..442709856a 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -978,6 +978,13 @@ class CheckoutAddPromoCode(BaseMutation):
checkout_info = fetch_checkout_info(
checkout, lines, info.context.discounts, manager
)
+
+ if info.context.user and checkout.user == info.context.user:
+ # reassign user from request to make sure that we will take into account
+ # that user can have granted staff permissions from external resources.
+ # Which is required to determine if user has access to 'staff discount'
+ checkout_info.user = info.context.user
+
add_promo_code_to_checkout(
manager,
checkout_info,
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index c6ad284f85..3e2f7772e1 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -150,6 +150,9 @@ class VoucherInput(graphene.InputObjectType):
apply_once_per_customer = graphene.Boolean(
description="Voucher should be applied once per customer."
)
+ only_for_staff = graphene.Boolean(
+ description="Voucher can be used only by staff user."
+ )
usage_limit = graphene.Int(
description="Limit number of times this voucher can be used in total."
)
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index 33066f48bf..aeb0a10cf8 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -186,6 +186,7 @@ class Voucher(ChannelContextType, CountableDjangoObjectType):
"providing valid voucher codes."
)
only_fields = [
+ "only_for_staff",
"apply_once_per_order",
"apply_once_per_customer",
"code",
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index acebe5f54c..e7e0c086ca 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5758,6 +5758,7 @@ type Voucher implements Node {
endDate: DateTime
applyOncePerOrder: Boolean!
applyOncePerCustomer: Boolean!
+ onlyForStaff: Boolean!
discountValueType: DiscountValueTypeEnum!
minCheckoutItemsQuantity: Int
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
@@ -5859,6 +5860,7 @@ input VoucherInput {
countries: [String]
applyOncePerOrder: Boolean
applyOncePerCustomer: Boolean
+ onlyForStaff: Boolean
usageLimit: Int
}
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index ea295a49c1..e3c8a9d251 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -678,7 +678,12 @@ def test_get_voucher_discount_for_order_voucher_validation(
validate_voucher_in_order(order_with_lines)
mock_validate_voucher.assert_called_once_with(
- voucher, subtotal, quantity, customer_email, order_with_lines.channel
+ voucher,
+ subtotal,
+ quantity,
+ customer_email,
+ order_with_lines.channel,
+ order_with_lines.user,
)