Skip to content

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

Do not create gift cards for waiting for approval orders (#8162)

Iga Karbowiaka17f11cf7e87
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index 8463f21f10..6be14a87d4 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -353,17 +353,14 @@ 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,
- ]
+ lines = [
+ gift_card_non_shippable_order_line,
+ gift_card_shippable_order_line,
+ order_line,
]
# when
- gift_card_lines = get_gift_card_lines(ids)
+ gift_card_lines = get_gift_card_lines(lines)
# then
assert set(gift_card_lines) == {
@@ -376,10 +373,10 @@ 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]]
+ lines = [order_line_with_one_allocation, order_line]
# when
- gift_card_lines = get_gift_card_lines(ids)
+ gift_card_lines = get_gift_card_lines(lines)
# then
assert not gift_card_lines
@@ -389,17 +386,14 @@ 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,
- ]
+ lines = [
+ gift_card_non_shippable_order_line,
+ gift_card_shippable_order_line,
+ order_line,
]
# when
- gift_card_lines = get_non_shippable_gift_card_lines(ids)
+ gift_card_lines = get_non_shippable_gift_card_lines(lines)
# then
assert set(gift_card_lines) == {gift_card_non_shippable_order_line}
@@ -409,10 +403,10 @@ 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]]
+ lines = [order_line_with_one_allocation, order_line]
# when
- gift_card_lines = get_gift_card_lines(ids)
+ gift_card_lines = get_gift_card_lines(lines)
# then
assert not gift_card_lines
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index dc077917ff..6af538e9af 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -13,8 +13,6 @@ from ..core.utils.promo_code import InvalidPromoCode, generate_promo_code
from ..core.utils.validators import user_is_valid
from ..order.actions import create_fulfillments
from ..order.models import OrderLine
-from ..product import ProductTypeKind
-from ..product.models import Product, ProductType, ProductVariant
from ..site import GiftCardSettingsExpiryType
from . import GiftCardEvents, events
from .models import GiftCard, GiftCardEvent
@@ -86,8 +84,7 @@ def fulfill_non_shippable_gift_cards(
):
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)
+ gift_card_lines = get_non_shippable_gift_card_lines(order_lines)
if not gift_card_lines:
return
fulfill_gift_card_lines(gift_card_lines, requestor_user, app, order, manager)
@@ -97,26 +94,16 @@ def fulfill_non_shippable_gift_cards(
)
-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,
+def get_non_shippable_gift_card_lines(lines: Iterable[OrderLine]) -> "QuerySet":
+ gift_card_lines = get_gift_card_lines(lines)
+ non_shippable_lines = OrderLine.objects.filter(
+ id__in=[line.pk for line in gift_card_lines], is_shipping_required=False
)
- return gift_card_lines
-
+ return non_shippable_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")))
- )
+def get_gift_card_lines(lines: Iterable[OrderLine]):
+ gift_card_lines = [line for line in lines if line.is_gift_card]
return gift_card_lines
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index d47b2c1e92..074122ff86 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -30,7 +30,6 @@ from ...core.mutations import BaseMutation
from ...core.scalars import PositiveDecimal
from ...core.types.common import OrderError
from ...core.utils import get_duplicated_values
-from ...utils import resolve_global_ids_to_primary_keys
from ...warehouse.types import Warehouse
from ..types import Fulfillment, FulfillmentLine, Order, OrderLine
from ..utils import prepare_insufficient_stock_order_validation_errors
@@ -225,18 +224,11 @@ class OrderFulfill(BaseMutation):
)
data["order_lines"] = order_lines
- data["gift_card_lines"] = cls.get_gift_card_lines(lines_ids)
+ data["gift_card_lines"] = get_gift_card_lines(order_lines)
data["quantities"] = order_line_id_to_total_quantity
data["lines_for_warehouses"] = lines_for_warehouses
return data
- @staticmethod
- def get_gift_card_lines(lines_ids):
- _, pks = resolve_global_ids_to_primary_keys(
- lines_ids, OrderLine, raise_error=True
- )
- return get_gift_card_lines(pks)
-
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, order, **data):
@@ -257,15 +249,18 @@ class OrderFulfill(BaseMutation):
gift_card_lines = cleaned_input["gift_card_lines"]
quantities = cleaned_input["quantities"]
- gift_cards_create(
- order,
- gift_card_lines,
- quantities,
- context.site.settings,
- user,
- app,
- manager,
- )
+ approved = info.context.site.settings.fulfillment_auto_approve
+
+ if approved:
+ gift_cards_create(
+ order,
+ gift_card_lines,
+ quantities,
+ context.site.settings,
+ user,
+ app,
+ manager,
+ )
try:
fulfillments = create_fulfillments(
@@ -276,7 +271,7 @@ class OrderFulfill(BaseMutation):
manager,
notify_customer,
allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
- approved=info.context.site.settings.fulfillment_auto_approve,
+ approved=approved,
)
except InsufficientStock as exc:
errors = prepare_insufficient_stock_order_validation_errors(exc)
@@ -470,8 +465,9 @@ class FulfillmentApprove(BaseMutation):
info.context.user,
info.context.app,
info.context.plugins,
- allow_stock_to_be_exceeded=data.get("allow_stock_to_be_exceeded"),
+ info.context.site.settings,
notify_customer=data["notify_customer"],
+ allow_stock_to_be_exceeded=data.get("allow_stock_to_be_exceeded"),
)
order.refresh_from_db(fields=["status"])
return FulfillmentApprove(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index f525fa135e..12f6975cfc 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -6,10 +6,12 @@ import pytest
from ....core.exceptions import InsufficientStock, InsufficientStockData
from ....giftcard import GiftCardEvents
from ....giftcard.models import GiftCard, GiftCardEvent
-from ....order import OrderStatus
+from ....order import OrderLineData, OrderStatus
+from ....order.actions import fulfill_order_lines
from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
from ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatus
+from ....plugins.manager import get_plugins_manager
from ....warehouse.models import Allocation, Stock
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -524,6 +526,77 @@ def test_order_fulfill_with_gift_cards(
)
+@patch("saleor.giftcard.utils.send_gift_card_notification")
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+def test_order_fulfill_with_gift_card_lines_waiting_for_approval(
+ 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,
+ site_settings,
+):
+ query = ORDER_FULFILL_QUERY
+
+ site_settings.fulfillment_auto_approve = False
+ site_settings.save(update_fields=["fulfillment_auto_approve"])
+
+ 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"]
+ assert GiftCard.objects.count() == 0
+
+ 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=False,
+ allow_stock_to_be_exceeded=False,
+ )
+
+ mock_send_notification.assert_not_called()
+
+
@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(
@@ -1501,6 +1574,73 @@ def test_fulfillment_approve(
assert event.user == staff_api_client.user
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_fulfillment_approve_gift_cards_created(
+ mock_email_fulfillment,
+ staff_api_client,
+ fulfillment,
+ permission_manage_orders,
+ gift_card_shippable_order_line,
+ gift_card_non_shippable_order_line,
+):
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+
+ gift_card_line_1 = gift_card_shippable_order_line
+ gift_card_line_2 = gift_card_non_shippable_order_line
+ stock_1 = gift_card_line_1.variant.stocks.first()
+ stock_2 = gift_card_line_2.variant.stocks.first()
+ fulfillment.lines.create(
+ order_line=gift_card_line_1, quantity=gift_card_line_1.quantity, stock=stock_1
+ )
+ fulfillment.lines.create(
+ order_line=gift_card_line_2, quantity=gift_card_line_2.quantity, stock=stock_2
+ )
+
+ fulfill_order_lines(
+ [
+ OrderLineData(
+ line=gift_card_line_1,
+ quantity=gift_card_line_1.quantity,
+ warehouse_pk=stock_1.warehouse.pk,
+ ),
+ OrderLineData(
+ line=gift_card_line_2,
+ quantity=gift_card_line_2.quantity,
+ warehouse_pk=stock_2.warehouse.pk,
+ ),
+ ],
+ manager=get_plugins_manager(),
+ )
+
+ query = APPROVE_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id, "notifyCustomer": True}
+ assert GiftCard.objects.count() == 0
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentApprove"]
+ assert not data["errors"]
+ assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()
+ assert data["order"]["status"] == OrderStatus.FULFILLED.upper()
+ fulfillment.refresh_from_db()
+ assert fulfillment.status == FulfillmentStatus.FULFILLED
+
+ assert mock_email_fulfillment.call_count == 1
+ events = fulfillment.order.events.all()
+ assert len(events) == 1
+ event = events[0]
+ assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
+ assert event.user == staff_api_client.user
+ assert (
+ GiftCard.objects.count()
+ == gift_card_line_1.quantity + gift_card_line_2.quantity
+ )
+
+
@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(
mock_email_fulfillment,
@@ -1528,7 +1668,6 @@ def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
-
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 5b6a794c3b..3c84fa4f69 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -64,6 +64,7 @@ from .utils import (
if TYPE_CHECKING:
from ..app.models import App
from ..plugins.manager import PluginsManager
+ from ..site.models import SiteSettings
from ..warehouse.models import Warehouse
logger = logging.getLogger(__name__)
@@ -370,6 +371,7 @@ def approve_fulfillment(
user: "User",
app: Optional["App"],
manager: "PluginsManager",
+ settings: "SiteSettings",
notify_customer=True,
allow_stock_to_be_exceeded: bool = False,
):
@@ -400,9 +402,42 @@ def approve_fulfillment(
if order.status == OrderStatus.FULFILLED:
transaction.on_commit(lambda: manager.order_fulfilled(order))
+ create_gift_cards_when_approving_fulfillment(
+ fulfillment.order, lines_to_fulfill, user, app, manager, settings
+ )
+
return fulfillment
+def create_gift_cards_when_approving_fulfillment(
+ order: "Order",
+ lines_data: List[OrderLineData],
+ user: "User",
+ app: Optional["App"],
+ manager: "PluginsManager",
+ settings: "SiteSettings",
+):
+ from ..giftcard.utils import gift_cards_create
+
+ gift_card_lines = []
+ quantities = {}
+ for line_data in lines_data:
+ if line_data.line.is_gift_card:
+ line = line_data.line
+ gift_card_lines.append(line)
+ quantities[line.pk] = line_data.quantity
+
+ gift_cards_create(
+ order,
+ gift_card_lines,
+ quantities,
+ settings,
+ user,
+ app,
+ manager,
+ )
+
+
@traced_atomic_transaction()
def mark_order_as_paid(
order: "Order",