Skip to content

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

Adjust order fulfillment (#17301)

Iga Karbowiak2aa5434ae95b
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 3b5d1b5b6a..f99079ea82 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1258,6 +1258,7 @@ def test_complete_checkout_0_total_with_transaction_for_mark_as_paid(
)
# then
+ order.refresh_from_db()
assert order
assert order.authorize_status == OrderAuthorizeStatus.FULL
assert order.charge_status == OrderChargeStatus.FULL
@@ -2760,6 +2761,7 @@ def test_checkout_complete_with_voucher_0_total(
)
# then
+ order.refresh_from_db()
assert order.status == OrderStatus.UNFULFILLED
assert order.lines.count() == 1
assert order.discounts.count() == 1
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index 6961832c43..c071332b9e 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -1035,6 +1035,7 @@ def test_create_order_with_voucher_0_total(
)
# then
+ order.refresh_from_db()
assert order.status == OrderStatus.UNFULFILLED
assert order.lines.count() == 1
assert order.discounts.count() == 1
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index f661c5a81e..2a4e68c70a 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -14,6 +14,7 @@ from ...core import TimePeriodType
from ...core.exceptions import GiftCardNotApplicable
from ...core.utils.json_serializer import CustomJsonEncoder
from ...core.utils.promo_code import InvalidPromoCode
+from ...order import OrderEvents
from ...order.models import OrderLine
from ...plugins.manager import get_plugins_manager
from ...site import GiftCardSettingsExpiryType
@@ -695,6 +696,11 @@ def test_fulfill_gift_card_lines(
assert card.fulfillment_line
assert GiftCardEvent.objects.filter(gift_card=card, type=GiftCardEvents.BOUGHT)
+ event = order.events.filter(type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS).first()
+ assert event
+ assert "auto" in event.parameters
+ assert event.parameters["auto"] is True
+
def test_fulfill_gift_card_lines_lack_of_stock(
staff_user,
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 2cdebfb50e..398f326d82 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -155,6 +155,7 @@ def fulfill_gift_card_lines(
manager,
settings,
notify_customer=True,
+ auto=True,
)
diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
index 18eb11345f..9de0323c69 100644
--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_complete.py
@@ -74,6 +74,7 @@ def test_checkout_complete(
address,
shipping_method,
):
+ # given
assert not gift_card.last_used_on
checkout = checkout_with_gift_card
@@ -113,8 +114,11 @@ def test_checkout_complete(
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
redirect_url = "https://www.example.com"
variables = {"checkoutId": checkout_id, "redirectUrl": redirect_url}
+
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ # then
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
assert not data["errors"]
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 539ffad56b..bcc869c7b2 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -3895,6 +3895,7 @@ def test_checkout_complete_with_preorder_variant(
address,
shipping_method,
):
+ # given
checkout = checkout_with_item_and_preorder_item
checkout.shipping_address = address
checkout.shipping_method = shipping_method
@@ -3926,8 +3927,11 @@ def test_checkout_complete_with_preorder_variant(
"id": to_global_id_or_none(checkout),
"redirectUrl": "https://www.example.com",
}
+
+ # when
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ # then
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
assert not data["errors"]
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index 40d3350583..7aeb1d0d73 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -4,6 +4,7 @@ from unittest.mock import ANY, patch
import graphene
import pytest
+from django.db import transaction
from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import TaxedMoney
@@ -51,6 +52,7 @@ MUTATION_CHECKOUT_COMPLETE = """
) {
order {
id
+ status
token
original
origin
@@ -2717,6 +2719,7 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(
shipping_method,
transaction_events_generator,
transaction_item_generator,
+ django_capture_on_commit_callbacks,
):
# given
checkout_with_item_and_voucher_specific_products.gift_cards.add(gift_card)
@@ -2760,7 +2763,8 @@ def test_checkout_complete_with_voucher_on_specific_product_and_gift_card(
}
# when
- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ with django_capture_on_commit_callbacks(execute=True):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
# then
content = get_graphql_content(response)
@@ -4737,3 +4741,49 @@ def test_checkout_complete_empty_product_translation(
recalculate_with_plugins_mock.assert_not_called()
assert not len(Reservation.objects.all())
+
+
+def test_complete_checkout_order_status_changed_after_creation(
+ checkout_with_item_total_0,
+ customer_user,
+ user_api_client,
+):
+ """Ensure order status is valid in the mutation response.
+
+ In case that order is created with `UNCONFIRMED` and then changed into `UNFULFILLED`
+ in post commit action, the returned order status should be upt-to-date.
+ """
+ # given
+ checkout = checkout_with_item_total_0
+
+ channel = checkout.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.save()
+
+ update_checkout_payment_statuses(
+ checkout, zero_money(checkout.currency), checkout_has_lines=True
+ )
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ def immediate_on_commit(func):
+ func()
+
+ # when
+ with patch.object(transaction, "on_commit", side_effect=immediate_on_commit):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+
+ order = data["order"]
+ assert order
+ assert order["status"] == OrderStatus.UNFULFILLED.upper()
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index 9b7a83c7b2..af72129aa5 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -4,14 +4,17 @@ from unittest.mock import ANY, patch
import graphene
import pytest
+from django.db import transaction
from django.db.models.aggregates import Sum
from django.utils import timezone
from prices import Money, TaxedMoney
+from .....channel import MarkAsPaidStrategy
from .....checkout import calculations
from .....checkout.error_codes import OrderCreateFromCheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
+from .....checkout.payment_utils import update_checkout_payment_statuses
from .....core.taxes import (
TaxDataError,
TaxDataErrorMessage,
@@ -41,6 +44,7 @@ mutation orderCreateFromCheckout(
){
order{
id
+ status
token
original
origin
@@ -2620,3 +2624,51 @@ def test_order_from_checkout_with_transaction_empty_product_translation(
order_line = order.lines.first()
assert order_line.translated_product_name == ""
assert order_line.translated_variant_name == ""
+
+
+def test_order_from_checkout_order_status_changed_after_creation(
+ checkout_with_item_total_0,
+ customer_user,
+ app_api_client,
+ permission_handle_checkouts,
+):
+ """Ensure order status is valid in the mutation response.
+
+ In case that order is created with `UNCONFIRMED` and then changed into `UNFULFILLED`
+ in post commit action, the returned order status should be upt-to-date.
+ """
+ # given
+ checkout = checkout_with_item_total_0
+
+ channel = checkout.channel
+ channel.order_mark_as_paid_strategy = MarkAsPaidStrategy.TRANSACTION_FLOW
+ channel.save(update_fields=["order_mark_as_paid_strategy"])
+
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.save()
+
+ update_checkout_payment_statuses(
+ checkout, zero_money(checkout.currency), checkout_has_lines=True
+ )
+
+ variables = {"id": graphene.Node.to_global_id("Checkout", checkout.pk)}
+
+ def immediate_on_commit(func):
+ func()
+
+ # when
+ with patch.object(transaction, "on_commit", side_effect=immediate_on_commit):
+ response = app_api_client.post_graphql(
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ variables,
+ permissions=[permission_handle_checkouts],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderCreateFromCheckout"]
+ assert not data["errors"]
+
+ order = data["order"]
+ assert order
+ assert order["status"] == OrderStatus.UNFULFILLED.upper()
diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.py
index 6aba2990b8..1c28bb92f0 100644
--- a/saleor/graphql/order/mutations/order_confirm.py
+++ b/saleor/graphql/order/mutations/order_confirm.py
@@ -6,7 +6,7 @@ from django.db import transaction
from ....account.models import User
from ....core.tracing import traced_atomic_transaction
-from ....order import OrderStatus, models
+from ....order import models
from ....order.actions import (
WEBHOOK_EVENTS_FOR_ORDER_CHARGED,
WEBHOOK_EVENTS_FOR_ORDER_CONFIRMED,
@@ -15,7 +15,7 @@ from ....order.actions import (
)
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
-from ....order.utils import update_order_display_gross_prices
+from ....order.utils import update_order_display_gross_prices, update_order_status
from ....payment import gateway
from ....permission.enums import OrderPermissions
from ....webhook.utils import get_webhooks_for_multiple_events
@@ -72,9 +72,9 @@ class OrderConfirm(ModelMutation):
user = cast(User, user)
order = cls.get_instance(info, **data)
cls.check_channel_permissions(info, [order.channel_id])
- order.status = OrderStatus.UNFULFILLED
+ update_order_status(order)
update_order_display_gross_prices(order)
- order.save(update_fields=["status", "updated_at", "display_gross_prices"])
+ order.save(update_fields=["updated_at", "display_gross_prices"])
order_info = fetch_order_info(order)
payment = order_info.payment
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.py
index 37195eb0bd..7457add04b 100644
--- a/saleor/graphql/order/mutations/order_fulfill.py
+++ b/saleor/graphql/order/mutations/order_fulfill.py
@@ -286,9 +286,9 @@ class OrderFulfill(BaseMutation):
dict(lines_for_warehouses),
manager,
site.settings,
- notify_customer,
+ notify_customer=notify_customer,
allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
- approved=approved,
+ auto_approved=approved,
tracking_number=tracking_number,
)
except InsufficientStock as e:
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index 2a67ed62c4..9401b2e5b1 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -281,9 +281,9 @@ def test_order_fulfill_old_line_id(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=fulfillment_auto_approve,
+ auto_approved=fulfillment_auto_approve,
tracking_number="",
)
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
index cdf55d08b3..85b8233a3a 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
@@ -47,13 +47,18 @@ def test_fulfillment_approve(
fulfillment,
permission_group_manage_orders,
):
+ # given
permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
query = APPROVE_FULFILLMENT_MUTATION
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
variables = {"id": fulfillment_id, "notifyCustomer": True}
+
+ # when
response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderFulfillmentApprove"]
assert not data["errors"]
@@ -182,7 +187,9 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
staff_api_client,
fulfillment,
permission_group_manage_orders,
+ django_capture_on_commit_callbacks,
):
+ # given
permission_group_manage_orders.user_set.add(staff_api_client.user)
fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
fulfillment.save(update_fields=["status"])
@@ -196,8 +203,12 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
"notifyCustomer": True,
"allowStockToBeExceeded": False,
}
- response = staff_api_client.post_graphql(query, variables)
+ # when
+ with django_capture_on_commit_callbacks(execute=True):
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
errors = content["data"]["orderFulfillmentApprove"]["errors"]
@@ -222,7 +233,7 @@ def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceede
fulfillment.refresh_from_db()
assert fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL
- assert mock_email_fulfillment.call_count == 1
+ mock_email_fulfillment.assert_not_called()
events = fulfillment.order.events.all()
assert len(events) == 0
mock_fulfillment_approved.assert_not_called()
diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
index f0ba444150..9c6b78c3b9 100644
--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
@@ -8,7 +8,7 @@ from .....core.exceptions import InsufficientStock, InsufficientStockData
from .....core.models import EventDelivery
from .....giftcard import GiftCardEvents
from .....giftcard.models import GiftCard, GiftCardEvent
-from .....order import FulfillmentStatus, OrderStatus
+from .....order import FulfillmentStatus, OrderEvents, OrderStatus
from .....order.actions import call_order_events, order_fulfilled
from .....order.error_codes import OrderErrorCode
from .....order.models import Fulfillment, FulfillmentLine
@@ -136,9 +136,9 @@ def test_order_fulfill(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=fulfillment_auto_approve,
+ auto_approved=fulfillment_auto_approve,
tracking_number="",
)
mocked_fulfillment_tracking_number_updated_event.assert_not_called()
@@ -246,9 +246,9 @@ def test_order_fulfill_with_tracking_number(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=fulfillment_auto_approve,
+ auto_approved=fulfillment_auto_approve,
tracking_number="test_tracking_number",
)
@@ -575,9 +575,9 @@ def test_order_fulfill_as_app(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=True,
+ auto_approved=True,
tracking_number="",
)
@@ -643,9 +643,9 @@ def test_order_fulfill_many_warehouses(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=True,
+ auto_approved=True,
tracking_number="",
)
@@ -936,9 +936,9 @@ def test_order_fulfill_without_notification(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- False,
+ notify_customer=False,
allow_stock_to_be_exceeded=False,
- approved=True,
+ auto_approved=True,
tracking_number="",
)
@@ -1003,9 +1003,9 @@ def test_order_fulfill_lines_with_empty_quantity(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=True,
+ auto_approved=True,
tracking_number="",
)
@@ -1068,9 +1068,9 @@ def test_order_fulfill_without_sku(
fulfillment_lines_for_warehouses,
ANY,
site_settings,
- True,
+ notify_customer=True,
allow_stock_to_be_exceeded=False,
- approved=fulfillment_auto_approve,
+ auto_approved=fulfillment_auto_approve,
tracking_number="",
)
@@ -1705,3 +1705,66 @@ def test_order_fulfill_fulfilled_order_race_condition(
assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name
assert error["orderLines"] == [order_line_id]
assert not error["warehouse"]
+
+
+@patch("saleor.plugins.manager.PluginsManager.tracking_number_updated")
[email protected]_db(transaction=True)
+def test_order_fulfill_order_in_proper_state_when_error_occur_when_sending_webhook(
+ mocked_fulfillment_tracking_number_updated_event,
+ staff_api_client,
+ order_with_lines,
+ permission_group_manage_orders,
+ warehouse,
+ site_settings,
+):
+ """Ensure that order has proper status and event in case error occur."""
+ # given
+ mocked_fulfillment_tracking_number_updated_event.side_effect = Exception()
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ site_settings.fulfillment_auto_approve = True
+ site_settings.save(update_fields=["fulfillment_auto_approve"])
+ order = order_with_lines
+ query = ORDER_FULFILL_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ order_line, order_line2 = order.lines.all()
+ 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": {
+ "trackingNumber": "123",
+ "notifyCustomer": True,
+ "lines": [
+ {
+ "orderLineId": order_line_id,
+ "stocks": [
+ {"quantity": order_line.quantity, "warehouse": warehouse_id}
+ ],
+ },
+ {
+ "orderLineId": order_line2_id,
+ "stocks": [
+ {"quantity": order_line2.quantity, "warehouse": warehouse_id}
+ ],
+ },
+ ],
+ },
+ }
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ order.refresh_from_db()
+ assert order.status == OrderStatus.FULFILLED
+ assert order.events.filter(type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS).exists()
+
+ fulfillment = order.fulfillments.first()
+ assert fulfillment
+ assert fulfillment.status == FulfillmentStatus.FULFILLED
+
+ for line in [order_line, order_line2]:
+ line.refresh_from_db()
+ assert line.quantity_fulfilled == line.quantity
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index 8a2654689d..8940104ffd 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -16,7 +16,7 @@ from .....order.actions import order_transaction_updated
from .....order.events import transaction_event as order_transaction_event
from .....order.fetch import fetch_order_info
from .....order.search import update_order_search_vector
-from .....order.utils import updates_amounts_for_order
+from .....order.utils import update_order_status, updates_amounts_for_order
from .....payment import TransactionEventType
from .....payment import models as payment_models
from .....payment.error_codes import TransactionCreateErrorCode
@@ -321,8 +321,7 @@ class TransactionCreate(BaseMutation):
order.channel.automatically_confirm_all_new_orders
and order.status == OrderStatus.UNCONFIRMED
):
- order.status = OrderStatus.UNFULFILLED
- update_fields.append("status")
+ update_order_status(order)
if update_search_vector:
update_order_search_vector(order, save=False)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 8a978e47a9..c957ce38c2 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -11,6 +11,7 @@ from django.contrib.sites.models import Site
from django.db import transaction
from ..account.models import User
+from ..app.models import App
from ..core.exceptions import AllocationError, InsufficientStock, InsufficientStockData
from ..core.tracing import traced_atomic_transaction
from ..core.transactions import transaction_with_commit_on_errors
@@ -379,7 +380,7 @@ def handle_fully_paid_order(
if order_info.customer_email:
send_payment_confirmation(order_info, manager)
if utils.order_needs_automatic_fulfillment(order_info.lines_data):
- automatically_fulfill_digital_lines(order_info, manager)
+ automatically_fulfill_digital_lines(order_info, manager, user, app)
if site_settings is None:
site_settings = Site.objects.get_current().settings
@@ -537,6 +538,8 @@ def order_fulfilled(
gift_card_lines_info: list[GiftCardLineData],
site_settings: "SiteSettings",
notify_customer=True,
+ auto=False,
+ manually_approved=False,
webhook_event_map: dict[str, set["Webhook"]] | None = None,
):
from ..giftcard.utils import gift_cards_create
@@ -550,25 +553,33 @@ def order_fulfilled(
# events are successfully created
with traced_atomic_transaction():
update_order_status(order)
- gift_cards_create(
- order,
- gift_card_lines_info,
- site_settings,
- user,
- app,
- manager,
- )
+ if gift_card_lines_info:
+ gift_cards_create(
+ order,
+ gift_card_lines_info,
+ site_settings,
+ user,
+ app,
+ manager,
+ )
events.fulfillment_fulfilled_items_event(
- order=order, user=user, app=app, fulfillment_lines=fulfillment_lines
+ order=order,
+ user=user,
+ app=app,
+ fulfillment_lines=fulfillment_lines,
+ auto=auto,
)
webhook_events = [WebhookEventAsyncType.ORDER_UPDATED]
for fulfillment in fulfillments:
call_event(manager.fulfillment_created, fulfillment, notify_customer)
- if order.status == OrderStatus.FULFILLED:
+ order_fulfilled = order.status == OrderStatus.FULFILLED
+ if order_fulfilled:
webhook_events.append(WebhookEventAsyncType.ORDER_FULFILLED)
+
+ if order_fulfilled or manually_approved:
for fulfillment in fulfillments:
- call_event(manager.fulfillment_approved, fulfillment)
+ call_event(manager.fulfillment_approved, fulfillment, notify_customer)
call_order_events(
manager,
@@ -578,8 +589,13 @@ def order_fulfilled(
)
if notify_customer:
for fulfillment in fulfillments:
- send_fulfillment_confirmation_to_customer(
- order, fulfillment, user, app, manager
+ call_event(
+ send_fulfillment_confirmation_to_customer,
+ order,
+ fulfillment,
+ user,
+ app,
+ manager,
)
@@ -835,28 +851,17 @@ def approve_fulfillment(
notify_customer=True,
allow_stock_to_be_exceeded: bool = False,
):
- from ..giftcard.utils import gift_cards_create
-
with traced_atomic_transaction():
fulfillment.status = FulfillmentStatus.FULFILLED
fulfillment.save()
order = fulfillment.order
- if notify_customer:
- send_fulfillment_confirmation_to_customer(
- fulfillment.order, fulfillment, user, app, manager
- )
- events.fulfillment_fulfilled_items_event(
- order=order,
- user=user,
- app=app,
- fulfillment_lines=list(fulfillment.lines.all()),
- )
lines_to_fulfill = []
gift_card_lines_info = []
insufficient_stocks = []
- for fulfillment_line in fulfillment.lines.all().prefetch_related(
+ fulfillment_lines = fulfillment.lines.all().prefetch_related(
"order_line__variant"
- ):
+ )
+ for fulfillment_line in fulfillment_lines:
order_line = fulfillment_line.order_line
variant = fulfillment_line.order_line.variant
@@ -898,33 +903,18 @@ def approve_fulfillment(
_decrease_stocks(lines_to_fulfill, manager, allow_stock_to_be_exceeded)
order.refresh_from_db()
- update_order_status(order)
-
- webhook_event_map = get_webhooks_for_multiple_events(
- WEBHOOK_EVENTS_FOR_ORDER_FULFILLED
- )
- webhook_events = [WebhookEventAsyncType.ORDER_UPDATED]
- call_event(manager.fulfillment_approved, fulfillment, notify_customer)
- if order.status == OrderStatus.FULFILLED:
- webhook_events.append(WebhookEventAsyncType.ORDER_FULFILLED)
-
- call_order_events(
+ order_fulfilled(
+ [fulfillment],
+ user,
+ app,
+ list(fulfillment_lines),
manager,
- webhook_events,
- order,
- webhook_event_map=webhook_event_map,
+ gift_card_lines_info,
+ settings,
+ notify_customer,
+ manually_approved=True,
)
- if gift_card_lines_info:
- gift_cards_create(
- order,
- gift_card_lines_info,
- settings,
- user,
- app,
- manager,
- )
-
return fulfillment
@@ -1077,7 +1067,10 @@ def fulfill_order_lines(
def automatically_fulfill_digital_lines(
- order_info: "OrderInfo", manager: "PluginsManager"
+ order_info: "OrderInfo",
+ manager: "PluginsManager",
+ user: User | None = None,
+ app: App | None = None,
):
"""Fulfill all digital lines which have enabled automatic fulfillment setting.
@@ -1125,6 +1118,9 @@ def automatically_fulfill_digital_lines(
FulfillmentLine.objects.bulk_create(fulfillments)
fulfill_order_lines(lines_info, manager)
+ events.fulfillment_fulfilled_items_event(
+ order=order, user=user, app=app, fulfillment_lines=fulfillments, auto=True
+ )
send_fulfillment_confirmation_to_customer(
order, fulfillment, user=order.user, app=None, manager=manager
@@ -1258,8 +1254,10 @@ def create_fulfillments(
fulfillment_lines_for_warehouses: dict[UUID, list[OrderFulfillmentLineInfo]],
manager: "PluginsManager",
site_settings: "SiteSettings",
+ *,
notify_customer: bool = True,
- approved: bool = True,
+ auto: bool = False,
+ auto_approved: bool = True,
allow_stock_to_be_exceeded: bool = False,
tracking_number: str = "",
) -> list[Fulfillment]:
@@ -1287,7 +1285,8 @@ def create_fulfillments(
notify_customer (bool): If `True` system send email about
fulfillments to customer.
site_settings (SiteSettings): Site settings used for creating gift cards.
- approved (Boolean): fulfillments will have status fulfilled if it's True,
+ auto (Boolean): define if the fulfillment is automatic
+ auto_approved (Boolean): fulfillments will have status fulfilled if it's True,
otherwise waiting_for_approval.
allow_stock_to_be_exceeded (bool): If `True` then stock quantity could exceed.
Default value is set to `False`.
@@ -1307,7 +1306,7 @@ def create_fulfillments(
gift_card_lines_info: list[GiftCardLineData] = []
status = (
FulfillmentStatus.FULFILLED
- if approved
+ if auto_approved
else FulfillmentStatus.WAITING_FOR_APPROVAL
)
@@ -1340,7 +1339,7 @@ def create_fulfillments(
order.channel.slug,
gift_card_lines_info,
manager,
- decrease_stock=approved,
+ decrease_stock=auto_approved,
allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
)
)
@@ -1349,28 +1348,25 @@ def create_fulfillments(
FulfillmentLine.objects.bulk_create(fulfillment_lines)
order.refresh_from_db()
- if approved:
- transaction.on_commit(
- lambda: order_fulfilled(
- fulfillments,
- user,
- app,
- fulfillment_lines,
- manager,
- gift_card_lines_info,
- site_settings,
- notify_customer,
- )
+ if auto_approved:
+ order_fulfilled(
+ fulfillments,
+ user,
+ app,
+ fulfillment_lines,
+ manager,
+ gift_card_lines_info,
+ site_settings,
+ notify_customer,
+ auto,
)
else:
- transaction.on_commit(
- lambda: order_awaits_fulfillment_approval(
- fulfillments,
- user,
- app,
- fulfillment_lines,
- manager,
- )
+ order_awaits_fulfillment_approval(
+ fulfillments,
+ user,
+ app,
+ fulfillment_lines,
+ manager,
)
return fulfillments
diff --git a/saleor/order/events.py b/saleor/order/events.py
index c33f669f2b..db3e920797 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -595,13 +595,17 @@ def fulfillment_fulfilled_items_event(
user: User | None,
app: App | None,
fulfillment_lines: list[FulfillmentLine],
+ auto: bool = False,
) -> OrderEvent:
return OrderEvent.objects.create(
order=order,
type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS,
user=user,
app=app,
- parameters={"fulfilled_items": [line.pk for line in fulfillment_lines]},
+ parameters={
+ "fulfilled_items": [line.pk for line in fulfillment_lines],
+ "auto": auto,
+ },
)
diff --git a/saleor/order/tests/test_fulfillments_actions.py b/saleor/order/tests/test_fulfillments_actions.py
index 8f32b66e3f..8b3b48bef4 100644
--- a/saleor/order/tests/test_fulfillments_actions.py
+++ b/saleor/order/tests/test_fulfillments_actions.py
@@ -30,6 +30,7 @@ def test_create_fulfillments(
{"order_line": order_line2, "quantity": 2},
]
}
+ notify_customer = True
manager = get_plugins_manager(allow_replica=False)
with django_capture_on_commit_callbacks(execute=True):
[fulfillment] = create_fulfillments(
@@ -39,7 +40,7 @@ def test_create_fulfillments(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=notify_customer,
)
order.refresh_from_db()
@@ -74,11 +75,12 @@ def test_create_fulfillments(
fulfillment_lines[0].pk,
fulfillment_lines[1].pk,
}
+ assert event.parameters["auto"] is False
mock_email_fulfillment.assert_called_once_with(
order, order.fulfillments.get(), staff_user, None, manager
)
- mock_fulfillment_approved.assert_called_once_with(fulfillment)
+ mock_fulfillment_approved.assert_called_once_with(fulfillment, notify_customer)
@patch("saleor.plugins.manager.PluginsManager.fulfillment_approved")
@@ -112,8 +114,8 @@ def test_create_fulfillments_require_approval(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
- False,
+ notify_customer=True,
+ auto_approved=False,
)
order.refresh_from_db()
@@ -182,8 +184,8 @@ def test_create_fulfillments_require_approval_as_app(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
- False,
+ notify_customer=True,
+ auto_approved=False,
)
order.refresh_from_db()
@@ -249,7 +251,7 @@ def test_create_fulfillments_without_notification(
fulfillment_lines_for_warehouses,
get_plugins_manager(allow_replica=False),
site_settings,
- False,
+ notify_customer=False,
)
order.refresh_from_db()
@@ -315,7 +317,7 @@ def test_create_fulfillments_many_warehouses(
fulfillment_lines_for_warehouses,
get_plugins_manager(allow_replica=False),
site_settings,
- False,
+ notify_customer=False,
)
order.refresh_from_db()
@@ -372,7 +374,7 @@ def test_create_fulfillments_with_one_line_empty_quantity(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=True,
)
order.refresh_from_db()
@@ -427,7 +429,7 @@ def test_create_fulfillments_with_variant_without_inventory_tracking(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=True,
)
order.refresh_from_db()
@@ -479,7 +481,7 @@ def test_create_fulfillments_without_allocations(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=True,
)
order.refresh_from_db()
@@ -535,7 +537,7 @@ def test_create_fulfillments_warehouse_without_stock(
fulfillment_lines_for_warehouses,
get_plugins_manager(allow_replica=False),
site_settings,
- True,
+ notify_customer=True,
)
assert len(exc.value.items) == 2
@@ -590,7 +592,7 @@ def test_create_fulfillments_with_variant_without_inventory_tracking_and_without
fulfillment_lines_for_warehouses,
get_plugins_manager(allow_replica=False),
site_settings,
- True,
+ notify_customer=True,
)
assert len(exc.value.items) == 1
@@ -674,7 +676,7 @@ def test_create_fullfilment_with_out_of_stock_webhook_not_triggered(
fulfillment_lines_for_warehouses=fulfillment_lines_for_warehouses,
manager=manager,
site_settings=site_settings,
- approved=False,
+ auto_approved=False,
)
product_variant_out_of_stock_webhook.assert_not_called()
@@ -730,7 +732,7 @@ def test_create_fulfillments_quantity_allocated_lower_than_line_quantity(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=True,
)
# then
@@ -791,5 +793,5 @@ def test_create_fulfillments_validate_lines_raise_error(
fulfillment_lines_for_warehouses,
manager,
site_settings,
- True,
+ notify_customer=True,
)
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 117371e286..d8b23b2c28 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -385,6 +385,7 @@ def test_restock_fulfillment_lines(fulfilled_order, warehouse):
def test_update_order_status_partially_fulfilled(fulfilled_order):
+ # given
fulfillment = fulfilled_order.fulfillments.first()
line = fulfillment.lines.first()
order_line = line.order_line
@@ -392,8 +393,11 @@ def test_update_order_status_partially_fulfilled(fulfilled_order):
order_line.quantity_fulfilled -= line.quantity
order_line.save()
line.delete()
+
+ # when
update_order_status(fulfilled_order)
+ # then
assert fulfilled_order.status == OrderStatus.PARTIALLY_FULFILLED
@@ -403,7 +407,6 @@ def test_update_order_status_unfulfilled(order_with_lines):
update_order_status(order_with_lines)
- order_with_lines.refresh_from_db()
assert order_with_lines.status == OrderStatus.UNFULFILLED
@@ -423,7 +426,6 @@ def test_update_order_status_fulfilled(fulfilled_order):
update_order_status(fulfilled_order)
- fulfilled_order.refresh_from_db()
assert fulfilled_order.status == OrderStatus.FULFILLED
@@ -434,7 +436,6 @@ def test_update_order_status_returned(fulfilled_order):
update_order_status(fulfilled_order)
- fulfilled_order.refresh_from_db()
assert fulfilled_order.status == OrderStatus.RETURNED
@@ -467,7 +468,6 @@ def test_update_order_status_partially_returned(fulfilled_order):
update_order_status(fulfilled_order)
- fulfilled_order.refresh_from_db()
assert fulfilled_order.status == OrderStatus.PARTIALLY_RETURNED
@@ -478,7 +478,6 @@ def test_update_order_status_waiting_for_approval(fulfilled_order):
update_order_status(fulfilled_order)
- fulfilled_order.refresh_from_db()
assert fulfilled_order.status == OrderStatus.PARTIALLY_FULFILLED
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index cb98d508eb..71ef3575f5 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -92,9 +92,12 @@ def test_handle_fully_paid_order_digital_lines(
# then
fulfillment = order.fulfillments.first()
- event_order_paid = order.events.get()
-
- assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID
+ assert set(order.events.values_list("type", flat=True)) == {
+ OrderEvents.ORDER_FULLY_PAID,
+ OrderEvents.FULFILLMENT_FULFILLED_ITEMS,
+ }
+ fulfilled_event = order.events.get(type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS)
+ assert fulfilled_event.parameters["auto"] is True
mock_send_payment_confirmation.assert_called_once_with(order_info, manager)
send_fulfillment_confirmation_to_customer.assert_called_once_with(
@@ -1574,6 +1577,14 @@ def test_fulfill_digital_lines(
assert mock_email_fulfillment.called
mock_fulfillment_created.assert_called_once_with(fulfillment)
+ event = order_with_lines.events.filter(
+ type=OrderEvents.FULFILLMENT_FULFILLED_ITEMS
+ ).first()
+ assert event
+ assert set(event.parameters["fulfilled_items"]) == {
+ line.pk for line in fulfillment_lines
+ }
+
@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer")
@patch("saleor.order.utils.get_default_digital_content_settings")
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index b03f70e6f5..dd2076403b 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Optional, cast
import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
+from django.db import transaction
from django.db.models import QuerySet, Sum
from django.template.defaultfilters import pluralize
from django.utils import timezone
@@ -168,17 +169,44 @@ def _calculate_quantity_including_returns(order):
def update_order_status(order: Order):
"""Update order status depending on fulfillments."""
- (
- total_quantity,
- quantity_fulfilled,
- quantity_returned,
- ) = _calculate_quantity_including_returns(order)
+ with transaction.atomic():
+ # Add a transaction block to ensure that the order status won't be overridden by
+ # another process.
+ locked_order = Order.objects.select_for_update().get(pk=order.pk)
+ # Calculate the quantities for the most recent data
+ (
+ total_quantity,
+ quantity_fulfilled,
+ quantity_returned,
+ ) = _calculate_quantity_including_returns(locked_order)
+
+ # check if order contains any fulfillments that awaiting approval
+ awaiting_approval = locked_order.fulfillments.filter(
+ status=FulfillmentStatus.WAITING_FOR_APPROVAL
+ ).exists()
+
+ status = determine_order_status(
+ order,
+ total_quantity,
+ quantity_fulfilled,
+ quantity_returned,
+ awaiting_approval,
+ )
+
+ # we would like to update the status for the order provided as the argument
+ # to ensure that the reference order has up to date status
+ if status != order.status:
+ order.status = status
+ order.save(update_fields=["status", "updated_at"])
- # check if order contains any fulfillments that awaiting approval
- awaiting_approval = order.fulfillments.filter(
- status=FulfillmentStatus.WAITING_FOR_APPROVAL
- ).exists()
+def determine_order_status(
+ order: Order,
+ total_quantity: int,
+ quantity_fulfilled: int,
+ quantity_returned: int,
+ awaiting_approval: bool,
+):
# total_quantity == 0 means that all products have been replaced, we don't change
# the order status in that case
if total_quantity == 0:
@@ -193,10 +221,7 @@ def update_order_status(order: Order):
status = OrderStatus.PARTIALLY_FULFILLED
else:
status = OrderStatus.FULFILLED
-
- if status != order.status:
- order.status = status
- order.save(update_fields=["status", "updated_at"])
+ return status
@traced_atomic_transaction()