Skip to content

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

Refactor fulfillments quantity fulfilled (#8062)

Tomasz Szymański46c325ab0ec8
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index 3f0f72da00..279ebe0a17 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -2,7 +2,6 @@ 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
@@ -104,17 +103,3 @@ 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 6d2f871960..6049d81322 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -93,19 +93,8 @@ class OrderFulfill(BaseMutation):
@classmethod
def clean_lines(cls, order_lines, quantities):
for order_line, line_quantities in zip(order_lines, quantities):
- quantity_awaiting = sum(
- [
- f_line.quantity
- if f_line.fulfillment.status
- == FulfillmentStatus.WAITING_FOR_APPROVAL
- else 0
- for f_line in order_line.fulfillment_lines.all()
- ]
- )
- line_quantity_unfulfilled = (
- order_line.quantity_unfulfilled - quantity_awaiting
- )
+ line_quantity_unfulfilled = order_line.quantity_unfulfilled
if sum(line_quantities) > line_quantity_unfulfilled:
msg = (
@@ -201,12 +190,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="lines",
- only_type=OrderLine,
- qs=order_models.OrderLine.objects.prefetch_related(
- "fulfillment_lines__fulfillment"
- ),
+ lines_ids, field="lines", only_type=OrderLine
)
cls.clean_lines(order_lines, quantities_for_lines)
@@ -674,100 +658,18 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
)
return cleaned_input
- @classmethod
- def remove_waiting_fulfillments(cls, lines_info):
- """Delete fulfillment lines which fulfillments are `WAITING_FOR_APPROVAL`.
-
- Delete fulfillments themselves if metioned lines were only lines inside.
- """
- if not lines_info:
- return {}, []
-
- lines_to_remove = []
- lines_to_update = []
- remaining_fulfillment_lines = []
- order_lines_map = defaultdict(lambda: 0)
-
- for line_data in lines_info:
- if (
- line_data.line.fulfillment.status
- == FulfillmentStatus.WAITING_FOR_APPROVAL
- ):
- if line_data.quantity < line_data.line.quantity:
- _line = line_data.line
- _line.quantity = _line.quantity - line_data.quantity
- lines_to_update.append(_line)
- else:
- lines_to_remove.append(line_data.line.id)
- order_lines_map[line_data.line.order_line] += line_data.quantity
- else:
- remaining_fulfillment_lines.append(line_data)
-
- lines_to_delete = order_models.FulfillmentLine.objects.filter(
- id__in=set(lines_to_remove)
- ).select_related("fulfillment")
-
- related_fulfillment_ids = [f.fulfillment.pk for f in lines_to_delete]
- related_fulfillment_ids.extend([f.fulfillment.pk for f in lines_to_update])
-
- if lines_to_update:
- order_models.FulfillmentLine.objects.bulk_update(
- lines_to_update, ["quantity"]
- )
-
- if lines_to_delete:
- lines_to_delete.delete()
-
- order_models.Fulfillment.objects.filter(
- pk__in=related_fulfillment_ids, lines=None
- ).delete()
-
- return order_lines_map, remaining_fulfillment_lines
-
- @classmethod
- def extend_order_lines(cls, order_lines, lines_data):
- """Extend order_lines with data from lines_data.
-
- If order line entry existed, increase it's quantity, create if it didn't.
- """
- for line, quantity in lines_data.items():
- appended = False
- for item in order_lines:
- if item.line == line:
- item.quantity += quantity
- appended = True
- if not appended:
- order_lines.append(
- OrderLineData(
- line=line,
- quantity=quantity,
- variant=None,
- replace=False,
- warehouse_pk=None,
- )
- )
- return order_lines
-
@classmethod
def perform_mutation(cls, _root, info, **data):
cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
order = cleaned_input["order"]
- order_lines_map, remaining_fulfillment_lines = cls.remove_waiting_fulfillments(
- cleaned_input.get("fulfillment_lines", [])
- )
-
- order_lines = cls.extend_order_lines(
- cleaned_input.get("order_lines", []), order_lines_map
- )
-
refund_fulfillment = create_refund_fulfillment(
info.context.user,
info.context.app,
order,
cleaned_input["payment"],
- order_lines,
- remaining_fulfillment_lines,
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
info.context.plugins,
cleaned_input["amount_to_refund"],
cleaned_input["include_shipping_costs"],
@@ -897,6 +799,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
whitelisted_statuses=[
FulfillmentStatus.FULFILLED,
FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
],
)
return cleaned_input
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index d6983cc88e..2a63e151aa 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -160,7 +160,7 @@ def test_order_fulfill_above_available_quantity(
"lines": [
{
"orderLineId": order_line_id,
- "stocks": [{"quantity": 3, "warehouse": warehouse_id}],
+ "stocks": [{"quantity": 4, "warehouse": warehouse_id}],
},
{
"orderLineId": order_line2_id,
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 06005f0146..5b0fa635e6 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -77,7 +77,6 @@ from ..shipping.types import ShippingMethod
from ..warehouse.types import Allocation, Warehouse
from .dataloaders import (
AllocationsByOrderLineIdLoader,
- FulfillmentLinesAwaitingApprovalByOrderLineIdLoader,
FulfillmentLinesByIdLoader,
FulfillmentsByOrderIdLoader,
OrderByIdLoader,
@@ -525,15 +524,7 @@ class OrderLine(CountableDjangoObjectType):
@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)
- )
+ return root.quantity_unfulfilled
@staticmethod
def resolve_undiscounted_unit_price(root: models.OrderLine, _info):
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 104cb528d6..b29f2986f1 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -350,6 +350,14 @@ def cancel_waiting_fulfillment(
events.fulfillment_canceled_event(
order=fulfillment.order, user=user, app=app, fulfillment=None
)
+
+ order_lines = []
+ for line in fulfillment:
+ order_line = line.order_line
+ order_line.quantity_fulfilled -= line.quantity
+ order_lines.append(order_line)
+ OrderLine.objects.bulk_update(order_lines, ["quantity_fulfilled"])
+
fulfillment.delete()
update_order_status(fulfillment.order)
transaction.on_commit(lambda: manager.fulfillment_canceled(fulfillment))
@@ -383,7 +391,7 @@ def approve_fulfillment(
)
for f_line in fulfillment.lines.all()
]
- fulfill_order_lines(lines_to_fulfill, manager)
+ _decrease_stocks(lines_to_fulfill, manager)
order.refresh_from_db()
update_order_status(order)
@@ -450,14 +458,13 @@ def clean_mark_order_as_paid(order: "Order"):
)
-@traced_atomic_transaction()
-def fulfill_order_lines(
- order_lines_info: Iterable["OrderLineData"], manager: "PluginsManager"
-):
- """Fulfill order line with given quantity."""
+def _decrease_stocks(order_lines_info, manager):
lines_to_decrease_stock = get_order_lines_with_track_inventory(order_lines_info)
if lines_to_decrease_stock:
decrease_stock(lines_to_decrease_stock, manager)
+
+
+def _increase_order_line_quantity(order_lines_info):
order_lines = []
for line_info in order_lines_info:
line = line_info.line
@@ -467,6 +474,16 @@ def fulfill_order_lines(
OrderLine.objects.bulk_update(order_lines, ["quantity_fulfilled"])
+@traced_atomic_transaction()
+def fulfill_order_lines(
+ order_lines_info: Iterable["OrderLineData"],
+ manager: "PluginsManager",
+):
+ """Fulfill order line with given quantity."""
+ _decrease_stocks(order_lines_info, manager)
+ _increase_order_line_quantity(order_lines_info)
+
+
@traced_atomic_transaction()
def automatically_fulfill_digital_lines(order: "Order", manager: "PluginsManager"):
"""Fulfill all digital lines which have enabled automatic fulfillment setting.
@@ -599,8 +616,10 @@ def _create_fulfillment_lines(
if insufficient_stocks:
raise InsufficientStock(insufficient_stocks)
- if lines_info and decrease_stock:
- fulfill_order_lines(lines_info, manager)
+ if lines_info:
+ if decrease_stock:
+ _decrease_stocks(lines_info, manager)
+ _increase_order_line_quantity(lines_info)
return fulfillment_lines
@@ -897,8 +916,14 @@ def create_refund_fulfillment(
target_fulfillment=refunded_fulfillment,
)
+ # Delete fulfillments without lines after lines are moved.
Fulfillment.objects.filter(
- order=order, lines=None, status=FulfillmentStatus.FULFILLED
+ order=order,
+ lines=None,
+ status__in=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
+ ],
).delete()
transaction.on_commit(lambda: manager.order_updated(order))
@@ -1257,7 +1282,12 @@ def create_fulfillments_for_returned_products(
manager=manager,
)
Fulfillment.objects.filter(
- order=order, lines=None, status=FulfillmentStatus.FULFILLED
+ order=order,
+ lines=None,
+ status__in=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
+ ],
).delete()
transaction.on_commit(lambda: manager.order_updated(order))
diff --git a/saleor/order/migrations/0118_auto_20210913_0731.py b/saleor/order/migrations/0118_auto_20210913_0731.py
new file mode 100644
index 0000000000..b031d7b2c9
--- /dev/null
+++ b/saleor/order/migrations/0118_auto_20210913_0731.py
@@ -0,0 +1,48 @@
+# Generated by Django 3.2.6 on 2021-09-13 07:31
+
+from django.db import migrations
+
+from ...order import FulfillmentStatus
+
+
+def increase_order_lines_quantity_for_waiting_fulfillments(apps, schema):
+ """Increase order_line quantity fulfilled.
+
+ Add quantity of each related fulfillment line
+ which fulfillment is in WAITING_FOR_APPROVAL state.
+ """
+ FulfillmentLine = apps.get_model("order", "FulfillmentLine")
+ for fulfillment_line in FulfillmentLine.objects.filter(
+ fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL
+ ).iterator():
+ order_line = fulfillment_line.order_line
+ order_line.quantity_fulfilled += fulfillment_line.quantity
+ if order_line.quantity_fulfilled > order_line.quantity:
+ order_line.quantity_fulfilled = order_line.quantity
+ order_line.save(update_fields=["quantity_fulfilled"])
+
+
+def decrease_order_lines_quantity_for_waiting_fulfillments(apps, schema):
+ FulfillmentLine = apps.get_model("order", "FulfillmentLine")
+ for fulfillment_line in FulfillmentLine.objects.filter(
+ fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL
+ ).iterator():
+ order_line = fulfillment_line.order_line
+ order_line.quantity_fulfilled -= fulfillment_line.quantity
+ if order_line.quantity_fulfilled < 0:
+ order_line.quantity_fulfilled = 0
+ order_line.save(update_fields=["quantity_fulfilled"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0117_merge_20210903_1013"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ increase_order_lines_quantity_for_waiting_fulfillments,
+ reverse_code=decrease_order_lines_quantity_for_waiting_fulfillments,
+ ),
+ ]
diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfullments_actions.py
index c9e08cfec6..ba7887bc62 100644
--- a/saleor/order/tests/test_fulfullments_actions.py
+++ b/saleor/order/tests/test_fulfullments_actions.py
@@ -99,12 +99,12 @@ def test_create_fulfillments_require_approval(
assert fulfillment_lines[1].stock == order_line2.variant.stocks.get()
assert fulfillment_lines[1].quantity == 2
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.FULFILLED
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 order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
assert (
Allocation.objects.filter(
@@ -155,12 +155,12 @@ def test_create_fulfillments_require_approval_as_app(
assert fulfillment_lines[1].stock == order_line2.variant.stocks.get()
assert fulfillment_lines[1].quantity == 2
- assert order.status == OrderStatus.UNFULFILLED
+ assert order.status == OrderStatus.FULFILLED
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 order_line1.quantity_fulfilled == 3
+ assert order_line2.quantity_fulfilled == 2
assert (
Allocation.objects.filter(