Skip to content

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

Add possibility to create order with gift cards

fowczarekf6140ae9be36
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 7ebbfb0814..966389f84f 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -74,7 +74,7 @@ class Checkout(models.Model):
discount_name = models.CharField(max_length=255, blank=True, null=True)
translated_discount_name = models.CharField(max_length=255, blank=True, null=True)
voucher_code = models.CharField(max_length=12, blank=True, null=True)
- gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="gift_cards")
+ gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts")
objects = CheckoutQueryset.as_manager()
@@ -106,12 +106,18 @@ class Checkout(models.Model):
subtotals = (line.get_total(discounts, taxes) for line in self)
return sum(subtotals, ZERO_TAXED_MONEY)
- def get_total(self, discounts=None, taxes=None):
- """Return the total cost of the checkout."""
- total = (
+ def get_total_without_gift_cards(self, discounts=None, taxes=None):
+ """Return the total cost of the checkout without gift cards."""
+ return (
self.get_subtotal(discounts, taxes)
+ self.get_shipping_price(taxes)
- self.discount_amount
+ )
+
+ def get_total(self, discounts=None, taxes=None):
+ """Return the total cost of the checkout."""
+ total = (
+ self.get_total_without_gift_cards(discounts, taxes)
- self.get_total_gift_cards_balance()
)
return max(total, ZERO_TAXED_MONEY)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 02e9f00525..ca4a29f355 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -960,6 +960,19 @@ def _process_user_data_for_order(checkout):
}
+def validate_gift_cards(checkout: Checkout):
+ """Check if all gift cards assigned to checkout are available."""
+ if (
+ not checkout.gift_cards.count()
+ == checkout.gift_cards.active(date=date.today()).count()
+ ):
+ msg = pgettext(
+ "Gift card not applicable",
+ "Gift card expired in meantime. Order placement aborted.",
+ )
+ raise NotApplicable(msg)
+
+
@transaction.atomic
def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user: User):
"""Create an order from the checkout.
@@ -973,7 +986,7 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user:
Current user's language is saved in the order so we can later determine
which language to use when sending email.
"""
- from ..order.utils import add_variant_to_order
+ from ..order.utils import add_gift_card_to_order, add_variant_to_order
order = Order.objects.filter(checkout_token=checkout.token).first()
if order is not None:
@@ -991,12 +1004,20 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user:
}
)
+ # validate checkout gift cards
+ validate_gift_cards(checkout)
+
order = Order.objects.create(**order_data, checkout_token=checkout.token)
# create order lines from checkout lines
for line in checkout:
add_variant_to_order(order, line.variant, line.quantity, discounts, taxes)
+ # assign gift cards to the order
+ total_price_left = checkout.get_total_without_gift_cards().gross
+ for gift_card in checkout.gift_cards.select_for_update():
+ total_price_left = add_gift_card_to_order(order, gift_card, total_price_left)
+
# assign checkout payments to the order
checkout.payments.update(order=order)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index cbd716c54f..3094df0753 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -20,6 +20,7 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.utils.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
+from ..giftcard.models import GiftCard
from ..payment import ChargeStatus, TransactionKind
from ..shipping.models import ShippingMethod
from . import FulfillmentStatus, OrderEvents, OrderStatus
@@ -126,6 +127,7 @@ class Order(models.Model):
voucher = models.ForeignKey(
Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULL
)
+ gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="orders")
discount_amount = MoneyField(
currency=settings.DEFAULT_CURRENCY,
max_digits=settings.DEFAULT_MAX_DIGITS,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 64b3849c9e..7eb06a53c6 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -290,6 +290,24 @@ def add_variant_to_order(
return line
+def add_gift_card_to_order(order, gift_card, total_price_left):
+ """Add gift card to order.
+
+ Return a total price left after applying the gift cards.
+ """
+ if total_price_left > ZERO_MONEY:
+ 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
+ gift_card.save(update_fields=["current_balance"])
+ else:
+ total_price_left = total_price_left - gift_card.current_balance
+ gift_card.current_balance = 0
+ gift_card.save(update_fields=["current_balance"])
+ return total_price_left
+
+
def change_order_line_quantity(user, line, old_quantity, new_quantity):
"""Change the quantity of ordered items in a order line."""
if new_quantity: