Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Create gift cards when completing checkout with gift card items
IKarbowiak20a2892579a3
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex e77f254e79..087ba9e5d8 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -24,6 +24,7 @@ from ..discount.utils import (remove_voucher_usage_by_customer,)from ..giftcard.models import GiftCard+from ..giftcard.utils import create_non_shippable_gift_cardsfrom ..graphql.checkout.utils import (prepare_insufficient_stock_checkout_validation_error,)@@ -437,6 +438,11 @@ def _create_order(order.update_total_paid()order.save()+ if site_settings.automatically_fulfill_non_shippable_gift_card:+ create_non_shippable_gift_cards(+ order, order_lines, site_settings, user, app, manager+ )+transaction.on_commit(lambda: order_created(order=order, user=user, app=app, manager=manager))diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 72d8f4b74e..ad1c525978 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -10,7 +10,7 @@ from ...core.exceptions import InsufficientStockfrom ...core.notify_events import NotifyEventTypefrom ...core.taxes import zero_money, zero_taxed_moneyfrom ...giftcard import GiftCardEvents-from ...giftcard.models import GiftCardEvent+from ...giftcard.models import GiftCard, GiftCardEventfrom ...order import OrderEventsfrom ...order.models import OrderEventfrom ...order.notifications import get_default_order_payload@@ -767,6 +767,182 @@ def test_create_order_with_many_gift_cards()[email protected]("is_anonymous_user", (True, False))+def test_create_order_gift_card_bought(+ checkout_with_gift_card_items,+ customer_user,+ shipping_method,+ is_anonymous_user,+ non_shippable_gift_card_product,+):+ checkout_user = None if is_anonymous_user else customer_user+ checkout = checkout_with_gift_card_items+ checkout.user = checkout_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ shipping_price = calculations.checkout_shipping_price(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount++ order = _create_order(+ checkout_info=checkout_info,+ order_data=_prepare_order_data(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ discounts=None,+ ),+ user=customer_user if not is_anonymous_user else AnonymousUser(),+ app=None,+ manager=manager,+ )++ assert order.total.gross == total_gross+ gift_card = GiftCard.objects.get()+ assert (+ gift_card.initial_balance+ == order.lines.get(+ variant=non_shippable_gift_card_product.variants.first()+ ).unit_price_gross+ )+ assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER+ )++[email protected]("is_anonymous_user", (True, False))+def test_create_order_gift_card_bought_only_shippable_gift_card(+ checkout,+ shippable_gift_card_product,+ customer_user,+ shipping_method,+ is_anonymous_user,+):+ checkout_user = None if is_anonymous_user else customer_user+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ shippable_variant = shippable_gift_card_product.variants.get()+ add_variant_to_checkout(checkout_info, shippable_variant, 2)++ checkout.user = checkout_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ shipping_price = calculations.checkout_shipping_price(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount++ order = _create_order(+ checkout_info=checkout_info,+ order_data=_prepare_order_data(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ discounts=None,+ ),+ user=customer_user if not is_anonymous_user else AnonymousUser(),+ app=None,+ manager=manager,+ )++ assert order.total.gross == total_gross+ assert not GiftCard.objects.all()++[email protected]("is_anonymous_user", (True, False))+def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(+ site_settings,+ checkout_with_gift_card_items,+ customer_user,+ shipping_method,+ is_anonymous_user,+ non_shippable_gift_card_product,+):+ site_settings.automatically_fulfill_non_shippable_gift_card = False+ site_settings.save(update_fields=["automatically_fulfill_non_shippable_gift_card"])++ checkout_user = None if is_anonymous_user else customer_user+ checkout = checkout_with_gift_card_items+ checkout.user = checkout_user+ checkout.billing_address = customer_user.default_billing_address+ checkout.shipping_address = customer_user.default_billing_address+ checkout.shipping_method = shipping_method+ checkout.tracking_code = "tracking_code"+ checkout.redirect_url = "https://www.example.com"+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ shipping_price = calculations.checkout_shipping_price(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ total_gross = subtotal.gross + shipping_price.gross - checkout.discount++ order = _create_order(+ checkout_info=checkout_info,+ order_data=_prepare_order_data(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ discounts=None,+ ),+ user=customer_user if not is_anonymous_user else AnonymousUser(),+ app=None,+ manager=manager,+ )++ assert order.total.gross == total_gross+ assert not GiftCard.objects.all()++def test_note_in_created_order(checkout_with_item, address, customer_user):checkout_with_item.shipping_address = addresscheckout_with_item.note = "test_note"diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 41238e866f..81bc5d1641 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -14,6 +14,9 @@ from ..models import GiftCardEventfrom ..utils import (add_gift_card_code_to_checkout,calculate_expiry_date,+ create_non_shippable_gift_cards,+ get_gift_card_lines,+ get_non_shippable_gift_card_lines,gift_cards_create,remove_gift_card_code_from_checkout,)@@ -342,3 +345,105 @@ def test_gift_cards_create_multiple_quantity(== quantity)assert send_notification_mock.call_count == 3+++def test_get_gift_card_lines(+ gift_card_non_shippable_order_line, gift_card_shippable_order_line, order_line+):+ # given+ ids = [+ line.pk+ for line in [+ gift_card_non_shippable_order_line,+ gift_card_shippable_order_line,+ order_line,+ ]+ ]++ # when+ gift_card_lines = get_gift_card_lines(ids)++ # then+ assert set(gift_card_lines) == {+ gift_card_non_shippable_order_line,+ gift_card_shippable_order_line,+ }+++def test_get_gift_card_lines_no_gift_card_lines(+ order_line_with_one_allocation, order_line+):+ # given+ ids = [line.pk for line in [order_line_with_one_allocation, order_line]]++ # when+ gift_card_lines = get_gift_card_lines(ids)++ # then+ assert not gift_card_lines+++def test_get_non_shippable_gift_card_lines(+ gift_card_non_shippable_order_line, gift_card_shippable_order_line, order_line+):+ # given+ ids = [+ line.pk+ for line in [+ gift_card_non_shippable_order_line,+ gift_card_shippable_order_line,+ order_line,+ ]+ ]++ # when+ gift_card_lines = get_non_shippable_gift_card_lines(ids)++ # then+ assert set(gift_card_lines) == {gift_card_non_shippable_order_line}+++def test_get_non_shippable_gift_card_lines_no_gift_card_lines(+ order_line_with_one_allocation, order_line+):+ # given+ ids = [line.pk for line in [order_line_with_one_allocation, order_line]]++ # when+ gift_card_lines = get_gift_card_lines(ids)++ # then+ assert not gift_card_lines+++@patch("saleor.giftcard.utils.gift_cards_create")+def test_create_non_shippable_gift_cards(+ gift_cards_create_mock,+ order,+ gift_card_shippable_order_line,+ gift_card_non_shippable_order_line,+ site_settings,+ staff_user,+):+ # 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,+ }++ # when+ create_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] == managerdiff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 85804d92dd..a0d39edd0f 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -2,10 +2,15 @@ from datetime import datefrom typing import TYPE_CHECKING, Dict, Iterable, Optionalfrom dateutil.relativedelta import relativedelta+from django.db.models.expressions import Exists, OuterReffrom django.utils import timezonefrom ..checkout.models import Checkoutfrom ..core.utils.promo_code import InvalidPromoCode, generate_promo_code+from ..core.utils.validators import user_is_valid+from ..order.models import OrderLine+from ..product import ProductTypeKind+from ..product.models import Product, ProductType, ProductVariantfrom ..site import GiftCardSettingsExpiryTypefrom . import eventsfrom .models import GiftCard@@ -14,7 +19,7 @@ from .notifications import send_gift_card_notificationif TYPE_CHECKING:from ..account.models import Userfrom ..app.models import App- from ..order.models import Order, OrderLine+ from ..order.models import Orderfrom ..plugins.manager import PluginsManagerfrom ..site.models import SiteSettings@@ -65,6 +70,49 @@ def activate_gift_card(gift_card: GiftCard):gift_card.save(update_fields=["is_active"])+def create_non_shippable_gift_cards(+ order: "Order",+ order_lines: Iterable[OrderLine],+ settings: "SiteSettings",+ requestor_user: Optional["User"],+ app: Optional["App"],+ manager: "PluginsManager",+):+ if not user_is_valid(requestor_user):+ requestor_user = None+ line_pks = [line.pk for line in order_lines]+ gift_card_lines = get_non_shippable_gift_card_lines(line_pks)+ if not gift_card_lines:+ return+ 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+ )+++def get_non_shippable_gift_card_lines(line_ids: Iterable[int]):+ gift_card_lines = get_gift_card_lines(line_ids)+ gift_card_lines = gift_card_lines.filter(+ is_shipping_required=False,+ )+ return gift_card_lines+++def get_gift_card_lines(line_pks: Iterable[int]):+ product_types = ProductType.objects.filter(kind=ProductTypeKind.GIFT_CARD)+ products = Product.objects.filter(+ Exists(product_types.filter(pk=OuterRef("product_type_id")))+ )+ variants = ProductVariant.objects.filter(+ Exists(products.filter(pk=OuterRef("product_id")))+ )+ gift_card_lines = OrderLine.objects.filter(id__in=line_pks).filter(+ Exists(variants.filter(pk=OuterRef("variant_id")))+ )++ return gift_card_lines++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 50ec473ee5..fba31ae9ca 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -13,7 +13,7 @@ from ....checkout.models import Checkoutfrom ....core.exceptions import InsufficientStock, InsufficientStockDatafrom ....core.taxes import zero_money, zero_taxed_moneyfrom ....giftcard import GiftCardEvents-from ....giftcard.models import GiftCardEvent+from ....giftcard.models import GiftCard, GiftCardEventfrom ....order import OrderOrigin, OrderStatusfrom ....order.models import Orderfrom ....payment import ChargeStatus, PaymentError, TransactionKind@@ -278,6 +278,64 @@ def test_checkout_complete(order_confirmed_mock.assert_called_once_with(order)+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_checkout_complete_gift_card_bought(+ order_confirmed_mock,+ site_settings,+ user_api_client,+ checkout_with_gift_card_items,+ payment_dummy,+ address,+ shipping_method,+):+ checkout = checkout_with_gift_card_items+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.store_value_in_metadata(items={"accepted": "true"})+ checkout.store_value_in_private_metadata(items={"accepted": "false"})+ checkout.save()++ manager = get_plugins_manager()+ lines = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ site_settings.automatically_confirm_all_new_orders = True+ site_settings.automatically_fulfill_non_shippable_gift_card = True+ site_settings.save()++ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ orders_count = Order.objects.count()+ redirect_url = "https://www.example.com"+ variables = {"token": checkout.token, "redirectUrl": redirect_url}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["errors"]++ assert Order.objects.count() == orders_count + 1+ order = Order.objects.first()+ assert order.status == OrderStatus.UNFULFILLED++ gift_card = GiftCard.objects.get()+ assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER+ )+ order_confirmed_mock.assert_called_once_with(order)++def test_checkout_complete_with_variant_without_price(site_settings,user_api_client,diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex deca918cbc..ca989f38e4 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -2,13 +2,12 @@ from collections import defaultdictimport graphenefrom django.core.exceptions import ValidationError-from django.db.models.expressions import Exists, OuterReffrom django.template.defaultfilters import pluralizefrom ....core.exceptions import InsufficientStockfrom ....core.permissions import OrderPermissionsfrom ....core.tracing import traced_atomic_transaction-from ....giftcard.utils import gift_cards_create+from ....giftcard.utils import get_gift_card_lines, gift_cards_createfrom ....order import FulfillmentLineData, FulfillmentStatus, OrderLineDatafrom ....order import models as order_modelsfrom ....order.actions import (@@ -22,8 +21,6 @@ from ....order.actions import ()from ....order.error_codes import OrderErrorCodefrom ....order.notifications import send_fulfillment_update-from ....product import ProductTypeKind-from ....product import models as product_modelsfrom ...core.descriptions import ADDED_IN_31from ...core.mutations import BaseMutationfrom ...core.scalars import PositiveDecimal@@ -229,20 +226,7 @@ class OrderFulfill(BaseMutation):_, pks = resolve_global_ids_to_primary_keys(lines_ids, OrderLine, raise_error=True)- product_types = product_models.ProductType.objects.filter(- kind=ProductTypeKind.GIFT_CARD- ).values("id")- products = product_models.Product.objects.filter(- Exists(product_types.filter(pk=OuterRef("product_type_id")))- )- variants = product_models.ProductVariant.objects.filter(- Exists(products.filter(pk=OuterRef("product_id")))- )- gift_card_lines = order_models.OrderLine.objects.filter(id__in=pks).filter(- Exists(variants.filter(pk=OuterRef("variant_id")))- )-- return gift_card_lines+ return get_gift_card_lines(pks)@classmethod@traced_atomic_transaction()diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 8af9bf814e..6e4e00b5ea 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -440,6 +440,19 @@ def checkout_with_gift_card(checkout_with_item, gift_card):return checkout_with_item+def checkout_with_gift_card_items(+ checkout, non_shippable_gift_card_product, shippable_gift_card_product+):+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ non_shippable_variant = non_shippable_gift_card_product.variants.get()+ shippable_variant = shippable_gift_card_product.variants.get()+ add_variant_to_checkout(checkout_info, non_shippable_variant, 1)+ add_variant_to_checkout(checkout_info, shippable_variant, 2)+ checkout.save()+ return checkout++@pytest.fixturedef checkout_with_voucher_percentage_and_shipping(checkout_with_voucher_percentage, shipping_method, address