Skip to content

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

Fulfillment confirmation (#7675)

Tomasz Szymański62f048048a58
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d62419b5b..9b9ec6ee40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -130,6 +130,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix failing account mutations for app - #7569 by @IKarbowiak
- Modify order of auth middleware calls - #7572 by @tomaszszymanski129
- Add app support for events - #7622 by @IKarbowiak
+- Fulfillment confirmation - #7675 by @tomaszszymanski129
- Add date & date time attributes - #7500 by @piotrgrundas
- Add `withChoices` flag for Attribute type - #7733 by @dexon44
- Drop assigning cheapest shipping method in checkout - #7767 by @maarcingebala
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 279ebe0a17..3f0f72da00 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -2,6 +2,7 @@ from collections import defaultdict
from django.db.models import F
+from ...order import FulfillmentStatus
from ...order.models import Fulfillment, FulfillmentLine, Order, OrderEvent, OrderLine
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
@@ -103,3 +104,17 @@ class FulfillmentLinesByIdLoader(DataLoader):
def batch_load(self, keys):
fulfillment_lines = FulfillmentLine.objects.in_bulk(keys)
return [fulfillment_lines.get(line_id) for line_id in keys]
+
+
+class FulfillmentLinesAwaitingApprovalByOrderLineIdLoader(DataLoader):
+ context_key = "fulfillment_lines_awaitng_approval_by_orderline"
+
+ def batch_load(self, keys):
+ fulfillments = FulfillmentLine.objects.filter(
+ order_line_id__in=keys,
+ fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL,
+ ).order_by("pk")
+ fulfillments_map = defaultdict(list)
+ for fulfillment in fulfillments.iterator():
+ fulfillments_map[fulfillment.order_line_id].append(fulfillment)
+ return [fulfillments_map.get(order_line_id, []) for order_line_id in keys]
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 96902817c7..9e060341a0 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -9,6 +9,7 @@ from ....core.permissions import OrderPermissions
from ....order import FulfillmentLineData, FulfillmentStatus, OrderLineData
from ....order import models as order_models
from ....order.actions import (
+ approve_fulfillment,
cancel_fulfillment,
create_fulfillments,
create_fulfillments_for_returned_products,
@@ -67,12 +68,6 @@ class FulfillmentUpdateTrackingInput(graphene.InputObjectType):
)
-class FulfillmentCancelInput(graphene.InputObjectType):
- warehouse_id = graphene.ID(
- description="ID of warehouse where items will be restock.", required=True
- )
-
-
class OrderFulfill(BaseMutation):
fulfillments = graphene.List(
Fulfillment, description="List of created fulfillments."
@@ -84,7 +79,7 @@ class OrderFulfill(BaseMutation):
description="ID of the order to be fulfilled.", name="order"
)
input = OrderFulfillInput(
- required=True, description="Fields required to create an fulfillment."
+ required=True, description="Fields required to create a fulfillment."
)
class Meta:
@@ -163,7 +158,21 @@ class OrderFulfill(BaseMutation):
)
@classmethod
- def clean_input(cls, data):
+ def clean_input(cls, info, order, data):
+ site_settings = info.context.site.settings
+ if not order.is_fully_paid() and (
+ site_settings.fulfillment_auto_approve
+ and not site_settings.fulfillment_allow_unpaid
+ ):
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "Cannot fulfill unpaid order.",
+ code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.value,
+ )
+ }
+ )
+
lines = data["lines"]
warehouse_ids_for_lines = [
@@ -206,7 +215,7 @@ class OrderFulfill(BaseMutation):
order = cls.get_node_or_error(info, order, field="order", only_type=Order)
data = data.get("input")
- cleaned_input = cls.clean_input(data)
+ cleaned_input = cls.clean_input(info, order, data)
user = info.context.user
lines_for_warehouses = cleaned_input["lines_for_warehouses"]
@@ -220,6 +229,7 @@ class OrderFulfill(BaseMutation):
dict(lines_for_warehouses),
info.context.plugins,
notify_customer,
+ approved=info.context.site.settings.fulfillment_auto_approve,
)
except InsufficientStock as exc:
errors = prepare_insufficient_stock_order_validation_errors(exc)
@@ -237,9 +247,9 @@ class FulfillmentUpdateTracking(BaseMutation):
)
class Arguments:
- id = graphene.ID(required=True, description="ID of an fulfillment to update.")
+ id = graphene.ID(required=True, description="ID of a fulfillment to update.")
input = FulfillmentUpdateTrackingInput(
- required=True, description="Fields required to update an fulfillment."
+ required=True, description="Fields required to update a fulfillment."
)
class Meta:
@@ -269,14 +279,22 @@ class FulfillmentUpdateTracking(BaseMutation):
return FulfillmentUpdateTracking(fulfillment=fulfillment, order=order)
+class FulfillmentCancelInput(graphene.InputObjectType):
+ warehouse_id = graphene.ID(
+ description="ID of a warehouse where items will be restocked. Optional "
+ "when fulfillment is in WAITING_FOR_APPROVAL state.",
+ required=False,
+ )
+
+
class FulfillmentCancel(BaseMutation):
fulfillment = graphene.Field(Fulfillment, description="A canceled fulfillment.")
order = graphene.Field(Order, description="Order which fulfillment was cancelled.")
class Arguments:
- id = graphene.ID(required=True, description="ID of an fulfillment to cancel.")
+ id = graphene.ID(required=True, description="ID of a fulfillment to cancel.")
input = FulfillmentCancelInput(
- required=True, description="Fields required to cancel an fulfillment."
+ required=False, description="Fields required to cancel a fulfillment."
)
class Meta:
@@ -286,22 +304,43 @@ class FulfillmentCancel(BaseMutation):
error_type_field = "order_errors"
@classmethod
- def perform_mutation(cls, _root, info, **data):
- warehouse_id = data.get("input").get("warehouse_id")
- warehouse = cls.get_node_or_error(
- info, warehouse_id, only_type="Warehouse", field="warehouse_id"
- )
- fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
-
+ def validate_fulfillment(cls, fulfillment, warehouse):
if not fulfillment.can_edit():
- err_msg = "This fulfillment can't be canceled"
raise ValidationError(
{
"fulfillment": ValidationError(
- err_msg, code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT
+ "This fulfillment can't be canceled",
+ code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT,
)
}
)
+ if (
+ fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL
+ and not warehouse
+ ):
+ raise ValidationError(
+ {
+ "warehouseId": ValidationError(
+ "This parameter is required for fulfillments which are not in "
+ "WAITING_FOR_APPROVAL state.",
+ code=OrderErrorCode.REQUIRED,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
+
+ warehouse = None
+ if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
+ warehouse = None
+ elif warehouse_id := data.get("input", {}).get("warehouse_id"):
+ warehouse = cls.get_node_or_error(
+ info, warehouse_id, only_type="Warehouse", field="warehouse_id"
+ )
+
+ cls.validate_fulfillment(fulfillment, warehouse)
order = fulfillment.order
cancel_fulfillment(
@@ -316,6 +355,56 @@ class FulfillmentCancel(BaseMutation):
return FulfillmentCancel(fulfillment=fulfillment, order=order)
+class FulfillmentApprove(BaseMutation):
+ fulfillment = graphene.Field(Fulfillment, description="An approved fulfillment.")
+ order = graphene.Field(Order, description="Order which fulfillment was approved.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a fulfillment to approve.")
+ notify_customer = graphene.Boolean(
+ required=True, description="True if confirmation email should be send."
+ )
+
+ class Meta:
+ description = "Approve existing fulfillment."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, fulfillment):
+ if fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL:
+ raise ValidationError(
+ "Invalid fulfillment status, only WAITING_FOR_APPROVAL "
+ "fulfillments can be accepted.",
+ code=OrderErrorCode.INVALID.value,
+ )
+ if (
+ not info.context.site.settings.fulfillment_allow_unpaid
+ and not fulfillment.order.is_fully_paid()
+ ):
+ raise ValidationError(
+ "Cannot fulfill unpaid order.",
+ code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER,
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ fulfillment = cls.get_node_or_error(info, data["id"], only_type="Fulfillment")
+ cls.clean_input(info, fulfillment)
+
+ order = fulfillment.order
+ fulfillment = approve_fulfillment(
+ fulfillment,
+ info.context.user,
+ info.context.app,
+ info.context.plugins,
+ notify_customer=data["notify_customer"],
+ )
+ order.refresh_from_db(fields=["status"])
+ return FulfillmentApprove(fulfillment=fulfillment, order=order)
+
+
class OrderRefundLineInput(graphene.InputObjectType):
order_line_id = graphene.ID(
description="The ID of the order line to refund.",
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index e38a263a1c..cb1f9115c8 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -24,6 +24,7 @@ from .mutations.draft_orders import (
DraftOrderUpdate,
)
from .mutations.fulfillments import (
+ FulfillmentApprove,
FulfillmentCancel,
FulfillmentRefundProducts,
FulfillmentReturnProducts,
@@ -151,6 +152,7 @@ class OrderMutations(graphene.ObjectType):
order_fulfill = OrderFulfill.Field()
order_fulfillment_cancel = FulfillmentCancel.Field()
+ order_fulfillment_approve = FulfillmentApprove.Field()
order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()
order_fulfillment_refund_products = FulfillmentRefundProducts.Field()
order_fulfillment_return_products = FulfillmentReturnProducts.Field()
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 8fa3023dbd..da748462c1 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -1,45 +1,51 @@
from unittest.mock import ANY, patch
import graphene
+import pytest
from django.contrib.auth.models import AnonymousUser
from ....core.exceptions import InsufficientStock, InsufficientStockData
from ....order import OrderStatus
from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
-from ....order.models import FulfillmentStatus
+from ....order.models import Fulfillment, FulfillmentStatus
from ....warehouse.models import Allocation, Stock
from ...tests.utils import assert_no_permission, get_graphql_content
ORDER_FULFILL_QUERY = """
-mutation fulfillOrder(
- $order: ID, $input: OrderFulfillInput!
-) {
- orderFulfill(
- order: $order,
- input: $input
+ mutation fulfillOrder(
+ $order: ID, $input: OrderFulfillInput!
) {
- errors {
- field
- code
- message
- warehouse
- orderLines
+ orderFulfill(
+ order: $order,
+ input: $input
+ ) {
+ errors {
+ field
+ code
+ message
+ warehouse
+ orderLines
+ }
}
}
-}
"""
[email protected]("fulfillment_auto_approve", [True, False])
@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill(
mock_create_fulfillments,
+ fulfillment_auto_approve,
staff_api_client,
staff_user,
order_with_lines,
permission_manage_orders,
warehouse,
+ site_settings,
):
+ site_settings.fulfillment_auto_approve = fulfillment_auto_approve
+ site_settings.save(update_fields=["fulfillment_auto_approve"])
order = order_with_lines
query = ORDER_FULFILL_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -77,7 +83,13 @@ def test_order_fulfill(
]
}
mock_create_fulfillments.assert_called_once_with(
- staff_user, None, order, fulfillment_lines_for_warehouses, ANY, True
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ True,
+ approved=fulfillment_auto_approve,
)
@@ -133,6 +145,7 @@ def test_order_fulfill_as_app(
fulfillment_lines_for_warehouses,
ANY,
True,
+ approved=True,
)
@@ -191,7 +204,13 @@ def test_order_fulfill_many_warehouses(
}
mock_create_fulfillments.assert_called_once_with(
- staff_user, None, order, fulfillment_lines_for_warehouses, ANY, True
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ True,
+ approved=True,
)
@@ -233,7 +252,13 @@ def test_order_fulfill_without_notification(
str(warehouse.pk): [{"order_line": order_line, "quantity": 1}]
}
mock_create_fulfillments.assert_called_once_with(
- staff_user, None, order, fulfillment_lines_for_warehouses, ANY, False
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ False,
+ approved=True,
)
@@ -291,7 +316,13 @@ def test_order_fulfill_lines_with_empty_quantity(
str(warehouse.pk): [{"order_line": order_line2, "quantity": 2}]
}
mock_create_fulfillments.assert_called_once_with(
- staff_user, None, order, fulfillment_lines_for_warehouses, ANY, True
+ staff_user,
+ None,
+ order,
+ fulfillment_lines_for_warehouses,
+ ANY,
+ True,
+ approved=True,
)
@@ -411,6 +442,46 @@ def test_order_fulfill_fulfilled_order(
mock_create_fulfillments.assert_not_called()
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+def test_order_fulfill_unpaid_order_and_disallow_unpaid(
+ mock_create_fulfillments,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ warehouse,
+ site_settings,
+):
+ site_settings.fulfillment_allow_unpaid = False
+ site_settings.save(update_fields=["fulfillment_allow_unpaid"])
+ query = ORDER_FULFILL_QUERY
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
+ order_line = order_with_lines.lines.first()
+ 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": {
+ "lines": [
+ {
+ "orderLineId": order_line_id,
+ "stocks": [{"quantity": 100, "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 data["errors"]
+ error = data["errors"][0]
+ assert error["field"] == "order"
+ assert error["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name
+
+ mock_create_fulfillments.assert_not_called()
+
+
@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
def test_order_fulfill_warehouse_with_insufficient_stock_exception(
mock_create_fulfillments,
@@ -555,13 +626,14 @@ def test_fulfillment_update_tracking(
permission_manage_orders,
):
query = """
- mutation updateFulfillment($id: ID!, $tracking: String) {
+ mutation updateFulfillment($id: ID!, $tracking: String) {
orderFulfillmentUpdateTracking(
- id: $id, input: {trackingNumber: $tracking}) {
- fulfillment {
- trackingNumber
- }
+ id: $id, input: { trackingNumber: $tracking }
+ ) {
+ fulfillment {
+ trackingNumber
}
+ }
}
"""
fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
@@ -577,16 +649,21 @@ def test_fulfillment_update_tracking(
FULFILLMENT_UPDATE_TRACKING_WITH_SEND_NOTIFICATION_QUERY = """
- mutation updateFulfillment($id: ID!, $tracking: String, $notifyCustomer: Boolean) {
- orderFulfillmentUpdateTracking(
- id: $id
- input: {trackingNumber: $tracking, notifyCustomer: $notifyCustomer}) {
- fulfillment {
- trackingNumber
- }
- }
+ mutation updateFulfillment(
+ $id: ID!
+ $tracking: String
+ $notifyCustomer: Boolean
+ ) {
+ orderFulfillmentUpdateTracking(
+ id: $id
+ input: { trackingNumber: $tracking, notifyCustomer: $notifyCustomer }
+ ) {
+ fulfillment {
+ trackingNumber
+ }
}
- """
+ }
+"""
@patch("saleor.graphql.order.mutations.fulfillments.send_fulfillment_update")
@@ -634,16 +711,20 @@ def test_fulfillment_update_tracking_send_notification_false(
CANCEL_FULFILLMENT_MUTATION = """
- mutation cancelFulfillment($id: ID!, $warehouseId: ID!) {
- orderFulfillmentCancel(id: $id, input: {warehouseId: $warehouseId}) {
- fulfillment {
- status
- }
- order {
- status
- }
- }
+ mutation cancelFulfillment($id: ID!, $warehouseId: ID) {
+ orderFulfillmentCancel(id: $id, input: {warehouseId: $warehouseId}) {
+ fulfillment {
+ status
+ }
+ order {
+ status
+ }
+ errors {
+ code
+ field
+ }
}
+ }
"""
@@ -674,6 +755,105 @@ def test_cancel_fulfillment(
assert event_restocked_items.user == staff_user
+def test_cancel_fulfillment_no_warehouse_id(
+ staff_api_client, fulfillment, permission_manage_orders
+):
+ query = """
+ mutation cancelFulfillment($id: ID!) {
+ orderFulfillmentCancel(id: $id) {
+ fulfillment {
+ status
+ }
+ order {
+ status
+ }
+ errors {
+ code
+ field
+ }
+ }
+ }
+ """
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["orderFulfillmentCancel"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "warehouseId"
+ assert error["code"] == OrderErrorCode.REQUIRED.name
+
+
+def test_cancel_fulfillment_awaiting_approval(
+ staff_api_client, fulfillment, permission_manage_orders
+):
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+ query = CANCEL_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentCancel"]
+ assert data["fulfillment"]["status"] == FulfillmentStatus.CANCELED.upper()
+ event_cancelled = fulfillment.order.events.get()
+ assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED)
+ assert event_cancelled.parameters == {"composed_id": fulfillment.composed_id}
+ assert event_cancelled.user == staff_api_client.user
+
+
+@patch("saleor.order.actions.restock_fulfillment_lines")
+def test_cancel_fulfillment_awaiting_approval_warehouse_specified(
+ mock_restock_lines,
+ staff_api_client,
+ fulfillment,
+ permission_manage_orders,
+ warehouse,
+):
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+ query = CANCEL_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentCancel"]
+ assert data["fulfillment"]["status"] == FulfillmentStatus.CANCELED.upper()
+ mock_restock_lines.assert_not_called()
+ event_cancelled = fulfillment.order.events.get()
+ assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED)
+ assert event_cancelled.parameters == {"composed_id": fulfillment.composed_id}
+ assert event_cancelled.user == staff_api_client.user
+
+
+def test_cancel_fulfillment_canceled_state(
+ staff_api_client, fulfillment, permission_manage_orders, warehouse
+):
+ query = CANCEL_FULFILLMENT_MUTATION
+ fulfillment.status = FulfillmentStatus.CANCELED
+ fulfillment.save(update_fields=["status"])
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["orderFulfillmentCancel"]["errors"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "fulfillment"
+ assert error["code"] == OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.name
+
+
def test_cancel_fulfillment_warehouse_without_stock(
order_line, warehouse, staff_api_client, permission_manage_orders, staff_user
):
@@ -770,26 +950,141 @@ def test_create_digital_fulfillment(
assert mock_email_fulfillment.call_count == 1
+APPROVE_FULFILLMENT_MUTATION = """
+ mutation approveFulfillment($id: ID!, $notifyCustomer: Boolean!) {
+ orderFulfillmentApprove(id: $id, notifyCustomer: $notifyCustomer) {
+ fulfillment {
+ status
+ }
+ order {
+ status
+ }
+ errors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_fulfillment_approve(
+ mock_email_fulfillment,
+ staff_api_client,
+ fulfillment,
+ permission_manage_orders,
+):
+ 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}
+ 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
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_fulfillment_approve_partial_order_fulfill(
+ mock_email_fulfillment,
+ staff_api_client,
+ fulfillment_awaiting_approval,
+ permission_manage_orders,
+):
+ query = APPROVE_FULFILLMENT_MUTATION
+ second_fulfillment = Fulfillment.objects.get(pk=fulfillment_awaiting_approval.pk)
+ second_fulfillment.pk = None
+ second_fulfillment.save()
+ fulfillment_id = graphene.Node.to_global_id(
+ "Fulfillment", fulfillment_awaiting_approval.id
+ )
+ variables = {"id": fulfillment_id, "notifyCustomer": False}
+ 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"] == "PARTIALLY_FULFILLED"
+ fulfillment_awaiting_approval.refresh_from_db()
+ assert fulfillment_awaiting_approval.status == FulfillmentStatus.FULFILLED
+
+ assert mock_email_fulfillment.call_count == 0
+
+
+def test_fulfillment_approve_invalid_status(
+ staff_api_client,
+ fulfillment,
+ permission_manage_orders,
+):
+ query = APPROVE_FULFILLMENT_MUTATION
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)
+ variables = {"id": fulfillment_id, "notifyCustomer": True}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentApprove"]
+ assert data["errors"][0]["code"] == OrderErrorCode.INVALID.name
+
+
+def test_fulfillment_approve_order_unpaid(
+ staff_api_client,
+ fulfillment,
+ site_settings,
+ permission_manage_orders,
+):
+ site_settings.fulfillment_allow_unpaid = False
+ site_settings.save(update_fields=["fulfillment_allow_unpaid"])
+ 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}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentApprove"]
+ assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name
+
+
QUERY_FULFILLMENT = """
-query fulfillment($id: ID!){
- order(id: $id){
- fulfillments{
- id
- fulfillmentOrder
- status
- trackingNumber
- warehouse{
+ query fulfillment($id: ID!) {
+ order(id: $id) {
+ fulfillments {
id
- }
- lines{
- orderLine{
+ fulfillmentOrder
+ status
+ trackingNumber
+ warehouse {
id
}
- quantity
+ lines {
+ orderLine {
+ id
+ }
+ quantity
+ }
}
}
}
-}
"""
@@ -830,22 +1125,22 @@ def test_fulfillment_query(
QUERY_ORDER_FULFILL_DATA = """
-query OrderFulfillData($id: ID!) {
- order(id: $id) {
- id
- lines {
- variant {
- stocks {
- warehouse {
- id
+ query OrderFulfillData($id: ID!) {
+ order(id: $id) {
+ id
+ lines {
+ variant {
+ stocks {
+ warehouse {
+ id
+ }
+ quantity
+ quantityAllocated
}
- quantity
- quantityAllocated
}
}
}
}
-}
"""
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 40adef51fc..0650c840a7 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -69,6 +69,7 @@ from ..shipping.types import ShippingMethod
from ..warehouse.types import Allocation, Warehouse
from .dataloaders import (
AllocationsByOrderLineIdLoader,
+ FulfillmentLinesAwaitingApprovalByOrderLineIdLoader,
FulfillmentLinesByIdLoader,
FulfillmentsByOrderIdLoader,
OrderByIdLoader,
@@ -440,6 +441,9 @@ class OrderLine(CountableDjangoObjectType):
graphene.NonNull(Allocation),
description="List of allocations across warehouses.",
)
+ quantity_to_fulfill = graphene.Int(
+ required=True, description="A quantity of items remaining to be fulfilled."
+ )
unit_discount_type = graphene.Field(
DiscountValueTypeEnum,
description="Type of the discount: fixed or percent",
@@ -510,6 +514,18 @@ class OrderLine(CountableDjangoObjectType):
def resolve_unit_price(root: models.OrderLine, _info):
return root.unit_price
+ @staticmethod
+ def resolve_quantity_to_fulfill(root: models.OrderLine, info):
+ def _resolve_quantity_to_fulfill(fulfillment_lines):
+ awaiting_quantity = sum(map(lambda f: f.quantity, fulfillment_lines)) or 0
+ return root.quantity - root.quantity_fulfilled - awaiting_quantity
+
+ return (
+ FulfillmentLinesAwaitingApprovalByOrderLineIdLoader(info.context)
+ .load(root.id)
+ .then(_resolve_quantity_to_fulfill)
+ )
+
@staticmethod
def resolve_undiscounted_unit_price(root: models.OrderLine, _info):
return root.undiscounted_unit_price
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7a1ac56552..2309de6243 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2144,6 +2144,13 @@ type Fulfillment implements Node & ObjectWithMetadata {
warehouse: Warehouse
}
+type FulfillmentApprove {
+ fulfillment: Fulfillment
+ order: Order
+ orderErrors: [OrderError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
+ errors: [OrderError!]!
+}
+
type FulfillmentCancel {
fulfillment: Fulfillment
order: Order
@@ -2152,7 +2159,7 @@ type FulfillmentCancel {
}
input FulfillmentCancelInput {
- warehouseId: ID!
+ warehouseId: ID
}
type FulfillmentLine implements Node {
@@ -2184,6 +2191,7 @@ enum FulfillmentStatus {
REPLACED
REFUNDED_AND_RETURNED
CANCELED
+ WAITING_FOR_APPROVAL
}
type FulfillmentUpdateTracking {
@@ -3694,7 +3702,8 @@ type Mutation {
orderCapture(amount: PositiveDecimal!, id: ID!): OrderCapture
orderConfirm(id: ID!): OrderConfirm
orderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfill
- orderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancel
+ orderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput): FulfillmentCancel
+ orderFulfillmentApprove(id: ID!, notifyCustomer: Boolean!): FulfillmentApprove
orderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking
orderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProducts
orderFulfillmentReturnProducts(input: OrderReturnProductsInput!, order: ID!): FulfillmentReturnProducts
@@ -4038,6 +4047,7 @@ enum OrderErrorCode {
CANNOT_DELETE
CANNOT_DISCOUNT
CANNOT_REFUND
+ CANNOT_FULFILL_UNPAID_ORDER
CAPTURE_INACTIVE_PAYMENT
NOT_EDITABLE
FULFILL_ORDER_LINE
@@ -4168,6 +4178,7 @@ enum OrderEventsEnum {
FULFILLMENT_REFUNDED
FULFILLMENT_RETURNED
FULFILLMENT_REPLACED
+ FULFILLMENT_AWAITS_APPROVAL
TRACKING_UPDATED
NOTE_ADDED
OTHER
@@ -4226,6 +4237,7 @@ type OrderLine implements Node {
translatedProductName: String!
translatedVariantName: String!
allocations: [Allocation!]
+ quantityToFulfill: Int!
unitDiscountType: DiscountValueTypeEnum
}
@@ -6146,6 +6158,8 @@ type Shop {
phonePrefixes: [String]!
headerText: String
includeTaxesInPrices: Boolean!
+ fulfillmentAutoApprove: Boolean!
+ fulfillmentAllowUnpaid: Boolean!
displayGrossPrices: Boolean!
chargeTaxesOnShipping: Boolean!
trackInventoryByDefault: Boolean
@@ -6204,6 +6218,8 @@ input ShopSettingsInput {
trackInventoryByDefault: Boolean
defaultWeightUnit: WeightUnitsEnum
automaticFulfillmentDigitalProducts: Boolean
+ fulfillmentAutoApprove: Boolean
+ fulfillmentAllowUnpaid: Boolean
defaultDigitalMaxDownloads: Int
defaultDigitalUrlValidDays: Int
defaultMailSenderName: String
@@ -7008,6 +7024,7 @@ enum WebhookEventTypeEnum {
CHECKOUT_CREATED
CHECKOUT_UPDATED
FULFILLMENT_CREATED
+ FULFILLMENT_CANCELED
NOTIFY_USER
PAGE_CREATED
PAGE_UPDATED
@@ -7044,6 +7061,7 @@ enum WebhookSampleEventTypeEnum {
CHECKOUT_CREATED
CHECKOUT_UPDATED
FULFILLMENT_CREATED
+ FULFILLMENT_CANCELED
NOTIFY_USER
PAGE_CREATED
PAGE_UPDATED
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 0d40b0329b..152b742d08 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -28,6 +28,12 @@ class ShopSettingsInput(graphene.InputObjectType):
automatic_fulfillment_digital_products = graphene.Boolean(
description="Enable automatic fulfillment for all digital products."
)
+ fulfillment_auto_approve = graphene.Boolean(
+ description="Enable automatic approval of all new fulfillments."
+ )
+ fulfillment_allow_unpaid = graphene.Boolean(
+ description="Enable ability to approve fulfillments which are unpaid."
+ )
default_digital_max_downloads = graphene.Int(
description="Default number of max downloads per digital content URL."
)
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index e20bead288..7092814f1b 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -321,7 +321,9 @@ def test_shop_settings_mutation(
shop {
headerText,
includeTaxesInPrices,
- chargeTaxesOnShipping
+ chargeTaxesOnShipping,
+ fulfillmentAutoApprove,
+ fulfillmentAllowUnpaid
}
errors {
field,
@@ -337,6 +339,7 @@ def test_shop_settings_mutation(
"includeTaxesInPrices": False,
"headerText": "Lorem ipsum",
"chargeTaxesOnShipping": new_charge_taxes_on_shipping,
+ "fulfillmentAllowUnpaid": False,
}
}
response = staff_api_client.post_graphql(
@@ -344,9 +347,11 @@ def test_shop_settings_mutation(
)
content = get_graphql_content(response)
data = content["data"]["shopSettingsUpdate"]["shop"]
- assert data["includeTaxesInPrices"] is False
assert data["headerText"] == "Lorem ipsum"
+ assert data["includeTaxesInPrices"] is False
assert data["chargeTaxesOnShipping"] == new_charge_taxes_on_shipping
+ assert data["fulfillmentAutoApprove"] is True
+ assert data["fulfillmentAllowUnpaid"] is False
site_settings.refresh_from_db()
assert not site_settings.include_taxes_in_prices
assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index ee9b4226bf..54a266aca2 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -164,6 +164,12 @@ class Shop(graphene.ObjectType):
include_taxes_in_prices = graphene.Boolean(
description="Include taxes in prices.", required=True
)
+ fulfillment_auto_approve = graphene.Boolean(
+ description="Automatically approve all new fulfillments.", required=True
+ )
+ fulfillment_allow_unpaid = graphene.Boolean(
+ description="Allow to approve fulfillments which are unpaid.", required=True
+ )
display_gross_prices = graphene.Boolean(
description="Display prices with tax in store.", required=True
)
@@ -291,6 +297,14 @@ class Shop(graphene.ObjectType):
def resolve_include_taxes_in_prices(_, info):
return info.context.site.settings.include_taxes_in_prices
+ @staticmethod
+ def resolve_fulfillment_auto_approve(_, info):
+ return info.context.site.settings.fulfillment_auto_approve
+
+ @staticmethod
+ def resolve_fulfillment_allow_unpaid(_, info):
+ return info.context.site.settings.fulfillment_allow_unpaid
+
@staticmethod
def resolve_display_gross_prices(_, info):
return info.context.site.settings.display_gross_prices
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 9f71ca32df..4fee1c3840 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -42,6 +42,8 @@ def description(enum):
return "An order is fulfilled."
elif enum == WebhookEventTypeEnum.FULFILLMENT_CREATED:
return "A new fulfillment is created."
+ elif enum == WebhookEventTypeEnum.FULFILLMENT_CANCELED:
+ return "A fulfillment is cancelled."
elif enum == WebhookEventTypeEnum.PAGE_CREATED:
return "A new page is created."
elif enum == WebhookEventTypeEnum.PAGE_UPDATED:
diff --git a/saleor/graphql/webhook/tests/test_webhook.py b/saleor/graphql/webhook/tests/test_webhook.py
index 133e506397..f84a52d56a 100644
--- a/saleor/graphql/webhook/tests/test_webhook.py
+++ b/saleor/graphql/webhook/tests/test_webhook.py
@@ -461,6 +461,7 @@ SAMPLE_PAYLOAD_QUERY = """
(WebhookSampleEventTypeEnum.CHECKOUT_CREATED, False),
(WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, False),
(WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, True),
+ (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, True),
(WebhookSampleEventTypeEnum.PAGE_CREATED, False),
(WebhookSampleEventTypeEnum.PAGE_UPDATED, False),
(WebhookSampleEventTypeEnum.PAGE_DELETED, False),
@@ -504,6 +505,7 @@ def test_sample_payload_query_by_app(
(WebhookSampleEventTypeEnum.CHECKOUT_CREATED, True),
(WebhookSampleEventTypeEnum.CHECKOUT_UPDATED, True),
(WebhookSampleEventTypeEnum.FULFILLMENT_CREATED, False),
+ (WebhookSampleEventTypeEnum.FULFILLMENT_CANCELED, False),
(WebhookSampleEventTypeEnum.PAGE_CREATED, True),
(WebhookSampleEventTypeEnum.PAGE_UPDATED, True),
(WebhookSampleEventTypeEnum.PAGE_DELETED, True),
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index f94b0820cc..d00c755374 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -56,6 +56,9 @@ class FulfillmentStatus:
)
REPLACED = "replaced" # group of replaced products
CANCELED = "canceled" # fulfilled group of products in an order marked as canceled
+ WAITING_FOR_APPROVAL = (
+ "waiting_for_approval" # group of products waiting for approval
+ )
CHOICES = [
(FULFILLED, "Fulfilled"),
@@ -64,6 +67,7 @@ class FulfillmentStatus:
(REPLACED, "Replaced"),
(REFUNDED_AND_RETURNED, "Refunded and returned"),
(CANCELED, "Canceled"),
+ (WAITING_FOR_APPROVAL, "Waiting for approval"),
]
@@ -119,6 +123,7 @@ class OrderEvents:
FULFILLMENT_REFUNDED = "fulfillment_refunded"
FULFILLMENT_RETURNED = "fulfillment_returned"
FULFILLMENT_REPLACED = "fulfillment_replaced"
+ FULFILLMENT_AWAITS_APPROVAL = "fulfillment_awaits_approval"
TRACKING_UPDATED = "tracking_updated"
NOTE_ADDED = "note_added"
@@ -167,6 +172,7 @@ class OrderEvents:
(FULFILLMENT_REFUNDED, "Some items were refunded"),
(FULFILLMENT_RETURNED, "Some items were returned"),
(FULFILLMENT_REPLACED, "Some items were replaced"),
+ (FULFILLMENT_AWAITS_APPROVAL, "Fulfillments awaits approval"),
(TRACKING_UPDATED, "The fulfillment's tracking code was updated"),
(NOTE_ADDED, "A note was added to the order"),
(OTHER, "An unknown order event containing a message"),
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 8548105084..71dc5709e3 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -163,8 +163,8 @@ def cancel_order(
order.status = OrderStatus.CANCELED
order.save(update_fields=["status"])
- manager.order_cancelled(order)
- manager.order_updated(order)
+ transaction.on_commit(lambda: manager.order_cancelled(order))
+ transaction.on_commit(lambda: manager.order_updated(order))
send_order_canceled_confirmation(order, user, app, manager)
@@ -222,13 +222,13 @@ def order_fulfilled(
events.fulfillment_fulfilled_items_event(
order=order, user=user, app=app, fulfillment_lines=fulfillment_lines
)
- manager.order_updated(order)
+ transaction.on_commit(lambda: manager.order_updated(order))
for fulfillment in fulfillments:
- manager.fulfillment_created(fulfillment)
+ transaction.on_commit(lambda: manager.fulfillment_created(fulfillment))
if order.status == OrderStatus.FULFILLED:
- manager.order_fulfilled(order)
+ transaction.on_commit(lambda: manager.order_fulfilled(order))
if notify_customer:
for fulfillment in fulfillments:
@@ -237,6 +237,23 @@ def order_fulfilled(
)
+@traced_atomic_transaction()
+def order_awaits_fulfillment_approval(
+ fulfillments: List["Fulfillment"],
+ user: "User",
+ app: Optional["App"],
+ fulfillment_lines: List["FulfillmentLine"],
+ manager: "PluginsManager",
+ _notify_customer=True,
+):
+ order = fulfillments[0].order
+ update_order_status(order)
+ events.fulfillment_awaits_approval_event(
+ order=order, user=user, app=app, fulfillment_lines=fulfillment_lines
+ )
+ transaction.on_commit(lambda: manager.order_updated(order))
+
+
def order_shipping_updated(order: "Order", manager: "PluginsManager"):
recalculate_order(order)
manager.order_updated(order)
@@ -294,29 +311,69 @@ def cancel_fulfillment(
fulfillment: "Fulfillment",
user: "User",
app: Optional["App"],
- warehouse: "Warehouse",
+ warehouse: Optional["Warehouse"],
manager: "PluginsManager",
):
"""Cancel fulfillment.
- Return products to corresponding stocks.
+ Return products to corresponding stocks if warehouse was defined.
"""
fulfillment = Fulfillment.objects.select_for_update().get(pk=fulfillment.pk)
- restock_fulfillment_lines(fulfillment, warehouse)
events.fulfillment_canceled_event(
order=fulfillment.order, user=user, app=app, fulfillment=fulfillment
)
- events.fulfillment_restocked_items_event(
- order=fulfillment.order,
- user=user,
- app=app,
- fulfillment=fulfillment,
- warehouse_pk=warehouse.pk,
- )
+ if warehouse:
+ restock_fulfillment_lines(fulfillment, warehouse)
+ events.fulfillment_restocked_items_event(
+ order=fulfillment.order,
+ user=user,
+ app=app,
+ fulfillment=fulfillment,
+ warehouse_pk=warehouse.pk,
+ )
fulfillment.status = FulfillmentStatus.CANCELED
fulfillment.save(update_fields=["status"])
update_order_status(fulfillment.order)
- manager.order_updated(fulfillment.order)
+ transaction.on_commit(lambda: manager.fulfillment_canceled(fulfillment))
+ transaction.on_commit(lambda: manager.order_updated(fulfillment.order))
+
+
+@traced_atomic_transaction()
+def approve_fulfillment(
+ fulfillment: Fulfillment,
+ user: "User",
+ app: Optional["App"],
+ manager: "PluginsManager",
+ notify_customer=True,
+):
+ 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 = [
+ OrderLineData(
+ line=f_line.order_line,
+ quantity=f_line.quantity,
+ variant=f_line.order_line.variant,
+ warehouse_pk=str(f_line.stock.warehouse_id), # type: ignore
+ )
+ for f_line in fulfillment.lines.all()
+ ]
+ fulfill_order_lines(lines_to_fulfill)
+ order.refresh_from_db()
+ update_order_status(order)
+
+ transaction.on_commit(lambda: manager.order_updated(order))
+ if order.status == OrderStatus.FULFILLED:
+ transaction.on_commit(lambda: manager.order_fulfilled(order))
+
+ return fulfillment
@traced_atomic_transaction()
@@ -442,6 +499,7 @@ def _create_fulfillment_lines(
warehouse_pk: str,
lines_data: List[Dict],
channel_slug: str,
+ decrease_stock: bool = True,
) -> List[FulfillmentLine]:
"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.
@@ -458,6 +516,7 @@ def _create_fulfillment_lines(
...
]
channel_slug (str): Channel for which fulfillment lines should be created.
+ decrease_stock (Bool): Stocks will get decreased if this is True.
Return:
List[FulfillmentLine]: Unsaved fulfillmet lines created for this fulfillment
@@ -518,7 +577,7 @@ def _create_fulfillment_lines(
if insufficient_stocks:
raise InsufficientStock(insufficient_stocks)
- if lines_info:
+ if lines_info and decrease_stock:
fulfill_order_lines(lines_info)
return fulfillment_lines
@@ -532,6 +591,7 @@ def create_fulfillments(
fulfillment_lines_for_warehouses: Dict,
manager: "PluginsManager",
notify_customer: bool = True,
+ approved: bool = True,
) -> List[Fulfillment]:
"""Fulfill order.
@@ -556,6 +616,8 @@ def create_fulfillments(
manager (PluginsManager): Base manager for handling plugins logic.
notify_customer (bool): If `True` system send email about
fulfillments to customer.
+ approved (Boolean): fulfillments will have status fulfilled if it's True,
+ otherwise waiting_for_approval.
Return:
List[Fulfillment]: Fulfillmet with lines created for this order
@@ -568,8 +630,13 @@ def create_fulfillments(
"""
fulfillments: List[Fulfillment] = []
fulfillment_lines: List[FulfillmentLine] = []
+ status = (
+ FulfillmentStatus.FULFILLED
+ if approved
+ else FulfillmentStatus.WAITING_FOR_APPROVAL
+ )
for warehouse_pk in fulfillment_lines_for_warehouses:
- fulfillment = Fulfillment.objects.create(order=order)
+ fulfillment = Fulfillment.objects.create(order=order, status=status)
fulfillments.append(fulfillment)
fulfillment_lines.extend(
_create_fulfillment_lines(
@@ -577,12 +644,16 @@ def create_fulfillments(
warehouse_pk,
fulfillment_lines_for_warehouses[warehouse_pk],
order.channel.slug,
+ decrease_stock=approved,
)
)
FulfillmentLine.objects.bulk_create(fulfillment_lines)
+ post_creation_func = (
+ order_fulfilled if approved else order_awaits_fulfillment_approval
+ )
transaction.on_commit(
- lambda: order_fulfilled(
+ lambda: post_creation_func( # type: ignore
fulfillments,
user,
app,
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 51b521a850..62eebab428 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -8,6 +8,7 @@ class OrderErrorCode(Enum):
CANNOT_DELETE = "cannot_delete"
CANNOT_DISCOUNT = "cannot_discount"
CANNOT_REFUND = "cannot_refund"
+ CANNOT_FULFILL_UNPAID_ORDER = "cannot_fulfill_unpaid_order"
CAPTURE_INACTIVE_PAYMENT = "capture_inactive_payment"
NOT_EDITABLE = "not_editable"
FULFILL_ORDER_LINE = "fulfill_order_line"
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 7bde2df95d..73ebfc5ef0 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -504,6 +504,24 @@ def fulfillment_fulfilled_items_event(
)
+def fulfillment_awaits_approval_event(
+ *,
+ order: Order,
+ user: UserType,
+ app: AppType,
+ fulfillment_lines: List[FulfillmentLine]
+) -> OrderEvent:
+ if not user_is_valid(user):
+ user = None
+ return OrderEvent.objects.create(
+ order=order,
+ type=OrderEvents.FULFILLMENT_AWAITS_APPROVAL,
+ user=user,
+ app=app,
+ parameters={"awaiting_fulfillments": [line.pk for line in fulfillment_lines]},
+ )
+
+
def order_returned_event(
*,
order: Order,
diff --git a/saleor/order/migrations/0114_auto_20210722_1146.py b/saleor/order/migrations/0114_auto_20210722_1146.py
new file mode 100644
index 0000000000..c8fbe67884
--- /dev/null
+++ b/saleor/order/migrations/0114_auto_20210722_1146.py
@@ -0,0 +1,84 @@
+# Generated by Django 3.2.5 on 2021-07-22 11:46
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0113_orderevent_app"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="fulfillment",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("fulfilled", "Fulfilled"),
+ ("refunded", "Refunded"),
+ ("returned", "Returned"),
+ ("replaced", "Replaced"),
+ ("refunded_and_returned", "Refunded and returned"),
+ ("canceled", "Canceled"),
+ ("waiting_for_approval", "Waiting for approval"),
+ ],
+ default="fulfilled",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("ADDED_PRODUCTS", "added_products"),
+ ("REMOVED_PRODUCTS", "removed_products"),
+ ("PLACED", "placed"),
+ ("PLACED_FROM_DRAFT", "placed_from_draft"),
+ ("OVERSOLD_ITEMS", "oversold_items"),
+ ("CANCELED", "canceled"),
+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),
+ ("ORDER_FULLY_PAID", "order_fully_paid"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),
+ (
+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",
+ "order_discount_automatically_updated",
+ ),
+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),
+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),
+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),
+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),
+ ("ORDER_LINE_PRODUCT_DELETED", "order_line_product_deleted"),
+ ("ORDER_LINE_VARIANT_DELETED", "order_line_variant_deleted"),
+ ("UPDATED_ADDRESS", "updated_address"),
+ ("EMAIL_SENT", "email_sent"),
+ ("CONFIRMED", "confirmed"),
+ ("PAYMENT_AUTHORIZED", "payment_authorized"),
+ ("PAYMENT_CAPTURED", "payment_captured"),
+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),
+ ("PAYMENT_REFUNDED", "payment_refunded"),
+ ("PAYMENT_VOIDED", "payment_voided"),
+ ("PAYMENT_FAILED", "payment_failed"),
+ ("INVOICE_REQUESTED", "invoice_requested"),
+ ("INVOICE_GENERATED", "invoice_generated"),
+ ("INVOICE_UPDATED", "invoice_updated"),
+ ("INVOICE_SENT", "invoice_sent"),
+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),
+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),
+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),
+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("FULFILLMENT_AWAITS_APPROVAL", "fulfillment_awaits_approval"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]
diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.py
index 5880f527b8..e9f7831497 100644
--- a/saleor/order/tests/test_fulfullments_actions.py
+++ b/saleor/order/tests/test_fulfullments_actions.py
@@ -3,6 +3,7 @@ from unittest.mock import patch
import pytest
from ...core.exceptions import InsufficientStock
+from ...order import OrderEvents
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
from ...warehouse.models import Allocation, Stock
@@ -54,11 +55,133 @@ def test_create_fulfillments(
== 0
)
+ events = order.events.all()
+ assert len(events) == 1
+ event = events[0]
+ assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
+ assert event.user == staff_user
+ assert set(event.parameters["fulfilled_items"]) == set(
+ [fulfillment_lines[0].pk, fulfillment_lines[1].pk]
+ )
+
mock_email_fulfillment.assert_called_once_with(
order, order.fulfillments.get(), staff_user, None, manager
)
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_require_approval(
+ mock_email_fulfillment,
+ staff_user,
+ order_with_lines,
+ warehouse,
+):
+ order = order_with_lines
+ order_line1, order_line2 = order.lines.all()
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+ manager = get_plugins_manager()
+ [fulfillment] = create_fulfillments(
+ staff_user, None, order, fulfillment_lines_for_warehouses, manager, True, False
+ )
+ flush_post_commit_hooks()
+
+ order.refresh_from_db()
+ fulfillment_lines = FulfillmentLine.objects.filter(
+ fulfillment__order=order
+ ).order_by("pk")
+ assert fulfillment_lines[0].stock == order_line1.variant.stocks.get()
+ assert fulfillment_lines[0].quantity == 3
+ assert fulfillment_lines[1].stock == order_line2.variant.stocks.get()
+ assert fulfillment_lines[1].quantity == 2
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 0
+ assert order_line2.quantity_fulfilled == 0
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 2
+ )
+
+ events = order.events.all()
+ assert len(events) == 1
+ event = events[0]
+ assert event.type == OrderEvents.FULFILLMENT_AWAITS_APPROVAL
+ assert event.user == staff_user
+ assert set(event.parameters["awaiting_fulfillments"]) == set(
+ [fulfillment_lines[0].pk, fulfillment_lines[1].pk]
+ )
+
+ mock_email_fulfillment.assert_not_called()
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_require_approval_as_app(
+ mock_email_fulfillment,
+ app,
+ order_with_lines,
+ warehouse,
+):
+ order = order_with_lines
+ order_line1, order_line2 = order.lines.all()
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+ manager = get_plugins_manager()
+ [fulfillment] = create_fulfillments(
+ None, app, order, fulfillment_lines_for_warehouses, manager, True, False
+ )
+ flush_post_commit_hooks()
+
+ order.refresh_from_db()
+ fulfillment_lines = FulfillmentLine.objects.filter(
+ fulfillment__order=order
+ ).order_by("pk")
+ assert fulfillment_lines[0].stock == order_line1.variant.stocks.get()
+ assert fulfillment_lines[0].quantity == 3
+ assert fulfillment_lines[1].stock == order_line2.variant.stocks.get()
+ assert fulfillment_lines[1].quantity == 2
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 0
+ assert order_line2.quantity_fulfilled == 0
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 2
+ )
+
+ events = order.events.all()
+ assert len(events) == 1
+ event = events[0]
+ assert event.type == OrderEvents.FULFILLMENT_AWAITS_APPROVAL
+ assert event.user is None
+ assert event.app == app
+ assert set(event.parameters["awaiting_fulfillments"]) == set(
+ [fulfillment_lines[0].pk, fulfillment_lines[1].pk]
+ )
+
+ mock_email_fulfillment.assert_not_called()
+
+
@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
def test_create_fulfillments_without_notification(
mock_email_fulfillment,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index ed1eac3bf7..83bcb06208 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -542,6 +542,16 @@ class BasePlugin:
"""
return NotImplemented
+ def fulfillment_canceled(
+ self, fulfillment: "Fulfillment", previous_value: Any
+ ) -> Any:
+ """Trigger when fulfillemnt is cancelled.
+
+ Overwrite this method if you need to trigger specific logic when a fulfillment is
+ cancelled.
+ """
+ return NotImplemented
+
def checkout_created(self, checkout: "Checkout", previous_value: Any) -> Any:
"""Trigger when checkout is created.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index e8814e721e..b3b1ccc526 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -599,6 +599,15 @@ class PluginsManager(PaymentInterface):
channel_slug=fulfillment.order.channel.slug,
)
+ def fulfillment_canceled(self, fulfillment: "Fulfillment"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "fulfillment_canceled",
+ default_value,
+ fulfillment,
+ channel_slug=fulfillment.order.channel.slug,
+ )
+
def checkout_created(self, checkout: "Checkout"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c1a14430e9..5650c88f91 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -131,6 +131,14 @@ class WebhookPlugin(BasePlugin):
WebhookEventType.FULFILLMENT_CREATED, fulfillment_data
)
+ def fulfillment_canceled(self, fulfillment: "Fulfillment", previous_value):
+ if not self.active:
+ return previous_value
+ fulfillment_data = generate_fulfillment_payload(fulfillment)
+ trigger_webhooks_for_event.delay(
+ WebhookEventType.FULFILLMENT_CANCELED, fulfillment_data
+ )
+
def customer_created(self, customer: "User", previous_value: Any) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/site/migrations/0030_auto_20210722_1141.py b/saleor/site/migrations/0030_auto_20210722_1141.py
new file mode 100644
index 0000000000..a7216c810f
--- /dev/null
+++ b/saleor/site/migrations/0030_auto_20210722_1141.py
@@ -0,0 +1,23 @@
+# Generated by Django 3.2.5 on 2021-07-22 11:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("site", "0029_auto_20210120_0934"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="fulfillment_allow_unpaid",
+ field=models.BooleanField(default=True),
+ ),
+ migrations.AddField(
+ model_name="sitesettings",
+ name="fulfillment_auto_approve",
+ field=models.BooleanField(default=True),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 3cf26a4d76..83a3eb9adf 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -65,6 +65,8 @@ class SiteSettings(models.Model):
default_mail_sender_address = models.EmailField(blank=True, null=True)
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
automatically_confirm_all_new_orders = models.BooleanField(default=True)
+ fulfillment_auto_approve = models.BooleanField(default=True)
+ fulfillment_allow_unpaid = models.BooleanField(default=True)
translated = TranslationProxy()
class Meta:
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 8638f735bd..f6c7749796 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -64,7 +64,13 @@ from ..order.events import (
fulfillment_refunded_event,
order_added_products_event,
)
-from ..order.models import FulfillmentStatus, Order, OrderEvent, OrderLine
+from ..order.models import (
+ FulfillmentLine,
+ FulfillmentStatus,
+ Order,
+ OrderEvent,
+ OrderLine,
+)
from ..order.utils import recalculate_order
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
@@ -2985,7 +2991,7 @@ def order_events(order):
@pytest.fixture
def fulfilled_order(order_with_lines):
order = order_with_lines
- invoice = order.invoices.create(
+ order.invoices.create(
url="http://www.example.com/invoice.pdf",
number="01/12/2020/TEST",
created=datetime.datetime.now(tz=pytz.utc),
@@ -3059,6 +3065,25 @@ def fulfillment(fulfilled_order):
return fulfilled_order.fulfillments.first()
+def fulfillment_awaiting_approval(fulfilled_order):
+ order_line = fulfilled_order.lines.first()
+ order_line.quantity_fulfilled = 0
+ order_line.save(update_fields=["quantity_fulfilled"])
+
+ fulfillment = fulfilled_order.fulfillments.first()
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+
+ fulfillment_lines_to_update = []
+ for f_line in fulfillment.lines.all():
+ f_line.quantity = 1
+ fulfillment_lines_to_update.append(f_line)
+ FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])
+
+ return fulfillment
+
+
@pytest.fixture
def draft_order(order_with_lines):
Allocation.objects.filter(order_line__order=order_with_lines).delete()
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 6c2c6ac25b..f56b41cbfc 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -16,6 +16,7 @@ class WebhookEventType:
ORDER_FULLY_PAID = "order_fully_paid"
ORDER_UPDATED = "order_updated"
ORDER_CANCELLED = "order_cancelled"
+ FULFILLMENT_CANCELED = "fulfillment_canceled"
ORDER_FULFILLED = "order_fulfilled"
INVOICE_REQUESTED = "invoice_requested"
@@ -77,6 +78,7 @@ class WebhookEventType:
CHECKOUT_CREATED: "Checkout created",
CHECKOUT_UPDATED: "Checkout updated",
FULFILLMENT_CREATED: "Fulfillment_created",
+ FULFILLMENT_CANCELED: "Fulfillment_cancelled",
NOTIFY_USER: "Notify user",
PAGE_CREATED: "Page Created",
PAGE_UPDATED: "Page Updated",
@@ -114,6 +116,7 @@ class WebhookEventType:
(CHECKOUT_CREATED, DISPLAY_LABELS[CHECKOUT_CREATED]),
(CHECKOUT_UPDATED, DISPLAY_LABELS[CHECKOUT_UPDATED]),
(FULFILLMENT_CREATED, DISPLAY_LABELS[FULFILLMENT_CREATED]),
+ (FULFILLMENT_CANCELED, DISPLAY_LABELS[FULFILLMENT_CANCELED]),
(NOTIFY_USER, DISPLAY_LABELS[NOTIFY_USER]),
(PAGE_CREATED, DISPLAY_LABELS[PAGE_CREATED]),
(PAGE_UPDATED, DISPLAY_LABELS[PAGE_UPDATED]),
@@ -160,6 +163,7 @@ class WebhookEventType:
CHECKOUT_CREATED: CheckoutPermissions.MANAGE_CHECKOUTS,
CHECKOUT_UPDATED: CheckoutPermissions.MANAGE_CHECKOUTS,
FULFILLMENT_CREATED: OrderPermissions.MANAGE_ORDERS,
+ FULFILLMENT_CANCELED: OrderPermissions.MANAGE_ORDERS,
NOTIFY_USER: AccountPermissions.MANAGE_USERS,
PAGE_CREATED: PagePermissions.MANAGE_PAGES,
PAGE_UPDATED: PagePermissions.MANAGE_PAGES,