Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add order fulfill mutation
fowczrek97ad15983e26
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex b66e4bd537..c5c745d0c4 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -1,7 +1,11 @@+from collections import defaultdict+import graphenefrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.template.defaultfilters import pluralize+from ....core.exceptions import InsufficientStockfrom ....core.permissions import OrderPermissionsfrom ....order import modelsfrom ....order.actions import (@@ -14,8 +18,11 @@ from ....order.emails import send_fulfillment_updatefrom ....order.error_codes import OrderErrorCodefrom ...core.mutations import BaseMutationfrom ...core.types.common import OrderError+from ...core.utils import from_global_id_strict_typefrom ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutationfrom ...order.types import Fulfillment, Order+from ...utils import get_user_or_service_account_from_context+from ...warehouse.types import Warehousefrom ..types import OrderLine@@ -36,6 +43,37 @@ class FulfillmentCreateInput(graphene.InputObjectType):)+class OrderFulfillStockInput(graphene.InputObjectType):+ quantity = graphene.Int(+ description="The number of line item to be fulfilled from given warehouse."+ )+ warehouse = graphene.ID(+ description="ID of the warehouse from which item be fulfilled."+ )+++class OrderFulfillLineInput(graphene.InputObjectType):+ order_line_id = graphene.ID(+ description="The ID of the order line.", name="orderLineId"+ )+ stocks = graphene.List(+ graphene.NonNull(OrderFulfillStockInput),+ required=True,+ description="Stocks from item line be fulfilled.",+ )+++class OrderFulfillInput(graphene.InputObjectType):+ lines = graphene.List(+ graphene.NonNull(OrderFulfillLineInput),+ required=True,+ description="Item line to be fulfilled.",+ )+ notify_customer = graphene.Boolean(+ description="If true, send an email notification to the customer."+ )++class FulfillmentUpdateTrackingInput(graphene.InputObjectType):tracking_number = graphene.String(description="Fulfillment tracking number.")notify_customer = graphene.Boolean(@@ -80,6 +118,190 @@ class FulfillmentUpdatePrivateMeta(UpdateMetaBaseMutation):public = False+class OrderFulfill(BaseMutation):+ fulfillments = graphene.List(Fulfillment, description="A created fulfillments.")+ order = graphene.Field(Order, description="Fulfilled order.")++ class Arguments:+ order = graphene.ID(+ description="ID of the order to be fulfilled.", name="order"+ )+ input = OrderFulfillInput(+ required=True, description="Fields required to create an fulfillment."+ )++ class Meta:+ description = "Creates a new fulfillments for an order."+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def clean_lines(cls, order_lines, quantities):+ for order_line, line_quantities in zip(order_lines, quantities):+ line_quantity_unfulfilled = order_line.quantity_unfulfilled++ if sum(line_quantities) > line_quantity_unfulfilled:+ msg = (+ "Only %(quantity)d item%(item_pluralize)s remaining "+ "to fulfill: %(order_line)s."+ ) % {+ "quantity": line_quantity_unfulfilled,+ "item_pluralize": pluralize(line_quantity_unfulfilled),+ "order_line": order_line,+ }+ raise ValidationError(+ {+ "order_line_id": ValidationError(+ msg, code=OrderErrorCode.FULFILL_ORDER_LINE+ )+ }+ )++ @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+ }+ if duplicates:+ raise ValidationError(+ {+ "warehouse": ValidationError(+ "Duplicated warehouse ID.", code=OrderErrorCode.UNIQUE+ )+ }+ )++ @classmethod+ def check_lines_for_duplicates(cls, lines_ids):+ duplicates = {id for id in lines_ids if lines_ids.count(id) > 1}+ if duplicates:+ raise ValidationError(+ {+ "orderLineId": ValidationError(+ "Duplicated warehouse ID.", code=OrderErrorCode.UNIQUE+ )+ }+ )++ @classmethod+ def clean_input(cls, data):+ lines = data["lines"]++ warehouse_ids_for_lines = [+ [stock["warehouse"] for stock in line["stocks"]] for line in lines+ ]+ cls.check_warehouses_for_duplicates(warehouse_ids_for_lines)++ quantities_for_lines = [+ [stock["quantity"] for stock in line["stocks"]] for line in lines+ ]++ 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+ )++ cls.clean_lines(order_lines, quantities_for_lines)++ if sum(sum(quantities_for_lines, [])) <= 0:+ raise ValidationError(+ {+ "lines": ValidationError(+ "Total quantity must be larger than 0.",+ code=OrderErrorCode.ZERO_QUANTITY,+ )+ }+ )++ 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(+ {"order_line": order_line, "quantity": stock["quantity"]}+ )++ data["order_lines"] = order_lines+ data["quantities"] = quantities_for_lines+ 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)+ data = data.get("input")++ cleaned_input = cls.clean_input(data)++ requester = get_user_or_service_account_from_context(info.context)+ fulfillments = cls.create_fulfillments(requester, order, cleaned_input)++ return OrderFulfill(fulfillments=fulfillments, order=order)++class FulfillmentCreate(BaseMutation):fulfillment = graphene.Field(Fulfillment, description="A created fulfillment.")order = graphene.Field(Order, description="Fulfilled order.")diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 4355011b25..b03864ba18 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -26,6 +26,7 @@ from .mutations.fulfillments import (FulfillmentUpdateMeta,FulfillmentUpdatePrivateMeta,FulfillmentUpdateTracking,+ OrderFulfill,)from .mutations.orders import (OrderAddNote,@@ -172,6 +173,7 @@ class OrderMutations(graphene.ObjectType):"after 2020-07-31."))+ order_fulfill = OrderFulfill.Field()order_fulfillment_cancel = FulfillmentCancel.Field()order_fulfillment_create = FulfillmentCreate.Field()order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9b08a89237..c0d323da3b 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2402,6 +2402,7 @@ type Mutation {orderCapture(amount: Decimal!, id: ID!): OrderCaptureorderClearPrivateMeta(id: ID!, input: MetaPath!): OrderClearPrivateMeta @deprecated(reason: "Use the `deletePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")orderClearMeta(input: MetaPath!, token: UUID!): OrderClearMeta @deprecated(reason: "Use the `deleteMetadata` mutation instead. This field will be removed after 2020-07-31.")+ orderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfillorderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancelorderFulfillmentCreate(input: FulfillmentCreateInput!, order: ID): FulfillmentCreateorderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking@@ -2769,6 +2770,28 @@ input OrderFilterInput {search: String}+type OrderFulfill {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ fulfillments: [Fulfillment]+ order: Order+ orderErrors: [OrderError!]!+}++input OrderFulfillInput {+ lines: [OrderFulfillLineInput!]!+ notifyCustomer: Boolean+}++input OrderFulfillLineInput {+ orderLineId: ID+ stocks: [OrderFulfillStockInput!]!+}++input OrderFulfillStockInput {+ quantity: Int+ warehouse: ID+}+type OrderLine implements Node {id: ID!productName: String!diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 552a0ffd74..e4e7fbdaf6 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -5,8 +5,9 @@ from typing import TYPE_CHECKING, Listfrom django.db import transactionfrom ..core import analytics-from ..plugins.manager import get_plugins_manager+from ..core.exceptions import InsufficientStockfrom ..payment import ChargeStatus, CustomPaymentChoices, PaymentError+from ..plugins.manager import get_plugins_managerfrom ..warehouse.management import decrease_stockfrom . import FulfillmentStatus, OrderStatus, emails, events, utilsfrom .emails import send_fulfillment_confirmation_to_customer, send_payment_confirmation@@ -103,25 +104,28 @@ def order_voided(order: "Order", user: "User", payment: "Payment"):def order_fulfilled(- fulfillment: "Fulfillment",+ fulfillments: List["Fulfillment"],user: "User",fulfillment_lines: List["FulfillmentLine"],notify_customer=True,):- order = fulfillment.order+ order = fulfillments[0].orderupdate_order_status(order)events.fulfillment_fulfilled_items_event(order=order, user=user, fulfillment_lines=fulfillment_lines)manager = get_plugins_manager()manager.order_updated(order)- manager.fulfillment_created(fulfillment)++ for fulfillment in fulfillments:+ manager.fulfillment_created(fulfillment)if order.status == OrderStatus.FULFILLED:manager.order_fulfilled(order)if notify_customer:- send_fulfillment_confirmation_to_customer(order, fulfillment, user)+ for fulfillment in fulfillments:+ send_fulfillment_confirmation_to_customer(order, fulfillment, user)def order_shipping_updated(order: "Order"):@@ -205,10 +209,13 @@ def clean_mark_order_as_paid(order: "Order"):raise PaymentError("Orders with payments can not be manually marked as paid.",)-def fulfill_order_line(order_line, quantity):+def fulfill_order_line(order_line, quantity, warehouse_pk):"""Fulfill order line with given quantity."""if order_line.variant and order_line.variant.track_inventory:- decrease_stock(order_line, quantity)+ try:+ decrease_stock(order_line, quantity, warehouse_pk)+ except InsufficientStock as exc:+ raise excorder_line.quantity_fulfilled += quantityorder_line.save(update_fields=["quantity_fulfilled"])@@ -236,7 +243,10 @@ def automatically_fulfill_digital_lines(order: "Order"):FulfillmentLine.objects.create(fulfillment=fulfillment, order_line=line, quantity=quantity)- fulfill_order_line(order_line=line, quantity=quantity)+ warehouse_pk = line.allocations.first().stock.warehouse.pk # type: ignore+ fulfill_order_line(+ order_line=line, quantity=quantity, warehouse_pk=warehouse_pk+ )emails.send_fulfillment_confirmation_to_customer(order, fulfillment, user=order.user)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 8d30523a90..e89c7e85b9 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -2,6 +2,7 @@ from typing import TYPE_CHECKINGfrom django.db import transactionfrom django.db.models import F, Sum+from django.db.models.functions import Coalescefrom ..core.exceptions import AllocationError, InsufficientStockfrom .models import Allocation, Stock, Warehouse@@ -139,41 +140,35 @@ def increase_stock(@transaction.atomic-def decrease_stock(order_line: "OrderLine", quantity: int):- """Decrease stock quantity for given `order_line`.-- Function lock for update stocks and allocations related to given `order_line`.- Iterate over allocations sorted by `stock.pk` and deallocate and decrease stock- quantity for as many items as needed of available in stock for order line, until- deallocated all required quantity for the order line. If there is less quantity in- stocks then raise an exception.+def decrease_stock(order_line: "OrderLine", quantity: int, warehouse_pk: str):+ """Decrease stock quantity for given `order_line` in given warehouse.++ Function deallocate as many quantities as requested if order_line has less quantity+ from requested function deallocate whole quantity. Next function try to find the+ stock in a given warehouse, if stock not exists or have not enough stock,+ the function raise InsufficientStock exception. When the stock has enough quantity+ function decrease it by given value."""- allocations = (- order_line.allocations.select_related("stock")- .select_for_update(of=("self", "stock",))- .order_by("stock__pk")- )- quantity_decreased = 0- updated_stocks = []-- for allocation in allocations:- quantity_to_decreased = min(- (quantity - quantity_decreased), allocation.quantity_allocated+ try:+ deallocate_stock(order_line, quantity)+ except AllocationError:+ order_line.allocations.update(quantity_allocated=0)++ try:+ stock = (+ order_line.variant.stocks.select_for_update() # type: ignore+ .prefetch_related("allocations")+ .get(warehouse__pk=warehouse_pk))- if quantity_to_decreased > 0:+ except Stock.DoesNotExist:+ raise InsufficientStock(order_line.variant)- allocation.quantity_allocated = (- F("quantity_allocated") - quantity_to_decreased- )+ quantity_allocated = stock.allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]- stock = allocation.stock- stock.quantity = F("quantity") - quantity_to_decreased- updated_stocks.append(stock)+ if stock.quantity - quantity_allocated < quantity:+ raise InsufficientStock(order_line.variant)- quantity_decreased += quantity_to_decreased- if quantity_decreased == quantity:- Allocation.objects.bulk_update(allocations, ["quantity_allocated"])- Stock.objects.bulk_update(updated_stocks, ["quantity"])- break- if not quantity_decreased == quantity:- raise AllocationError(order_line, quantity)+ stock.quantity = F("quantity") - quantity+ stock.save(update_fields=["quantity"])diff --git a/tests/api/test_fulfillment.py b/tests/api/test_fulfillment.pyindex 38093ac870..381806eb3d 100644--- a/tests/api/test_fulfillment.py+++ b/tests/api/test_fulfillment.py@@ -4,30 +4,28 @@ import grapheneimport pytestfrom saleor.core.permissions import OrderPermissions+from saleor.order.error_codes import OrderErrorCodefrom saleor.order.events import OrderEvents-from saleor.order.models import FulfillmentStatus-from saleor.warehouse.models import Allocation+from saleor.order.models import FulfillmentLine, FulfillmentStatus, OrderStatus+from saleor.warehouse.models import Allocation, Stockfrom tests.api.utils import assert_no_permission, get_graphql_content-CREATE_FULFILLMENT_QUERY = """- mutation fulfillOrder(- $order: ID, $lines: [FulfillmentLineInput]!, $tracking: String,- $notify: Boolean+ORDER_FULFILL_QUERY = """+mutation fulfillOrder(+ $order: ID, $input: OrderFulfillInput!+) {+ orderFulfill(+ order: $order,+ input: $input) {- orderFulfillmentCreate(- order: $order,- input: {- lines: $lines, trackingNumber: $tracking,- notifyCustomer: $notify}- ) {- errors {- field- message- }- fulfillment {- fulfillmentOrder- status- trackingNumber+ orderErrors {+ field+ code+ message+ }+ fulfillments {+ fulfillmentOrder+ statuslines {id}@@ -38,129 +36,447 @@ CREATE_FULFILLMENT_QUERY = """@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)-def test_create_fulfillment(+def test_order_fulfill(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_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 = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ 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"]) == 2++ order.refresh_from_db()+ assert order.status == OrderStatus.FULFILLED++ mock_email_fulfillment.assert_called_once_with(+ order, order.fulfillments.get(), staff_user+ )+++def test_order_fulfill_many_warehouses(+ staff_api_client,staff_user,+ order_with_lines,permission_manage_orders,+ warehouses,):order = order_with_lines- query = CREATE_FULFILLMENT_QUERY+ query = ORDER_FULFILL_QUERY++ 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)+ warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouse1.pk)+ warehouse2_id = graphene.Node.to_global_id("Warehouse", warehouse2.pk)++ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": False,+ "lines": [+ {+ "orderLineId": order_line1_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse1_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [+ {"quantity": 1, "warehouse": warehouse1_id},+ {"quantity": 1, "warehouse": warehouse2_id},+ ],+ },+ ],+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert not data["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+ )+++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_order_fulfill_without_notification(+ mock_email_fulfillment,+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_manage_orders,+ warehouse,+):+ order = order_with_lines+ query = ORDER_FULFILL_QUERYorder_id = graphene.Node.to_global_id("Order", order.id)order_line = order.lines.first()order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)- tracking = "Flames tracking"+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)variables = {"order": order_id,- "lines": [{"orderLineId": order_line_id, "quantity": 1}],- "tracking": tracking,- "notify": True,+ "input": {+ "notifyCustomer": False,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ }+ ],+ },}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content["data"]["orderFulfillmentCreate"]["fulfillment"]+ data = content["data"]["orderFulfill"]["fulfillments"][0]assert data["fulfillmentOrder"] == 1assert data["status"] == FulfillmentStatus.FULFILLED.upper()- assert data["trackingNumber"] == trackingassert len(data["lines"]) == 1- assert mock_email_fulfillment.call_count == 1+ mock_email_fulfillment.assert_not_called()@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)-def test_create_fulfillment_with_empty_quantity(- mock_send_fulfillment_confirmation,+def test_order_fulfill_with_one_line_empty_quantity(+ mock_email_fulfillment,staff_api_client,- order_with_lines,staff_user,+ order_with_lines,permission_manage_orders,+ warehouse,):order = order_with_lines- query = CREATE_FULFILLMENT_QUERY+ query = ORDER_FULFILL_QUERYorder_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]- tracking = "Flames tracking"+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)assert not order.events.all()variables = {"order": order_id,- "lines": [- {"orderLineId": order_line_id, "quantity": 1}- for order_line_id in order_line_ids- ],- "tracking": tracking,- "notify": True,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ }+ for order_line_id in order_line_ids+ ]+ },}- variables["lines"][0]["quantity"] = 0+ variables["input"]["lines"][0]["stocks"][0]["quantity"] = 0response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content["data"]["orderFulfillmentCreate"]["fulfillment"]+ data = content["data"]["orderFulfill"]["fulfillments"][0]assert data["fulfillmentOrder"] == 1assert data["status"] == FulfillmentStatus.FULFILLED.upper()+ assert len(data["lines"]) == len(order_line_ids) - 1++ order.refresh_from_db()+ assert order.status == OrderStatus.PARTIALLY_FULFILLED- assert mock_send_fulfillment_confirmation.called+ 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_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}],+ }+ ]+ },+ }+ 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+ )@pytest.mark.parametrize(- "quantity, error_message, error_field",+ "quantity, error_code, error_field",(- (0, "Total quantity must be larger than 0.", "lines"),- (100, "Only 3 items remaining to fulfill:", "orderLineId"),+ (0, OrderErrorCode.ZERO_QUANTITY.name, "lines"),+ (100, OrderErrorCode.FULFILL_ORDER_LINE.name, "orderLineId"),),)-def test_create_fulfillment_not_sufficient_quantity(+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_order_fulfill_not_sufficient_quantity(+ mock_email_fulfillment,staff_api_client,- order_with_lines,staff_user,+ order_with_lines,quantity,- error_message,+ error_code,error_field,permission_manage_orders,+ warehouse,):- query = CREATE_FULFILLMENT_QUERY+ 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": quantity, "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["orderErrors"]+ assert data["orderErrors"][0]["field"] == error_field+ assert data["orderErrors"][0]["code"] == error_code++ mock_email_fulfillment.assert_not_called()+++def test_order_fulfill_warehouse_without_stock(+ staff_api_client,+ order_with_lines,+ permission_manage_orders,+ warehouse_no_shipping_zone,+):+ 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_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id(+ "Warehouse", warehouse_no_shipping_zone.pk+ )+ variables = {+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ }+ ]+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert data["orderErrors"]+ assert data["orderErrors"][0]["field"] == "stocks"+ assert data["orderErrors"][0]["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name+++def test_order_fulfill_warehouse_duplicated_warehouse_id(+ 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_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)variables = {- "order": graphene.Node.to_global_id("Order", order_with_lines.id),- "lines": [{"orderLineId": order_line_id, "quantity": quantity}],+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [+ {"quantity": 1, "warehouse": warehouse_id},+ {"quantity": 2, "warehouse": warehouse_id},+ ],+ }+ ]+ },}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content["data"]["orderFulfillmentCreate"]- assert data["errors"]- assert data["errors"][0]["field"] == error_field- assert error_message in data["errors"][0]["message"]+ data = content["data"]["orderFulfill"]+ assert data["orderErrors"]+ assert data["orderErrors"][0]["field"] == "warehouse"+ assert data["orderErrors"][0]["code"] == OrderErrorCode.UNIQUE.name-def test_create_fulfillment_with_invalid_input(- staff_api_client, order_with_lines, permission_manage_orders+def test_order_fulfill_warehouse_duplicated_order_line_id(+ staff_api_client, order_with_lines, permission_manage_orders, warehouse,):- query = CREATE_FULFILLMENT_QUERY+ 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_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)variables = {- "order": graphene.Node.to_global_id("Order", order_with_lines.id),- "lines": [{"orderLineId": "fake-orderline-id", "quantity": 1}],+ "order": order_id,+ "input": {+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ ]+ },}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)- data = content["data"]["orderFulfillmentCreate"]- assert data["errors"]- assert data["errors"][0]["field"] == "lines"- assert data["errors"][0]["message"] == (- "Could not resolve to a node with the global id list"- " of '['fake-orderline-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@patch("saleor.order.emails.send_fulfillment_update.delay")@@ -315,17 +631,18 @@ def test_create_digital_fulfillment(digital_content,staff_api_client,order_with_lines,- staff_user,+ warehouse,permission_manage_orders,):order = order_with_lines- query = CREATE_FULFILLMENT_QUERY+ query = ORDER_FULFILL_QUERYorder_id = graphene.Node.to_global_id("Order", order.id)order_line = order.lines.first()order_line.variant = digital_content.product_variantorder_line.save()+ order_line.allocations.all().delete()- stock = digital_content.product_variant.stocks.first()+ stock = digital_content.product_variant.stocks.get(warehouse=warehouse)Allocation.objects.create(order_line=order_line, stock=stock, quantity_allocated=order_line.quantity)@@ -333,16 +650,23 @@ def test_create_digital_fulfillment(second_line = order.lines.last()first_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)- tracking = "Flames tracking"variables = {"order": order_id,- "lines": [- {"orderLineId": first_line_id, "quantity": 1},- {"orderLineId": second_line_id, "quantity": 1},- ],- "tracking": tracking,- "notify": True,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": first_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": second_line_id,+ "stocks": [{"quantity": 1, "warehouse": warehouse_id}],+ },+ ],+ },}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_orders]diff --git a/tests/conftest.py b/tests/conftest.pyindex 2c532767a6..8249203b3a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1211,9 +1211,11 @@ def fulfilled_order(order_with_lines):line_1 = order.lines.first()line_2 = order.lines.last()fulfillment.lines.create(order_line=line_1, quantity=line_1.quantity)- fulfill_order_line(line_1, line_1.quantity)+ warehouse_1_pk = line_1.allocations.get().stock.warehouse.pk+ fulfill_order_line(line_1, line_1.quantity, warehouse_1_pk)fulfillment.lines.create(order_line=line_2, quantity=line_2.quantity)- fulfill_order_line(line_2, line_2.quantity)+ warehouse_2_pk = line_2.allocations.get().stock.warehouse.pk+ fulfill_order_line(line_2, line_2.quantity, warehouse_2_pk)order.status = OrderStatus.FULFILLEDorder.save(update_fields=["status"])return orderdiff --git a/tests/test_order_actions.py b/tests/test_order_actions.pyindex 59a1e1dba0..562f891848 100644--- a/tests/test_order_actions.py+++ b/tests/test_order_actions.py@@ -174,7 +174,7 @@ def test_fulfill_order_line(order_with_lines):stock = Stock.objects.get(product_variant=variant)stock_quantity_after = stock.quantity - line.quantity- fulfill_order_line(line, line.quantity)+ fulfill_order_line(line, line.quantity, stock.warehouse.pk)stock.refresh_from_db()assert stock.quantity == stock_quantity_after@@ -187,7 +187,7 @@ def test_fulfill_order_line_with_variant_deleted(order_with_lines):line.refresh_from_db()- fulfill_order_line(line, line.quantity)+ fulfill_order_line(line, line.quantity, "warehouse_pk")def test_fulfill_order_line_without_inventory_tracking(order_with_lines):@@ -202,7 +202,7 @@ def test_fulfill_order_line_without_inventory_tracking(order_with_lines):# stock should not changestock_quantity_after = stock.quantity- fulfill_order_line(line, line.quantity)+ fulfill_order_line(line, line.quantity, stock.warehouse.pk)stock.refresh_from_db()assert stock.quantity == stock_quantity_afterdiff --git a/tests/test_stock_management.py b/tests/test_stock_management.pyindex 54fa286845..cac12bab6e 100644--- a/tests/test_stock_management.py+++ b/tests/test_stock_management.py@@ -1,4 +1,6 @@import pytest+from django.db.models import Sum+from django.db.models.functions import Coalescefrom saleor.core.exceptions import InsufficientStockfrom saleor.warehouse.management import (@@ -177,8 +179,9 @@ def test_decrease_stock(allocation):stock.save(update_fields=["quantity"])allocation.quantity_allocated = 80allocation.save(update_fields=["quantity_allocated"])+ warehouse_pk = allocation.stock.warehouse.pk- decrease_stock(allocation.order_line, 50)+ decrease_stock(allocation.order_line, 50, warehouse_pk)stock.refresh_from_db()assert stock.quantity == 50@@ -192,8 +195,9 @@ def test_decrease_stock_partially(allocation):stock.save(update_fields=["quantity"])allocation.quantity_allocated = 80allocation.save(update_fields=["quantity_allocated"])+ warehouse_pk = allocation.stock.warehouse.pk- decrease_stock(allocation.order_line, 80)+ decrease_stock(allocation.order_line, 80, warehouse_pk)stock.refresh_from_db()assert stock.quantity == 20@@ -203,25 +207,44 @@ def test_decrease_stock_partially(allocation):def test_decrease_stock_many_allocations(order_line_with_allocation_in_many_stocks,):order_line = order_line_with_allocation_in_many_stocks+ allocations = order_line.allocations.all()+ warehouse_pk = allocations[1].stock.warehouse.pk- decrease_stock(order_line, 3)+ decrease_stock(order_line, 3, warehouse_pk)- allocations = order_line.allocations.all()assert allocations[0].quantity_allocated == 0- assert allocations[0].stock.quantity == 2assert allocations[1].quantity_allocated == 0- assert allocations[1].stock.quantity == 2+ assert allocations[0].stock.quantity == 4+ assert allocations[1].stock.quantity == 0def test_decrease_stock_many_allocations_partially(order_line_with_allocation_in_many_stocks,):order_line = order_line_with_allocation_in_many_stocks+ allocations = order_line.allocations.all()+ warehouse_pk = allocations[0].stock.warehouse.pk- decrease_stock(order_line, 2)+ decrease_stock(order_line, 2, warehouse_pk)- allocations = order_line.allocations.all()assert allocations[0].quantity_allocated == 0- assert allocations[0].stock.quantity == 2assert allocations[1].quantity_allocated == 1+ assert allocations[0].stock.quantity == 2+ assert allocations[1].stock.quantity == 3+++def test_decrease_stock_more_then_allocated(order_line_with_allocation_in_many_stocks,):+ order_line = order_line_with_allocation_in_many_stocks+ allocations = order_line.allocations.all()+ warehouse_pk = allocations[0].stock.warehouse.pk+ quantity_allocated = allocations.aggregate(+ quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)+ )["quantity_allocated"]+ assert quantity_allocated < 4++ decrease_stock(order_line, 4, warehouse_pk)++ assert allocations[0].quantity_allocated == 0+ assert allocations[1].quantity_allocated == 0+ assert allocations[0].stock.quantity == 0assert allocations[1].stock.quantity == 3