Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Create gift card fulfillments when completing checkout with gift card lines
IKarbowiakc26c438886c5
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 087ba9e5d8..20e2377706 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -24,7 +24,7 @@ from ..discount.utils import (remove_voucher_usage_by_customer,)from ..giftcard.models import GiftCard-from ..giftcard.utils import create_non_shippable_gift_cards+from ..giftcard.utils import fulfill_non_shippable_gift_cardsfrom ..graphql.checkout.utils import (prepare_insufficient_stock_checkout_validation_error,)@@ -439,7 +439,7 @@ def _create_order(order.save()if site_settings.automatically_fulfill_non_shippable_gift_card:- create_non_shippable_gift_cards(+ fulfill_non_shippable_gift_cards(order, order_lines, site_settings, user, app, manager)diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex 6664c406fc..2bf89fcbec 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -22,6 +22,7 @@ class CheckoutErrorCode(Enum):TAX_ERROR = "tax_error"UNIQUE = "unique"VOUCHER_NOT_APPLICABLE = "voucher_not_applicable"+ GIFT_CARD_NOT_APPLICABLE = "gift_card_not_applicable"ZERO_QUANTITY = "zero_quantity"MISSING_CHANNEL_SLUG = "missing_channel_slug"CHANNEL_INACTIVE = "channel_inactive"diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 81bc5d1641..9e4ef54e42 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -1,20 +1,24 @@from datetime import date, timedelta-from unittest.mock import patch+from unittest.mock import ANY, patchimport pytestfrom dateutil.relativedelta import relativedelta+from django.core.exceptions import ValidationErrorfrom django.utils import timezonefrom ...core import TimePeriodTypefrom ...core.utils.promo_code import InvalidPromoCode+from ...order.models import OrderLinefrom ...plugins.manager import get_plugins_managerfrom ...site import GiftCardSettingsExpiryType+from ...warehouse.models import Allocationfrom .. import GiftCardEventsfrom ..models import GiftCardEventfrom ..utils import (add_gift_card_code_to_checkout,calculate_expiry_date,- create_non_shippable_gift_cards,+ fulfill_gift_card_lines,+ fulfill_non_shippable_gift_cards,get_gift_card_lines,get_non_shippable_gift_card_lines,gift_cards_create,@@ -416,14 +420,17 @@ def test_get_non_shippable_gift_card_lines_no_gift_card_lines(assert not gift_card_lines+@patch("saleor.giftcard.utils.create_fulfillments")@patch("saleor.giftcard.utils.gift_cards_create")-def test_create_non_shippable_gift_cards(+def test_fulfill_non_shippable_gift_cards(gift_cards_create_mock,+ create_fulfillments_mock,order,gift_card_shippable_order_line,gift_card_non_shippable_order_line,site_settings,staff_user,+ warehouse,):# givenmanager = get_plugins_manager()@@ -433,7 +440,7 @@ def test_create_non_shippable_gift_cards(}# when- create_non_shippable_gift_cards(+ fulfill_non_shippable_gift_cards(order, order_lines, site_settings, staff_user, None, manager)@@ -447,3 +454,138 @@ def test_create_non_shippable_gift_cards(assert args[4] == staff_userassert args[5] is Noneassert args[6] == manager++ fulfillment_lines_for_warehouses = {+ str(warehouse.pk): [+ {+ "order_line": gift_card_non_shippable_order_line,+ "quantity": gift_card_non_shippable_order_line.quantity,+ },+ ]+ }++ create_fulfillments_mock.assert_called_once_with(+ staff_user,+ None,+ order,+ fulfillment_lines_for_warehouses,+ ANY,+ notify_customer=True,+ )+++@patch("saleor.giftcard.utils.create_fulfillments")+@patch("saleor.giftcard.utils.gift_cards_create")+def test_fulfill_non_shippable_gift_cards_line_with_allocation(+ gift_cards_create_mock,+ create_fulfillments_mock,+ order,+ gift_card_shippable_order_line,+ gift_card_non_shippable_order_line,+ site_settings,+ staff_user,+ warehouse,+):+ # given+ manager = get_plugins_manager()+ order_lines = [gift_card_shippable_order_line, gift_card_non_shippable_order_line]+ quantities = {+ gift_card_non_shippable_order_line.pk: 1,+ }++ order = gift_card_non_shippable_order_line.order+ non_shippable_variant = gift_card_non_shippable_order_line.variant+ non_shippable_variant.track_inventory = True+ non_shippable_variant.save(update_fields=["track_inventory"])++ stock = non_shippable_variant.stocks.first()+ Allocation.objects.create(+ order_line=gift_card_non_shippable_order_line,+ stock=stock,+ quantity_allocated=gift_card_non_shippable_order_line.quantity,+ )++ # when+ fulfill_non_shippable_gift_cards(+ order, order_lines, site_settings, staff_user, None, manager+ )++ # then+ gift_cards_create_mock.assert_called_once()+ args, kwargs = gift_cards_create_mock.call_args+ assert args[0] == order+ assert {line.pk for line in args[1]} == {gift_card_non_shippable_order_line.pk}+ assert args[2] == quantities+ assert args[3] == site_settings+ assert args[4] == staff_user+ assert args[5] is None+ assert args[6] == manager++ fulfillment_lines_for_warehouses = {+ str(stock.warehouse.pk): [+ {+ "order_line": gift_card_non_shippable_order_line,+ "quantity": gift_card_non_shippable_order_line.quantity,+ },+ ]+ }++ create_fulfillments_mock.assert_called_once_with(+ staff_user,+ None,+ order,+ fulfillment_lines_for_warehouses,+ ANY,+ notify_customer=True,+ )+++def test_fulfill_gift_card_lines(+ staff_user, gift_card_non_shippable_order_line, gift_card_shippable_order_line+):+ # given+ manager = get_plugins_manager()+ order = gift_card_non_shippable_order_line.order+ non_shippable_variant = gift_card_non_shippable_order_line.variant+ non_shippable_variant.track_inventory = True+ non_shippable_variant.save(update_fields=["track_inventory"])++ Allocation.objects.create(+ order_line=gift_card_non_shippable_order_line,+ stock=non_shippable_variant.stocks.first(),+ quantity_allocated=gift_card_non_shippable_order_line.quantity,+ )++ lines = OrderLine.objects.filter(+ pk__in=[+ gift_card_non_shippable_order_line.pk,+ gift_card_shippable_order_line.pk,+ ]+ )++ # when+ fulfillments = fulfill_gift_card_lines(lines, staff_user, None, order, manager)++ # then+ assert len(fulfillments) == 1+ assert fulfillments[0].lines.count() == len(lines)+++def test_fulfill_gift_card_lines_lack_of_stock(+ staff_user, gift_card_non_shippable_order_line, gift_card_shippable_order_line+):+ # given+ manager = get_plugins_manager()+ order = gift_card_non_shippable_order_line.order+ gift_card_non_shippable_order_line.variant.stocks.all().delete()++ lines = OrderLine.objects.filter(+ pk__in=[+ gift_card_non_shippable_order_line.pk,+ gift_card_shippable_order_line.pk,+ ]+ )++ # when+ with pytest.raises(ValidationError):+ fulfill_gift_card_lines(lines, staff_user, None, order, manager)diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex a0d39edd0f..fc70e5c580 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -1,13 +1,17 @@+from collections import defaultdictfrom datetime import datefrom typing import TYPE_CHECKING, Dict, Iterable, Optionalfrom dateutil.relativedelta import relativedelta+from django.core.exceptions import ValidationErrorfrom django.db.models.expressions import Exists, OuterReffrom django.utils import timezone+from ..checkout.error_codes import CheckoutErrorCodefrom ..checkout.models import Checkoutfrom ..core.utils.promo_code import InvalidPromoCode, generate_promo_codefrom ..core.utils.validators import user_is_valid+from ..order.actions import create_fulfillmentsfrom ..order.models import OrderLinefrom ..product import ProductTypeKindfrom ..product.models import Product, ProductType, ProductVariant@@ -17,6 +21,8 @@ from .models import GiftCardfrom .notifications import send_gift_card_notificationif TYPE_CHECKING:+ from django.db.models import QuerySet+from ..account.models import Userfrom ..app.models import Appfrom ..order.models import Order@@ -70,7 +76,7 @@ def activate_gift_card(gift_card: GiftCard):gift_card.save(update_fields=["is_active"])-def create_non_shippable_gift_cards(+def fulfill_non_shippable_gift_cards(order: "Order",order_lines: Iterable[OrderLine],settings: "SiteSettings",@@ -84,6 +90,7 @@ def create_non_shippable_gift_cards(gift_card_lines = get_non_shippable_gift_card_lines(line_pks)if not gift_card_lines:return+ fulfill_gift_card_lines(gift_card_lines, requestor_user, app, order, manager)quantities = {line.pk: line.quantity for line in gift_card_lines}return gift_cards_create(order, gift_card_lines, quantities, settings, requestor_user, app, manager@@ -113,6 +120,48 @@ def get_gift_card_lines(line_pks: Iterable[int]):return gift_card_lines+def fulfill_gift_card_lines(+ gift_card_lines: "QuerySet",+ requestor_user: Optional["User"],+ app: Optional["App"],+ order: "Order",+ manager: "PluginsManager",+):+ lines_for_warehouses = defaultdict(list)+ channel_slug = order.channel.slug+ for line in gift_card_lines.prefetch_related(+ "allocations__stock", "variant__stocks"+ ):+ if allocations := line.allocations.all():+ for allocation in allocations:+ quantity = allocation.quantity_allocated+ if quantity > 0:+ warehouse_pk = str(allocation.stock.warehouse_id)+ lines_for_warehouses[warehouse_pk].append(+ {"order_line": line, "quantity": quantity}+ )+ else:+ stock = line.variant.stocks.for_channel(channel_slug).first()+ if not stock:+ raise ValidationError(+ "Lack of gift card stock for checkout channel.",+ code=CheckoutErrorCode.GIFT_CARD_NOT_APPLICABLE.value,+ )+ warehouse_pk = str(stock.warehouse_id)+ lines_for_warehouses[warehouse_pk].append(+ {"order_line": line, "quantity": line.quantity}+ )++ return create_fulfillments(+ requestor_user,+ app,+ order,+ dict(lines_for_warehouses),+ manager,+ notify_customer=True,+ )++def gift_cards_create(order: "Order",gift_card_lines: Iterable["OrderLine"],diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex fba31ae9ca..8b65679fbc 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -15,7 +15,7 @@ from ....core.taxes import zero_money, zero_taxed_moneyfrom ....giftcard import GiftCardEventsfrom ....giftcard.models import GiftCard, GiftCardEventfrom ....order import OrderOrigin, OrderStatus-from ....order.models import Order+from ....order.models import Fulfillment, Orderfrom ....payment import ChargeStatus, PaymentError, TransactionKindfrom ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPINGfrom ....payment.interface import GatewayResponse@@ -326,7 +326,7 @@ def test_checkout_complete_gift_card_bought(assert Order.objects.count() == orders_count + 1order = Order.objects.first()- assert order.status == OrderStatus.UNFULFILLED+ assert order.status == OrderStatus.PARTIALLY_FULFILLEDgift_card = GiftCard.objects.get()assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)@@ -334,6 +334,7 @@ def test_checkout_complete_gift_card_bought(gift_card=gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER)order_confirmed_mock.assert_called_once_with(order)+ assert Fulfillment.objects.count() == 1def test_checkout_complete_with_variant_without_price(diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 27b5d3a6e9..4fa658e5e6 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1111,6 +1111,7 @@ enum CheckoutErrorCode {TAX_ERRORUNIQUEVOUCHER_NOT_APPLICABLE+ GIFT_CARD_NOT_APPLICABLEZERO_QUANTITYMISSING_CHANNEL_SLUGCHANNEL_INACTIVEdiff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 104cb528d6..c86350b70e 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -210,7 +210,7 @@ def order_returned(@traced_atomic_transaction()def order_fulfilled(fulfillments: List["Fulfillment"],- user: "User",+ user: Optional["User"],app: Optional["App"],fulfillment_lines: List["FulfillmentLine"],manager: "PluginsManager",@@ -607,7 +607,7 @@ def _create_fulfillment_lines(@traced_atomic_transaction()def create_fulfillments(- user: "User",+ user: Optional["User"],app: Optional["App"],order: "Order",fulfillment_lines_for_warehouses: Dict,