Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Create gift cards when fulfilling order
IKarbowiakd1005e3b92f7
diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.pyindex d213baab78..162e8d5007 100644--- a/saleor/giftcard/events.py+++ b/saleor/giftcard/events.py@@ -44,6 +44,24 @@ def gift_card_sent()+def gift_cards_sent(+ gift_cards: Iterable[GiftCard], user: UserType, app: AppType, email: str+):+ if not user_is_valid(user):+ user = None+ gift_cards_events = [+ GiftCardEvent(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.SENT_TO_CUSTOMER,+ parameters={"email": email},+ )+ for gift_card in gift_cards+ ]+ return GiftCardEvent.objects.bulk_create(gift_cards_events)++def gift_card_resent(gift_card_id: int, user_id: Optional[int], app_id: Optional[int], email: str):@@ -236,3 +254,21 @@ def gift_cards_used_in_order(for gift_card, previous_balance in balance_data]return GiftCardEvent.objects.bulk_create(events)+++def gift_cards_bought(+ gift_cards: Iterable[GiftCard], order_id: int, user: UserType, app: AppType+):+ if not user_is_valid(user):+ user = None+ events = [+ GiftCardEvent(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.BOUGHT,+ parameters={"order_id": order_id},+ )+ for gift_card in gift_cards+ ]+ return GiftCardEvent.objects.bulk_create(events)diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 777cdb89d5..1c720fbb7a 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -1,13 +1,18 @@from datetime import date, timedelta+from unittest.mock import patchimport pytestfrom dateutil.relativedelta import relativedeltafrom django.utils import timezonefrom ...core.utils.promo_code import InvalidPromoCode+from ...plugins.manager import get_plugins_manager+from .. import GiftCardEvents+from ..models import GiftCardEventfrom ..utils import (add_gift_card_code_to_checkout,calculate_expiry_date,+ gift_cards_create,remove_gift_card_code_from_checkout,)@@ -159,3 +164,72 @@ def test_calculate_expiry_settings_for_expire_date_gift_card(gift_card_expiry_da# thenassert expiry_date is None+++@patch("saleor.giftcard.utils.send_gift_card_notification")+def test_gift_cards_create(+ send_notification_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]+ user_email = order.user_email++ # when+ gift_cards = gift_cards_create(+ order, order_lines, site_settings, staff_user, None, manager+ )++ # then+ assert len(gift_cards) == len(order_lines)++ shippable_gift_card = gift_cards[0]+ shippable_price = gift_card_shippable_order_line.total_price_gross+ assert shippable_gift_card.initial_balance == shippable_price+ assert shippable_gift_card.current_balance == shippable_price+ assert shippable_gift_card.created_by == order.user+ assert shippable_gift_card.created_by_email == user_email+ assert shippable_gift_card.expiry_type == site_settings.gift_card_expiry_type+ assert shippable_gift_card.expiry_period_type is None+ assert shippable_gift_card.expiry_period is None++ bought_event_for_shippable_card = GiftCardEvent.objects.get(+ gift_card=shippable_gift_card+ )+ assert bought_event_for_shippable_card.user == staff_user+ assert bought_event_for_shippable_card.app is None+ assert bought_event_for_shippable_card.type == GiftCardEvents.BOUGHT+ assert bought_event_for_shippable_card.parameters == {"order_id": order.id}++ non_shippable_gift_card = gift_cards[1]+ non_shippable_price = gift_card_non_shippable_order_line.total_price_gross+ assert non_shippable_gift_card.initial_balance == non_shippable_price+ assert non_shippable_gift_card.current_balance == non_shippable_price+ assert non_shippable_gift_card.created_by == order.user+ assert non_shippable_gift_card.created_by_email == user_email+ assert non_shippable_gift_card.expiry_type == site_settings.gift_card_expiry_type+ assert non_shippable_gift_card.expiry_period_type is None+ assert non_shippable_gift_card.expiry_period is None++ sent_to_customer_event = GiftCardEvent.objects.get(+ gift_card=non_shippable_gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER+ )+ assert sent_to_customer_event.user == staff_user+ assert sent_to_customer_event.app is None+ assert sent_to_customer_event.parameters == {"email": user_email}++ shippable_event = GiftCardEvent.objects.get(+ gift_card=non_shippable_gift_card, type=GiftCardEvents.BOUGHT+ )+ assert shippable_event.user == staff_user+ assert shippable_event.app is None+ assert shippable_event.parameters == {"order_id": order.id}++ send_notification_mock.assert_called_once_with(+ staff_user, None, user_email, non_shippable_gift_card, manager+ )diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex cdd26decd2..6c98cae6a1 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -1,12 +1,21 @@from datetime import date+from typing import TYPE_CHECKING, Iterable, Optionalfrom dateutil.relativedelta import relativedeltafrom django.utils import timezonefrom ..checkout.models import Checkout-from ..core.utils.promo_code import InvalidPromoCode-from . import GiftCardExpiryType+from ..core.utils.promo_code import InvalidPromoCode, generate_promo_code+from . import GiftCardExpiryType, eventsfrom .models import GiftCard+from .notifications import send_gift_card_notification++if TYPE_CHECKING:+ from ..account.models import User+ from ..app.models import App+ from ..order.models import Order, OrderLine+ from ..plugins.manager import PluginsManager+ from ..site.models import SiteSettingsdef add_gift_card_code_to_checkout(@@ -66,3 +75,59 @@ def calculate_expiry_date(gift_card: GiftCard):time_delta = {f"{gift_card.expiry_period_type}s": gift_card.expiry_period}expiry_date = today + relativedelta(**time_delta) # type: ignorereturn expiry_date+++def gift_cards_create(+ order: "Order",+ gift_card_lines: Iterable["OrderLine"],+ settings: "SiteSettings",+ requestor_user: Optional["User"],+ app: Optional["App"],+ manager: "PluginsManager",+):+ """Create purchased gift cards."""+ customer_user = order.user+ user_email = order.user_email+ gift_cards = []+ non_shippable_gift_cards = []+ for order_line in gift_card_lines:+ price = order_line.total_price_gross+ line_gift_cards = [+ GiftCard( # type: ignore+ code=generate_promo_code(),+ initial_balance=price,+ current_balance=price,+ created_by=customer_user,+ created_by_email=user_email,+ product=order_line.variant.product if order_line.variant else None,+ expiry_type=settings.gift_card_expiry_type,+ expiry_period_type=settings.gift_card_expiry_period_type,+ expiry_period=settings.gift_card_expiry_period,+ )+ for _ in range(order_line.quantity)+ ]+ gift_cards.extend(line_gift_cards)+ if not order_line.is_shipping_required:+ non_shippable_gift_cards.extend(line_gift_cards)++ gift_cards = GiftCard.objects.bulk_create(gift_cards)+ events.gift_cards_bought(gift_cards, order.id, requestor_user, app)++ # send to customer all non-shippable gift cards+ send_gift_cards_to_customer(+ non_shippable_gift_cards, user_email, requestor_user, app, manager+ )+ return gift_cards+++def send_gift_cards_to_customer(+ gift_cards: Iterable[GiftCard],+ user_email: str,+ requestor_user: Optional["User"],+ app: Optional["App"],+ manager: "PluginsManager",+):+ for gift_card in gift_cards:+ send_gift_card_notification(requestor_user, app, user_email, gift_card, manager)++ events.gift_cards_sent(gift_cards, requestor_user, app, user_email)diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex da1fdc3da1..a4967a3d57 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -2,10 +2,13 @@ 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 OrderPermissions+from ....core.tracing import traced_atomic_transaction+from ....giftcard.utils import gift_cards_createfrom ....order import FulfillmentLineData, FulfillmentStatus, OrderLineDatafrom ....order import models as order_modelsfrom ....order.actions import (@@ -19,11 +22,14 @@ 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 PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...core.utils import get_duplicated_values+from ...utils import resolve_global_ids_to_primary_keysfrom ...warehouse.types import Warehousefrom ..types import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..utils import prepare_insufficient_stock_order_validation_errors@@ -208,28 +214,63 @@ class OrderFulfill(BaseMutation):)data["order_lines"] = order_lines+ data["gift_card_lines"] = cls.get_gift_card_lines(lines_ids)data["quantities"] = quantities_for_linesdata["lines_for_warehouses"] = lines_for_warehousesreturn data+ @staticmethod+ def get_gift_card_lines(lines_ids):+ _, 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+@classmethod+ @traced_atomic_transaction()def perform_mutation(cls, _root, info, order, **data):order = cls.get_node_or_error(info, order, field="order", only_type=Order)data = data.get("input")cleaned_input = cls.clean_input(info, order, data)- user = info.context.user+ context = info.context+ user = context.user if not context.user.is_anonymous else None+ app = context.app+ manager = context.pluginslines_for_warehouses = cleaned_input["lines_for_warehouses"]notify_customer = cleaned_input.get("notify_customer", True)+ gift_card_lines = cleaned_input["gift_card_lines"]++ gift_cards_create(+ order,+ gift_card_lines,+ context.site.settings,+ user,+ app,+ manager,+ )try:fulfillments = create_fulfillments(user,- info.context.app,+ app,order,dict(lines_for_warehouses),- info.context.plugins,+ manager,notify_customer,approved=info.context.site.settings.fulfillment_auto_approve,)diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex 5bef2e470d..5335ce95ca 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -2,9 +2,10 @@ from unittest.mock import ANY, patchimport grapheneimport pytest-from django.contrib.auth.models import AnonymousUserfrom ....core.exceptions import InsufficientStock, InsufficientStockData+from ....giftcard import GiftCardEvents+from ....giftcard.models import GiftCard, GiftCardEventfrom ....order import OrderStatusfrom ....order.error_codes import OrderErrorCodefrom ....order.events import OrderEvents@@ -136,7 +137,6 @@ def test_order_fulfill(def test_order_fulfill_as_app(mock_create_fulfillments,app_api_client,- staff_user,order_with_lines,permission_manage_orders,warehouse,@@ -178,7 +178,7 @@ def test_order_fulfill_as_app(]}mock_create_fulfillments.assert_called_once_with(- AnonymousUser(),+ None,app_api_client.app,order,fulfillment_lines_for_warehouses,@@ -253,6 +253,164 @@ def test_order_fulfill_many_warehouses()+@patch("saleor.giftcard.utils.send_gift_card_notification")+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")+def test_order_fulfill_with_gift_cards(+ mock_create_fulfillments,+ mock_send_notification,+ staff_api_client,+ staff_user,+ order,+ gift_card_non_shippable_order_line,+ gift_card_shippable_order_line,+ permission_manage_orders,+ warehouse,+):+ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line, order_line2 = (+ gift_card_non_shippable_order_line,+ gift_card_shippable_order_line,+ )+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert not data["errors"]+ gift_cards = GiftCard.objects.all()+ assert gift_cards.count() == 2+ non_shippable_gift_card = gift_cards.get(+ product_id=gift_card_non_shippable_order_line.variant.product_id+ )+ shippable_gift_card = gift_cards.get(+ product_id=gift_card_shippable_order_line.variant.product_id+ )+ assert non_shippable_gift_card.initial_balance.amount == round(+ gift_card_non_shippable_order_line.total_price_gross.amount, 2+ )+ assert non_shippable_gift_card.current_balance.amount == round(+ gift_card_non_shippable_order_line.total_price_gross.amount, 2+ )+ assert shippable_gift_card.initial_balance.amount == round(+ gift_card_shippable_order_line.total_price_gross.amount, 2+ )+ assert shippable_gift_card.current_balance.amount == round(+ gift_card_shippable_order_line.total_price_gross.amount, 2+ )++ assert GiftCardEvent.objects.filter(+ gift_card=shippable_gift_card, type=GiftCardEvents.BOUGHT+ )+ assert GiftCardEvent.objects.filter(+ gift_card=non_shippable_gift_card, type=GiftCardEvents.BOUGHT+ )+ assert GiftCardEvent.objects.filter(+ gift_card=non_shippable_gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER+ )++ fulfillment_lines_for_warehouses = {+ str(warehouse.pk): [+ {"order_line": order_line, "quantity": 1},+ {"order_line": order_line2, "quantity": 1},+ ]+ }+ mock_create_fulfillments.assert_called_once_with(+ staff_user,+ None,+ order,+ fulfillment_lines_for_warehouses,+ ANY,+ True,+ approved=True,+ )++ mock_send_notification.assert_called_once_with(+ staff_user, None, order.user_email, non_shippable_gift_card, ANY+ )+++@patch("saleor.giftcard.utils.send_gift_card_notification")+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")+def test_order_fulfill_with_gift_cards_by_app(+ mock_create_fulfillments,+ mock_send_notification,+ app_api_client,+ order,+ gift_card_shippable_order_line,+ permission_manage_orders,+ warehouse,+):+ query = ORDER_FULFILL_QUERY+ app = app_api_client.app+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line = gift_card_shippable_order_line+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ response = app_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert not data["errors"]+ shippable_gift_card = GiftCard.objects.get()+ assert shippable_gift_card.initial_balance.amount == round(+ gift_card_shippable_order_line.total_price_gross.amount, 2+ )+ assert shippable_gift_card.current_balance.amount == round(+ gift_card_shippable_order_line.total_price_gross.amount, 2+ )++ assert GiftCardEvent.objects.filter(+ gift_card=shippable_gift_card,+ type=GiftCardEvents.BOUGHT,+ user=None,+ app=app_api_client.app,+ )++ fulfillment_lines_for_warehouses = {+ str(warehouse.pk): [+ {"order_line": order_line, "quantity": 1},+ ]+ }+ mock_create_fulfillments.assert_called_once_with(+ None, app, order, fulfillment_lines_for_warehouses, ANY, True, approved=True+ )++ mock_send_notification.assert_not_called++@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")def test_order_fulfill_without_notification(mock_create_fulfillments,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 7c526de1de..8a64aa2152 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -1452,6 +1452,30 @@ def product_type(color_attribute, size_attribute):return product_type+def non_shippable_gift_card_product_type(db):+ product_type = ProductType.objects.create(+ name="Gift card type no shipping",+ slug="gift-card-type-no-shipping",+ kind=ProductTypeKind.GIFT_CARD,+ has_variants=True,+ is_shipping_required=False,+ )+ return product_type+++def shippable_gift_card_product_type(db):+ product_type = ProductType.objects.create(+ name="Gift card type with shipping",+ slug="gift-card-type-with-shipping",+ kind=ProductTypeKind.GIFT_CARD,+ has_variants=True,+ is_shipping_required=True,+ )+ return product_type++@pytest.fixturedef product_type_with_rich_text_attribute(rich_text_attribute, color_attribute, size_attribute@@ -1520,6 +1544,80 @@ def product(product_type, category, warehouse, channel_USD):return product+def shippable_gift_card_product(+ shippable_gift_card_product_type, category, warehouse, channel_USD+):+ product_type = shippable_gift_card_product_type++ product = Product.objects.create(+ name="Shippable gift card",+ slug="shippable-gift-card",+ product_type=product_type,+ category=category,+ )+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ discounted_price_amount="100.00",+ currency=channel_USD.currency_code,+ visible_in_listings=True,+ available_for_purchase=datetime.date(1999, 1, 1),+ )++ variant = ProductVariant.objects.create(+ product=product, sku="958", track_inventory=False+ )+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(100),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=1)++ return product+++def non_shippable_gift_card_product(+ non_shippable_gift_card_product_type, category, warehouse, channel_USD+):+ product_type = non_shippable_gift_card_product_type++ product = Product.objects.create(+ name="Non shippable gift card",+ slug="non-shippable-gift-card",+ product_type=product_type,+ category=category,+ )+ ProductChannelListing.objects.create(+ product=product,+ channel=channel_USD,+ is_published=True,+ discounted_price_amount="200.00",+ currency=channel_USD.currency_code,+ visible_in_listings=True,+ available_for_purchase=datetime.date(1999, 1, 1),+ )++ variant = ProductVariant.objects.create(+ product=product, sku="785", track_inventory=False+ )+ ProductVariantChannelListing.objects.create(+ variant=variant,+ channel=channel_USD,+ price_amount=Decimal(250),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=1)++ return product++@pytest.fixturedef product_with_rich_text_attribute(product_type_with_rich_text_attribute, category, warehouse, channel_USD@@ -1956,6 +2054,34 @@ def variant_with_many_stocks_different_shipping_zones(return variant+def gift_card_shippable_variant(shippable_gift_card_product, channel_USD):+ product = shippable_gift_card_product+ product_variant = ProductVariant.objects.create(product=product, sku="SKU_CARD_A")+ ProductVariantChannelListing.objects.create(+ variant=product_variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ return product_variant+++def gift_card_non_shippable_variant(non_shippable_gift_card_product, channel_USD):+ product = non_shippable_gift_card_product+ product_variant = ProductVariant.objects.create(product=product, sku="SKU_CARD_B")+ ProductVariantChannelListing.objects.create(+ variant=product_variant,+ channel=channel_USD,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=channel_USD.currency_code,+ )+ return product_variant++@pytest.fixturedef product_variant_list(product, channel_USD, channel_PLN):variants = list(@@ -2520,6 +2646,58 @@ def order_line(order, variant):)+def gift_card_non_shippable_order_line(order, gift_card_non_shippable_variant):+ variant = gift_card_non_shippable_variant+ product = variant.product+ channel = order.channel+ channel_listing = variant.channel_listings.get(channel=channel)+ net = variant.get_price(product, [], channel, channel_listing)+ currency = net.currency+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)+ quantity = 1+ unit_price = TaxedMoney(net=net, gross=gross)+ return order.lines.create(+ product_name=str(product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price,+ total_price=unit_price * quantity,+ undiscounted_unit_price=unit_price,+ undiscounted_total_price=unit_price * quantity,+ tax_rate=Decimal("0.23"),+ )+++def gift_card_shippable_order_line(order, gift_card_shippable_variant):+ variant = gift_card_shippable_variant+ product = variant.product+ channel = order.channel+ channel_listing = variant.channel_listings.get(channel=channel)+ net = variant.get_price(product, [], channel, channel_listing)+ currency = net.currency+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)+ quantity = 1+ unit_price = TaxedMoney(net=net, gross=gross)+ return order.lines.create(+ product_name=str(product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price,+ total_price=unit_price * quantity,+ undiscounted_unit_price=unit_price,+ undiscounted_total_price=unit_price * quantity,+ tax_rate=Decimal("0.23"),+ )++@pytest.fixturedef order_line_with_allocation_in_many_stocks(customer_user, variant_with_many_stocks, channel_USD