Skip to content

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

Move fulfillment create outside mutation

fowczrek67acc9a56f58
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 89847f8a44..929fb9d108 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -2,7 +2,6 @@ from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
-from django.db import transaction
from django.template.defaultfilters import pluralize
from ....core.exceptions import InsufficientStock
@@ -10,18 +9,17 @@ from ....core.permissions import OrderPermissions
from ....order import models
from ....order.actions import (
cancel_fulfillment,
- fulfill_order_line,
+ create_fulfillments,
fulfillment_tracking_updated,
- order_fulfilled,
)
from ....order.emails import send_fulfillment_update
from ....order.error_codes import OrderErrorCode
from ...core.mutations import BaseMutation
from ...core.types.common import OrderError
-from ...core.utils import from_global_id_strict_type
+from ...core.utils import from_global_id_strict_type, get_duplicated_values
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
from ...order.types import Fulfillment, Order
-from ...utils import get_user_or_service_account_from_context
+from ...utils import get_user_or_app_from_context
from ...warehouse.types import Warehouse
from ..types import OrderLine
@@ -42,7 +40,7 @@ class OrderFulfillLineInput(graphene.InputObjectType):
stocks = graphene.List(
graphene.NonNull(OrderFulfillStockInput),
required=True,
- description="Stocks from item line be fulfilled.",
+ description="List of stock items to create.",
)
@@ -50,7 +48,7 @@ class OrderFulfillInput(graphene.InputObjectType):
lines = graphene.List(
graphene.NonNull(OrderFulfillLineInput),
required=True,
- description="Item line to be fulfilled.",
+ description="List of items informing how to fulfill the order.",
)
notify_customer = graphene.Boolean(
description="If true, send an email notification to the customer."
@@ -102,7 +100,9 @@ class FulfillmentUpdatePrivateMeta(UpdateMetaBaseMutation):
class OrderFulfill(BaseMutation):
- fulfillments = graphene.List(Fulfillment, description="A created fulfillments.")
+ fulfillments = graphene.List(
+ Fulfillment, description="List of created fulfillments."
+ )
order = graphene.Field(Order, description="Fulfilled order.")
class Arguments:
@@ -114,7 +114,7 @@ class OrderFulfill(BaseMutation):
)
class Meta:
- description = "Creates a new fulfillments for an order."
+ description = "Creates new fulfillments for an order."
permissions = (OrderPermissions.MANAGE_ORDERS,)
error_type_class = OrderError
error_type_field = "order_errors"
@@ -144,28 +144,26 @@ class OrderFulfill(BaseMutation):
@classmethod
def check_warehouses_for_duplicates(cls, warehouse_ids):
for warehouse_ids_for_line in warehouse_ids:
- duplicates = {
- id
- for id in warehouse_ids_for_line
- if warehouse_ids_for_line.count(id) > 1
- }
+ duplicates = get_duplicated_values(warehouse_ids_for_line)
if duplicates:
raise ValidationError(
{
"warehouse": ValidationError(
- "Duplicated warehouse ID.", code=OrderErrorCode.UNIQUE
+ "Duplicated warehouse ID.",
+ code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
)
}
)
@classmethod
def check_lines_for_duplicates(cls, lines_ids):
- duplicates = {id for id in lines_ids if lines_ids.count(id) > 1}
+ duplicates = get_duplicated_values(lines_ids)
if duplicates:
raise ValidationError(
{
"orderLineId": ValidationError(
- "Duplicated warehouse ID.", code=OrderErrorCode.UNIQUE
+ "Duplicated order line ID.",
+ code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
)
}
)
@@ -186,7 +184,7 @@ class OrderFulfill(BaseMutation):
lines_ids = [line["order_line_id"] for line in lines]
cls.check_lines_for_duplicates(lines_ids)
order_lines = cls.get_nodes_or_error(
- lines_ids, field="liens", only_type=OrderLine
+ lines_ids, field="lines", only_type=OrderLine
)
cls.clean_lines(order_lines, quantities_for_lines)
@@ -204,7 +202,10 @@ class OrderFulfill(BaseMutation):
lines_for_warehouses = defaultdict(list)
for line, order_line in zip(lines, order_lines):
for stock in line["stocks"]:
- lines_for_warehouses[stock["warehouse"]].append(
+ warehouse_pk = from_global_id_strict_type(
+ stock["warehouse"], only_type=Warehouse, field="warehouse"
+ )
+ lines_for_warehouses[warehouse_pk].append(
{"order_line": order_line, "quantity": stock["quantity"]}
)
@@ -213,65 +214,6 @@ class OrderFulfill(BaseMutation):
data["lines_for_warehouses"] = lines_for_warehouses
return data
- @classmethod
- def create_fulfillment(cls, fulfillment, warehouse_pk, lines):
- fulfillment_lines = []
- for line in lines:
- quantity = line["quantity"]
- order_line = line["order_line"]
- if quantity > 0:
- try:
- fulfill_order_line(order_line, quantity, warehouse_pk)
- except InsufficientStock as exc:
- raise ValidationError(
- {
- "stocks": ValidationError(
- f"Insufficient product stock: {exc.item}",
- code=OrderErrorCode.INSUFFICIENT_STOCK,
- )
- }
- )
- if order_line.is_digital:
- order_line.variant.digital_content.urls.create(line=order_line)
- fulfillment_lines.append(
- models.FulfillmentLine(
- order_line=order_line,
- fulfillment=fulfillment,
- quantity=quantity,
- stock=order_line.variant.stocks.get(warehouse=warehouse_pk),
- )
- )
- return fulfillment_lines
-
- @classmethod
- @transaction.atomic()
- def create_fulfillments(cls, requester, order, cleaned_input):
- lines_for_warehouses = cleaned_input["lines_for_warehouses"]
- fulfillments = []
- fulfillment_lines = []
- for warehouse_global_id in lines_for_warehouses:
- warehouse_pk = from_global_id_strict_type(
- warehouse_global_id, only_type=Warehouse, field="warehouse",
- )
- fulfillment = models.Fulfillment.objects.create(order=order)
- fulfillments.append(fulfillment)
- fulfillment_lines.extend(
- cls.create_fulfillment(
- fulfillment,
- warehouse_pk,
- lines_for_warehouses[warehouse_global_id],
- )
- )
-
- models.FulfillmentLine.objects.bulk_create(fulfillment_lines)
- order_fulfilled(
- fulfillments,
- requester,
- fulfillment_lines,
- cleaned_input.get("notify_customer", True),
- )
- return fulfillments
-
@classmethod
def perform_mutation(cls, _root, info, order, **data):
order = cls.get_node_or_error(info, order, field="order", only_type=Order)
@@ -279,8 +221,23 @@ class OrderFulfill(BaseMutation):
cleaned_input = cls.clean_input(data)
- requester = get_user_or_service_account_from_context(info.context)
- fulfillments = cls.create_fulfillments(requester, order, cleaned_input)
+ requester = get_user_or_app_from_context(info.context)
+ lines_for_warehouses = cleaned_input["lines_for_warehouses"]
+ notify_customer = cleaned_input.get("notify_customer", True)
+
+ try:
+ fulfillments = create_fulfillments(
+ requester, order, dict(lines_for_warehouses), notify_customer
+ )
+ except InsufficientStock as exc:
+ raise ValidationError(
+ {
+ "stocks": ValidationError(
+ f"Insufficient product stock: {exc.item}",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
+ }
+ )
return OrderFulfill(fulfillments=fulfillments, order=order)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 4ffc2cac16..4e6c2c511d 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2673,6 +2673,7 @@ enum OrderErrorCode {
VOID_INACTIVE_PAYMENT
ZERO_QUANTITY
INSUFFICIENT_STOCK
+ DUPLICATED_INPUT_ITEM
}
type OrderEvent implements Node {
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index e4e7fbdaf6..623663b85c 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1,6 +1,6 @@
import logging
from decimal import Decimal
-from typing import TYPE_CHECKING, List
+from typing import TYPE_CHECKING, Dict, List
from django.db import transaction
@@ -251,3 +251,107 @@ def automatically_fulfill_digital_lines(order: "Order"):
order, fulfillment, user=order.user
)
update_order_status(order)
+
+
+def _create_fulfillment(
+ fulfillment: Fulfillment, warehouse_pk: str, lines: List[Dict]
+) -> List[FulfillmentLine]:
+ """Modify stocks and allocations. Return list of unsaved FulfillmentLines.
+
+ Args:
+ fulfillment (Fulfillment): Fulfillment to create lines
+ warehouse_pk (str): Warehouse to fulfill order.
+ lines (List[Dict]): List with information from which system
+ create FulfillmentLines. Example:
+ [
+ {
+ "order_line": (OrderLine),
+ "quantity": (int),
+ },
+ ...
+ ]
+
+ Return:
+ List[FulfillmentLine]: Unsaved fulfillmet lines created for this fulfillment
+ based on information form `lines`
+
+ Raise:
+ InsufficientStock: If system hasn't containt enough item in stock for any line.
+
+ """
+ fulfillment_lines = []
+ for line in lines:
+ quantity = line["quantity"]
+ order_line = line["order_line"]
+ if quantity > 0:
+ try:
+ fulfill_order_line(order_line, quantity, warehouse_pk)
+ except InsufficientStock as exc:
+ raise exc
+ if order_line.is_digital:
+ order_line.variant.digital_content.urls.create(line=order_line)
+ fulfillment_lines.append(
+ FulfillmentLine(
+ order_line=order_line,
+ fulfillment=fulfillment,
+ quantity=quantity,
+ stock=order_line.variant.stocks.get(warehouse=warehouse_pk),
+ )
+ )
+ return fulfillment_lines
+
+
+def create_fulfillments(
+ requester: "User",
+ order: "Order",
+ fulfillment_lines_for_warehouses: Dict,
+ notify_customer: bool = True,
+):
+ """Fulfill order.
+
+ Function create fulfillments with lines.
+ Next updates Order based on created fulfillments.
+
+ Args:
+ requester (User): Requester who trigger this action.
+ order (Order): Order to fulfill
+ fulfillment_lines_for_warehouses (Dict): Dict with information from which
+ system create fulfillments. Example:
+ {
+ (Warehouse.pk): [
+ {
+ "order_line": (OrderLine),
+ "quantity": (int),
+ },
+ ...
+ ]
+ }
+ notify_customer (bool): If `True` system send email about
+ fulfillments to customer.
+
+ Raise:
+ InsufficientStock: If system hasn't containt enough item in stock for any line.
+
+ """
+ fulfillments = []
+ fulfillment_lines: List[FulfillmentLine] = []
+ for warehouse_pk in fulfillment_lines_for_warehouses:
+ fulfillment = Fulfillment.objects.create(order=order)
+ fulfillments.append(fulfillment)
+ try:
+ fulfillment_lines.extend(
+ _create_fulfillment(
+ fulfillment,
+ warehouse_pk,
+ fulfillment_lines_for_warehouses[warehouse_pk],
+ )
+ )
+ except InsufficientStock as exc:
+ raise exc
+
+ FulfillmentLine.objects.bulk_create(fulfillment_lines)
+ order_fulfilled(
+ fulfillments, requester, fulfillment_lines, notify_customer,
+ )
+ return fulfillments
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 6d94c009da..e16f113cc9 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -23,3 +23,4 @@ class OrderErrorCode(Enum):
VOID_INACTIVE_PAYMENT = "void_inactive_payment"
ZERO_QUANTITY = "zero_quantity"
INSUFFICIENT_STOCK = "insufficient_stock"
+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"
diff --git a/tests/api/test_fulfillment.py b/tests/api/test_fulfillment.py
index 8b20de4940..f17e703676 100644
--- a/tests/api/test_fulfillment.py
+++ b/tests/api/test_fulfillment.py
@@ -3,11 +3,12 @@ from unittest.mock import patch
import graphene
import pytest
+from saleor.core.exceptions import InsufficientStock
from saleor.core.permissions import OrderPermissions
from saleor.order.error_codes import OrderErrorCode
from saleor.order.events import OrderEvents
-from saleor.order.models import FulfillmentLine, FulfillmentStatus, OrderStatus
-from saleor.warehouse.models import Allocation, Stock
+from saleor.order.models import FulfillmentStatus
+from saleor.warehouse.models import Allocation
from tests.api.utils import assert_no_permission, get_graphql_content
ORDER_FULFILL_QUERY = """
@@ -23,21 +24,14 @@ mutation fulfillOrder(
code
message
}
- fulfillments {
- fulfillmentOrder
- status
- lines {
- id
- }
- }
}
}
"""
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill(
- mock_email_fulfillment,
+ mock_create_fulfillments,
staff_api_client,
staff_user,
order_with_lines,
@@ -47,9 +41,8 @@ def test_order_fulfill(
order = order_with_lines
query = ORDER_FULFILL_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
- order_line = order.lines.first()
+ order_line, order_line2 = order.lines.all()
order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
- order_line2 = order.lines.last()
order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
variables = {
@@ -72,20 +65,23 @@ def test_order_fulfill(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
- data = content["data"]["orderFulfill"]["fulfillments"][0]
- assert data["fulfillmentOrder"] == 1
- assert data["status"] == FulfillmentStatus.FULFILLED.upper()
- assert len(data["lines"]) == 2
-
- order.refresh_from_db()
- assert order.status == OrderStatus.FULFILLED
+ data = content["data"]["orderFulfill"]
+ assert not data["orderErrors"]
- mock_email_fulfillment.assert_called_once_with(
- order, order.fulfillments.get(), staff_user
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user, order, fulfillment_lines_for_warehouses, True
)
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill_many_warehouses(
+ mock_create_fulfillments,
staff_api_client,
staff_user,
order_with_lines,
@@ -98,17 +94,6 @@ def test_order_fulfill_many_warehouses(
warehouse1, warehouse2 = warehouses
order_line1, order_line2 = order.lines.all()
- stock_w1_l1 = Stock(
- warehouse=warehouse1, product_variant=order_line1.variant, quantity=3
- )
- stock_w1_l2 = Stock(
- warehouse=warehouse1, product_variant=order_line2.variant, quantity=1
- )
- stock_w2_l2 = Stock(
- warehouse=warehouse2, product_variant=order_line2.variant, quantity=1
- )
- Stock.objects.bulk_create([stock_w1_l1, stock_w1_l2, stock_w2_l2])
-
order_id = graphene.Node.to_global_id("Order", order.id)
order_line1_id = graphene.Node.to_global_id("OrderLine", order_line1.id)
order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)
@@ -118,7 +103,6 @@ def test_order_fulfill_many_warehouses(
variables = {
"order": order_id,
"input": {
- "notifyCustomer": False,
"lines": [
{
"orderLineId": order_line1_id,
@@ -140,34 +124,23 @@ def test_order_fulfill_many_warehouses(
content = get_graphql_content(response)
data = content["data"]["orderFulfill"]
assert not data["orderErrors"]
- order.refresh_from_db()
- fulfillment_lines = FulfillmentLine.objects.filter(
- fulfillment__order=order
- ).order_by("pk")
- assert fulfillment_lines[0].stock == stock_w1_l1
- assert fulfillment_lines[0].quantity == 3
- assert fulfillment_lines[1].stock == stock_w1_l2
- assert fulfillment_lines[1].quantity == 1
- assert fulfillment_lines[2].stock == stock_w2_l2
- assert fulfillment_lines[2].quantity == 1
-
- assert order.status == OrderStatus.FULFILLED
- order_line1, order_line2 = order.lines.all()
- assert order_line1.quantity_fulfilled == 3
- assert order_line2.quantity_fulfilled == 2
-
- assert (
- Allocation.objects.filter(
- order_line__order=order, quantity_allocated__gt=0
- ).count()
- == 0
+ fulfillment_lines_for_warehouses = {
+ str(warehouse1.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 1},
+ ],
+ str(warehouse2.pk): [{"order_line": order_line2, "quantity": 1}],
+ }
+
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user, order, fulfillment_lines_for_warehouses, True
)
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill_without_notification(
- mock_email_fulfillment,
+ mock_create_fulfillments,
staff_api_client,
staff_user,
order_with_lines,
@@ -196,17 +169,20 @@ def test_order_fulfill_without_notification(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
- data = content["data"]["orderFulfill"]["fulfillments"][0]
- assert data["fulfillmentOrder"] == 1
- assert data["status"] == FulfillmentStatus.FULFILLED.upper()
- assert len(data["lines"]) == 1
+ data = content["data"]["orderFulfill"]
+ assert not data["orderErrors"]
- mock_email_fulfillment.assert_not_called()
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [{"order_line": order_line, "quantity": 1}]
+ }
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user, order, fulfillment_lines_for_warehouses, False
+ )
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill_with_one_line_empty_quantity(
- mock_email_fulfillment,
+ mock_create_fulfillments,
staff_api_client,
staff_user,
order_with_lines,
@@ -216,11 +192,9 @@ def test_order_fulfill_with_one_line_empty_quantity(
order = order_with_lines
query = ORDER_FULFILL_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
- order_lines = order.lines.all()
- order_line_ids = [
- graphene.Node.to_global_id("OrderLine", order_line.id)
- for order_line in order_lines
- ]
+ 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)
assert not order.events.all()
variables = {
@@ -229,10 +203,13 @@ def test_order_fulfill_with_one_line_empty_quantity(
"lines": [
{
"orderLineId": order_line_id,
- "stocks": [{"quantity": 1, "warehouse": warehouse_id}],
- }
- for order_line_id in order_line_ids
- ]
+ "stocks": [{"quantity": 0, "warehouse": warehouse_id}],
+ },
+ {
+ "orderLineId": order_line2_id,
+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],
+ },
+ ],
},
}
variables["input"]["lines"][0]["stocks"][0]["quantity"] = 0
@@ -240,57 +217,17 @@ def test_order_fulfill_with_one_line_empty_quantity(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
- data = content["data"]["orderFulfill"]["fulfillments"][0]
- assert data["fulfillmentOrder"] == 1
- assert data["status"] == FulfillmentStatus.FULFILLED.upper()
- assert len(data["lines"]) == len(order_line_ids) - 1
-
- order.refresh_from_db()
- assert order.status == OrderStatus.PARTIALLY_FULFILLED
-
- mock_email_fulfillment.assert_called_once_with(
- order, order.fulfillments.get(), staff_user
- )
-
+ data = content["data"]["orderFulfill"]
+ assert not data["orderErrors"]
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
-def test_order_fulfill_without_allocations(
- mock_email_fulfillment,
- staff_api_client,
- staff_user,
- order_with_lines,
- permission_manage_orders,
- warehouse,
-):
- order = order_with_lines
- query = ORDER_FULFILL_QUERY
- order_id = graphene.Node.to_global_id("Order", order.id)
- order_line = order.lines.first()
- order_line.allocations.all().delete()
- 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": 1, "warehouse": warehouse_id}],
- }
- ]
- },
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line, "quantity": 0},
+ {"order_line": order_line2, "quantity": 2},
+ ]
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- data = content["data"]["orderFulfill"]["fulfillments"][0]
- assert data["fulfillmentOrder"] == 1
- assert data["status"] == FulfillmentStatus.FULFILLED.upper()
- assert len(data["lines"]) == 1
-
- mock_email_fulfillment.assert_called_once_with(
- order, order.fulfillments.get(), staff_user
+ mock_create_fulfillments.assert_called_once_with(
+ staff_user, order, fulfillment_lines_for_warehouses, True
)
@@ -301,9 +238,9 @@ def test_order_fulfill_without_allocations(
(100, OrderErrorCode.FULFILL_ORDER_LINE.name, "orderLineId"),
),
)
-@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
def test_order_fulfill_not_sufficient_quantity(
- mock_email_fulfillment,
+ mock_create_fulfillments,
staff_api_client,
staff_user,
order_with_lines,
@@ -338,10 +275,12 @@ def test_order_fulfill_not_sufficient_quantity(
assert data["orderErrors"][0]["field"] == error_field
assert data["orderErrors"][0]["code"] == error_code
- mock_email_fulfillment.assert_not_called()
+ mock_create_fulfillments.assert_not_called()
-def test_order_fulfill_warehouse_without_stock(
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
+def test_order_fulfill_warehouse_with_insufficient_stock_exception(
+ mock_create_fulfillments,
staff_api_client,
order_with_lines,
permission_manage_orders,
@@ -366,6 +305,9 @@ def test_order_fulfill_warehouse_without_stock(
]
},
}
+
+ mock_create_fulfillments.side_effect = InsufficientStock(order_line.variant)
+
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
@@ -376,8 +318,13 @@ def test_order_fulfill_warehouse_without_stock(
assert data["orderErrors"][0]["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
def test_order_fulfill_warehouse_duplicated_warehouse_id(
- staff_api_client, order_with_lines, permission_manage_orders, warehouse,
+ mock_create_fulfillments,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ warehouse,
):
order = order_with_lines
query = ORDER_FULFILL_QUERY
@@ -406,11 +353,17 @@ def test_order_fulfill_warehouse_duplicated_warehouse_id(
data = content["data"]["orderFulfill"]
assert data["orderErrors"]
assert data["orderErrors"][0]["field"] == "warehouse"
- assert data["orderErrors"][0]["code"] == OrderErrorCode.UNIQUE.name
+ assert data["orderErrors"][0]["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name
+ mock_create_fulfillments.assert_not_called()
+@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
def test_order_fulfill_warehouse_duplicated_order_line_id(
- staff_api_client, order_with_lines, permission_manage_orders, warehouse,
+ mock_create_fulfillments,
+ staff_api_client,
+ order_with_lines,
+ permission_manage_orders,
+ warehouse,
):
order = order_with_lines
query = ORDER_FULFILL_QUERY
@@ -440,43 +393,8 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(
data = content["data"]["orderFulfill"]
assert data["orderErrors"]
assert data["orderErrors"][0]["field"] == "orderLineId"
- assert data["orderErrors"][0]["code"] == OrderErrorCode.UNIQUE.name
-
-
-def test_order_fulfill_warehouse_without_out_of_stock(
- staff_api_client, order_with_lines, permission_manage_orders, warehouse,
-):
- order = order_with_lines
- query = ORDER_FULFILL_QUERY
- order_id = graphene.Node.to_global_id("Order", order.id)
- order_line = order.lines.first()
- order_line.allocations.all().delete()
- order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)
- stock = order_line.variant.stocks.get(warehouse=warehouse)
- stock.quantity = 2
- stock.save(update_fields=["quantity"])
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- variables = {
- "order": order_id,
- "input": {
- "lines": [
- {
- "orderLineId": order_line_id,
- "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
- }
- ]
- },
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- order.refresh_from_db()
- assert order.fulfillments.count() == 0
- content = get_graphql_content(response)
- data = content["data"]["orderFulfill"]
- assert data["orderErrors"]
- assert data["orderErrors"][0]["field"] == "stocks"
- assert data["orderErrors"][0]["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name
+ assert data["orderErrors"][0]["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name
+ mock_create_fulfillments.assert_not_called()
@patch("saleor.order.emails.send_fulfillment_update.delay")
diff --git a/tests/test_fulfullments_actions.py b/tests/test_fulfullments_actions.py
new file mode 100644
index 0000000000..6865e2867a
--- /dev/null
+++ b/tests/test_fulfullments_actions.py
@@ -0,0 +1,317 @@
+from unittest.mock import patch
+
+import pytest
+
+from saleor.core.exceptions import InsufficientStock
+from saleor.order.actions import create_fulfillments
+from saleor.order.models import FulfillmentLine, OrderStatus
+from saleor.warehouse.models import Allocation, Stock
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments(
+ 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},
+ ]
+ }
+
+ [fulfillment] = create_fulfillments(
+ staff_user, order, fulfillment_lines_for_warehouses, True
+ )
+
+ 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.FULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 0
+ )
+
+ mock_email_fulfillment.assert_called_once_with(
+ order, order.fulfillments.get(), staff_user
+ )
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_without_email(
+ 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},
+ ]
+ }
+
+ [fulfillment] = create_fulfillments(
+ staff_user, order, fulfillment_lines_for_warehouses, False
+ )
+
+ 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.FULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 0
+ )
+
+ mock_email_fulfillment.assert_not_called()
+
+
+def test_create_fulfillments_many_warehouses(
+ staff_user, order_with_lines, warehouses,
+):
+ order = order_with_lines
+ warehouse1, warehouse2 = warehouses
+ order_line1, order_line2 = order.lines.all()
+
+ stock_w1_l1 = Stock(
+ warehouse=warehouse1, product_variant=order_line1.variant, quantity=3
+ )
+ stock_w1_l2 = Stock(
+ warehouse=warehouse1, product_variant=order_line2.variant, quantity=1
+ )
+ stock_w2_l2 = Stock(
+ warehouse=warehouse2, product_variant=order_line2.variant, quantity=1
+ )
+ Stock.objects.bulk_create([stock_w1_l1, stock_w1_l2, stock_w2_l2])
+ fulfillment_lines_for_warehouses = {
+ str(warehouse1.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 1},
+ ],
+ str(warehouse2.pk): [{"order_line": order_line2, "quantity": 1}],
+ }
+
+ [fulfillment1, fulfillment2] = create_fulfillments(
+ staff_user, order, fulfillment_lines_for_warehouses, False
+ )
+
+ order.refresh_from_db()
+ fulfillment_lines = FulfillmentLine.objects.filter(
+ fulfillment__order=order
+ ).order_by("pk")
+ assert fulfillment_lines[0].stock == stock_w1_l1
+ assert fulfillment_lines[0].quantity == 3
+ assert fulfillment_lines[1].stock == stock_w1_l2
+ assert fulfillment_lines[1].quantity == 1
+ assert fulfillment_lines[2].stock == stock_w2_l2
+ assert fulfillment_lines[2].quantity == 1
+
+ assert order.status == OrderStatus.FULFILLED
+ assert order.fulfillments.get(fulfillment_order=1) == fulfillment1
+ assert order.fulfillments.get(fulfillment_order=2) == fulfillment2
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 0
+ )
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_with_one_line_empty_quantity(
+ 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": 0},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+
+ [fulfillment] = create_fulfillments(
+ staff_user, order, fulfillment_lines_for_warehouses, True
+ )
+
+ order.refresh_from_db()
+ fulfillment_lines = FulfillmentLine.objects.filter(
+ fulfillment__order=order
+ ).order_by("pk")
+ assert fulfillment_lines[0].stock == order_line2.variant.stocks.get()
+ assert fulfillment_lines[0].quantity == 2
+
+ assert order.status == OrderStatus.PARTIALLY_FULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 0
+ assert order_line2.quantity_fulfilled == 2
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 1
+ )
+
+ mock_email_fulfillment.assert_called_once_with(
+ order, order.fulfillments.get(), staff_user
+ )
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_without_allocations(
+ mock_email_fulfillment, staff_user, order_with_lines, warehouse,
+):
+ order = order_with_lines
+ order_line1, order_line2 = order.lines.all()
+ Allocation.objects.filter(order_line__order=order).delete()
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+
+ [fulfillment] = create_fulfillments(
+ staff_user, order, fulfillment_lines_for_warehouses, True
+ )
+
+ 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.FULFILLED
+ assert order.fulfillments.get() == fulfillment
+
+ order_line1, order_line2 = order.lines.all()
+ assert order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
+
+ assert (
+ Allocation.objects.filter(
+ order_line__order=order, quantity_allocated__gt=0
+ ).count()
+ == 0
+ )
+
+ mock_email_fulfillment.assert_called_once_with(
+ order, order.fulfillments.get(), staff_user
+ )
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_warehouse_with_out_of_stock(
+ mock_email_fulfillment, staff_user, order_with_lines, warehouse,
+):
+ order = order_with_lines
+ order_line1, order_line2 = order.lines.all()
+ order_line1.allocations.all().delete()
+ stock = order_line1.variant.stocks.get(warehouse=warehouse)
+ stock.quantity = 2
+ stock.save(update_fields=["quantity"])
+ fulfillment_lines_for_warehouses = {
+ str(warehouse.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+
+ with pytest.raises(InsufficientStock):
+ create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
+
+ order.refresh_from_db()
+ assert FulfillmentLine.objects.filter(fulfillment__order=order).count() == 0
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.fulfillments.all().count() == 0
+
+ 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()
+ == 1
+ )
+
+ mock_email_fulfillment.assert_not_called()
+
+
+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
+def test_create_fulfillments_warehouse_without_stock(
+ mock_email_fulfillment, staff_user, order_with_lines, warehouse_no_shipping_zone,
+):
+ order = order_with_lines
+ order_line1, order_line2 = order.lines.all()
+ fulfillment_lines_for_warehouses = {
+ str(warehouse_no_shipping_zone.pk): [
+ {"order_line": order_line1, "quantity": 3},
+ {"order_line": order_line2, "quantity": 2},
+ ]
+ }
+
+ with pytest.raises(InsufficientStock):
+ create_fulfillments(staff_user, order, fulfillment_lines_for_warehouses, True)
+
+ order.refresh_from_db()
+ assert FulfillmentLine.objects.filter(fulfillment__order=order).count() == 0
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.fulfillments.all().count() == 0
+
+ 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
+ )
+
+ mock_email_fulfillment.assert_not_called()