Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Update gift card and create events when using card in order
IKarbowiakd3ab58054844
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex f817451086..e77f254e79 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -335,8 +335,6 @@ def _prepare_order_data(# Get voucher data (last) as they require a transactionorder_data.update(_get_voucher_data_for_order(checkout_info))- # assign gift cards to the order-order_data["total_price_left"] = (manager.calculate_checkout_subtotal(checkout_info, lines, address, discounts)+ shipping_total@@ -368,7 +366,7 @@ def _create_order(Current user's language is saved in the order so we can later determinewhich language to use when sending email."""- from ..order.utils import add_gift_card_to_order+ from ..order.utils import add_gift_cards_to_ordercheckout = checkout_info.checkoutorder = Order.objects.filter(checkout_token=checkout.token).first()@@ -427,9 +425,7 @@ def _create_order(additional_warehouse_lookup,)- # Add gift cards to the order- for gift_card in checkout.gift_cards.select_for_update():- total_price_left = add_gift_card_to_order(order, gift_card, total_price_left)+ add_gift_cards_to_order(checkout_info, order, total_price_left, user, app)# assign checkout payments to the ordercheckout.payments.update(order=order)diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex ed3da4ce7f..cb90e50af1 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -1,4 +1,5 @@"""Checkout-related ORM models."""+from datetime import datefrom operator import attrgetterfrom typing import TYPE_CHECKING, Iterable, Optionalfrom uuid import uuid4@@ -124,9 +125,9 @@ class Checkout(ModelWithMetadata):def get_total_gift_cards_balance(self) -> Money:"""Return the total balance of the gift cards assigned to the checkout."""- balance = self.gift_cards.aggregate(models.Sum("current_balance_amount"))[- "current_balance_amount__sum"- ]+ balance = self.gift_cards.active(date=date.today()).aggregate( # type: ignore+ models.Sum("current_balance_amount")+ )["current_balance_amount__sum"]if balance is None:return zero_money(currency=self.currency)return Money(balance, self.currency)diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex f68e4ac445..72d8f4b74e 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -9,6 +9,8 @@ from ...account.models import CustomerEventfrom ...core.exceptions import InsufficientStockfrom ...core.notify_events import NotifyEventTypefrom ...core.taxes import zero_money, zero_taxed_money+from ...giftcard import GiftCardEvents+from ...giftcard.models import GiftCardEventfrom ...order import OrderEventsfrom ...order.models import OrderEventfrom ...order.notifications import get_default_order_payload@@ -638,8 +640,12 @@ def test_create_order_with_gift_card()assert order.gift_cards.count() == 1- assert order.gift_cards.first().current_balance.amount == 0+ gift_card = order.gift_cards.first()+ assert gift_card.current_balance.amount == 0assert order.total.gross == (total_gross_without_gift_cards - gift_cards_balance)+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER+ )def test_create_order_with_gift_card_partial_use(@@ -691,6 +697,9 @@ def test_create_order_with_gift_card_partial_use(assert order.gift_cards.count() > 0assert order.total == zero_taxed_money(order.currency)assert gift_card_balance_before_order == expected_old_balance+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card_used, type=GiftCardEvents.USED_IN_ORDER+ )def test_create_order_with_many_gift_cards(@@ -750,6 +759,12 @@ def test_create_order_with_many_gift_cards(assert price_without_gift_card.gross.amount == (gift_cards_balance_before_order + order.total.gross.amount)+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card_created_by_staff, type=GiftCardEvents.USED_IN_ORDER+ )+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER+ )def test_note_in_created_order(checkout_with_item, address, customer_user):diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 829299dffb..777cdb89d5 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -1,9 +1,15 @@from datetime import date, timedeltaimport pytest+from dateutil.relativedelta import relativedelta+from django.utils import timezonefrom ...core.utils.promo_code import InvalidPromoCode-from ..utils import add_gift_card_code_to_checkout, remove_gift_card_code_from_checkout+from ..utils import (+ add_gift_card_code_to_checkout,+ calculate_expiry_date,+ remove_gift_card_code_from_checkout,+)def test_add_gift_card_code_to_checkout(checkout, gift_card):@@ -121,3 +127,35 @@ def test_remove_gift_card_code_from_checkout_no_checkout_gift_cards(# thenassert checkout.gift_cards.count() == 0+++ "period_type, period", [("years", 5), ("months", 13), ("days", 100)]+)+def test_calculate_expiry_settings(period_type, period, gift_card_expiry_period):+ # given+ gift_card_expiry_period.expiry_period_type = period_type.rstrip("s")+ gift_card_expiry_period.expiry_period = period+ gift_card_expiry_period.save(update_fields=["expiry_period_type", "expiry_period"])++ # when+ expiry_date = calculate_expiry_date(gift_card_expiry_period)++ # then+ assert expiry_date == timezone.now().date() + relativedelta(**{period_type: period})+++def test_calculate_expiry_settings_for_never_expire_gift_card(gift_card):+ # when+ expiry_date = calculate_expiry_date(gift_card)++ # then+ assert expiry_date is None+++def test_calculate_expiry_settings_for_expire_date_gift_card(gift_card_expiry_date):+ # when+ expiry_date = calculate_expiry_date(gift_card_expiry_date)++ # then+ assert expiry_date is Nonediff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 40b70b5db6..cdd26decd2 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -1,7 +1,11 @@from datetime import date+from dateutil.relativedelta import relativedelta+from django.utils import timezone+from ..checkout.models import Checkoutfrom ..core.utils.promo_code import InvalidPromoCode+from . import GiftCardExpiryTypefrom .models import GiftCard@@ -49,3 +53,16 @@ def activate_gift_card(gift_card: GiftCard):if not gift_card.is_active:gift_card.is_active = Truegift_card.save(update_fields=["is_active"])+++def calculate_expiry_date(gift_card: GiftCard):+ """Calculate gift card expiry date for gift card with expiry period settings.++ Return None for gift card with different expiry settings.+ """+ today = timezone.now().date()+ expiry_date = None+ if gift_card.expiry_type == GiftCardExpiryType.EXPIRY_PERIOD:+ time_delta = {f"{gift_card.expiry_period_type}s": gift_card.expiry_period}+ expiry_date = today + relativedelta(**time_delta) # type: ignore+ return expiry_datediff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 5af047176c..50ec473ee5 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -12,6 +12,8 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.models import Checkoutfrom ....core.exceptions import InsufficientStock, InsufficientStockDatafrom ....core.taxes import zero_money, zero_taxed_money+from ....giftcard import GiftCardEvents+from ....giftcard.models import GiftCardEventfrom ....order import OrderOrigin, OrderStatusfrom ....order.models import Orderfrom ....payment import ChargeStatus, PaymentError, TransactionKind@@ -266,6 +268,9 @@ def test_checkout_complete(gift_card.refresh_from_db()assert gift_card.current_balance == zero_money(gift_card.currency)assert gift_card.last_used_on+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.USED_IN_ORDER+ )assert not Checkout.objects.filter(pk=checkout.pkdiff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.pyindex d474855aa7..9c47440a58 100644--- a/saleor/graphql/giftcard/types.py+++ b/saleor/graphql/giftcard/types.py@@ -30,7 +30,6 @@ class GiftCardEventBalance(graphene.ObjectType):initial_balance = graphene.Field(Money,description="Initial balance of the gift card.",- required=True,)current_balance = graphene.Field(Money,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2a4606e18a..f5f6cc524a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2356,7 +2356,7 @@ type GiftCardEvent implements Node {}type GiftCardEventBalance {- initialBalance: Money!+ initialBalance: MoneycurrentBalance: Money!oldInitialBalance: MoneyoldCurrentBalance: Moneydiff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex bede997665..be5be461a0 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -2,13 +2,19 @@ from decimal import Decimalfrom unittest.mock import Mockimport pytest+from dateutil.relativedelta import relativedelta+from django.utils import timezonefrom prices import Money, TaxedMoney+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ...giftcard import GiftCardEvents+from ...giftcard.models import GiftCardEventfrom ...plugins.manager import get_plugins_managerfrom .. import OrderLineData, OrderStatusfrom ..events import OrderEventsfrom ..models import Order, OrderEventfrom ..utils import (+ add_gift_cards_to_order,add_variant_to_order,change_order_line_quantity,get_valid_shipping_methods_for_order,@@ -275,3 +281,68 @@ def test_add_variant_to_order(order, customer_user, variant):assert line.undiscounted_unit_price == unit_priceassert line.undiscounted_total_price == total_priceassert line.tax_rate == tax_rate+++def test_add_gift_cards_to_order(+ checkout_with_item, gift_card, gift_card_expiry_period, order, staff_user+):+ # given+ checkout = checkout_with_item+ checkout.gift_cards.add(gift_card, gift_card_expiry_period)+ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ # when+ add_gift_cards_to_order(+ checkout_info, order, Money(20, gift_card.currency), staff_user, None+ )++ # then+ gift_card.refresh_from_db()+ gift_card_expiry_period.refresh_from_db()+ assert gift_card.current_balance_amount == 0+ assert gift_card_expiry_period.current_balance_amount == 0++ gift_card_events = GiftCardEvent.objects.filter(gift_card_id=gift_card.id)+ assert gift_card_events.count() == 1+ gift_card_event = gift_card_events[0]+ assert gift_card_event.type == GiftCardEvents.USED_IN_ORDER+ assert gift_card_event.user == staff_user+ assert gift_card_event.app is None+ assert gift_card_event.parameters == {+ "balance": {+ "currency": "USD",+ "current_balance": "0",+ "old_current_balance": "10.000",+ },+ "order_id": order.id,+ }++ gift_card_expiry_period_events = GiftCardEvent.objects.filter(+ gift_card_id=gift_card_expiry_period.id+ )+ assert len(gift_card_expiry_period_events) == 2+ order_created_event = gift_card_expiry_period_events.get(+ type=GiftCardEvents.USED_IN_ORDER+ )+ assert order_created_event.user == staff_user+ assert order_created_event.app is None+ assert order_created_event.parameters == {+ "balance": {+ "currency": "USD",+ "current_balance": "0",+ "old_current_balance": "10.000",+ },+ "order_id": order.id,+ }+ expiry_date_set_event = gift_card_expiry_period_events.get(+ type=GiftCardEvents.EXPIRY_DATE_SET+ )+ assert expiry_date_set_event.user == staff_user+ assert expiry_date_set_event.app is None+ assert expiry_date_set_event.parameters == {+ "expiry": {+ "expiry_date": (timezone.now().date() + relativedelta(years=2)).isoformat()+ }+ }diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex c2a2309e08..f2e9da2c10 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -14,6 +14,9 @@ from ..core.weight import zero_weightfrom ..discount import DiscountValueType, OrderDiscountTypefrom ..discount.models import NotApplicable, OrderDiscount, Voucher, VoucherTypefrom ..discount.utils import get_products_voucher_discount, validate_voucher_in_order+from ..giftcard import events as gift_card_events+from ..giftcard.models import GiftCard+from ..giftcard.utils import calculate_expiry_datefrom ..order import FulfillmentStatus, OrderLineData, OrderStatusfrom ..order.models import Order, OrderLinefrom ..product.utils.digital_products import get_default_digital_content_settings@@ -29,6 +32,10 @@ from ..warehouse.models import Warehousefrom . import eventsif TYPE_CHECKING:+ from datetime import date++ from ..app.models import App+ from ..checkout.fetch import CheckoutInfofrom ..plugins.manager import PluginsManager@@ -400,22 +407,76 @@ def add_variant_to_order(return line-def add_gift_card_to_order(order, gift_card, total_price_left):- """Add gift card to order.+def add_gift_cards_to_order(+ checkout_info: "CheckoutInfo",+ order: Order,+ total_price_left: Money,+ user: Optional[User],+ app: Optional["App"],+):+ order_gift_cards = []+ gift_cards_to_update = []+ expiry_date_data: List[Tuple[int, "date"]] = []+ balance_data: List[Tuple[GiftCard, float]] = []+ used_by_user = checkout_info.user+ used_by_email = checkout_info.get_customer_email()+ for gift_card in checkout_info.checkout.gift_cards.select_for_update():+ if total_price_left > zero_money(total_price_left.currency):+ order_gift_cards.append(gift_card)++ update_gift_card_balance(gift_card, total_price_left, balance_data)++ # set user and expiry date value when gift card is used for the first time+ set_gift_card_user_and_expiry_date(+ gift_card, used_by_user, used_by_email, expiry_date_data+ )- Return a total price left after applying the gift cards.- """- if total_price_left > zero_money(total_price_left.currency):- order.gift_cards.add(gift_card)- if total_price_left < gift_card.current_balance:- gift_card.current_balance = gift_card.current_balance - total_price_left- total_price_left = zero_money(total_price_left.currency)- else:- total_price_left = total_price_left - gift_card.current_balance- gift_card.current_balance_amount = 0- gift_card.last_used_on = timezone.now()- gift_card.save(update_fields=["current_balance_amount", "last_used_on"])- return total_price_left+ gift_card.last_used_on = timezone.now()+ gift_cards_to_update.append(gift_card)++ order.gift_cards.add(*order_gift_cards)+ update_fields = [+ "current_balance_amount",+ "last_used_on",+ "used_by",+ "used_by_email",+ ]+ if expiry_date_data:+ update_fields.append("expiry_date")+ GiftCard.objects.bulk_update(gift_cards_to_update, update_fields)+ gift_card_events.gift_cards_used_in_order(balance_data, order.id, user, app)+ if expiry_date_data:+ gift_card_events.gift_cards_expiry_date_set(expiry_date_data, user, app)+++def update_gift_card_balance(+ gift_card: GiftCard,+ total_price_left: Money,+ balance_data: List[Tuple[GiftCard, float]],+):+ previous_balance = gift_card.current_balance+ if total_price_left < gift_card.current_balance:+ gift_card.current_balance = gift_card.current_balance - total_price_left+ total_price_left = zero_money(total_price_left.currency)+ else:+ total_price_left = total_price_left - gift_card.current_balance+ gift_card.current_balance_amount = 0+ balance_data.append((gift_card, previous_balance.amount))+++def set_gift_card_user_and_expiry_date(+ gift_card: GiftCard,+ used_by_user: Optional[User],+ used_by_email: str,+ expiry_date_data: List[Tuple[int, "date"]],+):+ if gift_card.used_by_email is None:+ gift_card.used_by = used_by_user+ gift_card.used_by_email = used_by_email+ expiry_date = calculate_expiry_date(gift_card)+ if expiry_date is not None:+ gift_card.expiry_date = expiry_date+ expiry_date_data.append((gift_card.id, expiry_date))def _update_allocations_for_line(