Skip to content

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

Fix fulfillments refund with waiting for approval state (#7938)

Tomasz Szymański5cd79a0be74f
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index da1fdc3da1..f22fa0f40e 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -652,21 +652,105 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
whitelisted_statuses=[
FulfillmentStatus.FULFILLED,
FulfillmentStatus.RETURNED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
],
)
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"],
- cleaned_input.get("order_lines", []),
- cleaned_input.get("fulfillment_lines", []),
+ order_lines,
+ remaining_fulfillment_lines,
info.context.plugins,
cleaned_input["amount_to_refund"],
cleaned_input["include_shipping_costs"],
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index d8de363422..7ccf84c24c 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -6,7 +6,7 @@ from prices import Money, TaxedMoney
from ....core.prices import quantize_price
from ....order.error_codes import OrderErrorCode
-from ....order.models import FulfillmentStatus
+from ....order.models import FulfillmentLine, FulfillmentStatus
from ....payment import ChargeStatus, PaymentError
from ....warehouse.models import Allocation, Stock
from ...tests.utils import get_graphql_content
@@ -304,6 +304,61 @@ def test_fulfillment_refund_products_fulfillment_lines(
)
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_refund_products_waiting_fulfillment_lines(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfillment = fulfilled_order.fulfillments.first()
+ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL
+ fulfillment.save(update_fields=["status"])
+ fulfilled_order.payments.add(payment_dummy)
+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()
+ fulfillment_line_to_refund.order_line.quantity_fulfilled = 0
+ fulfillment_line_to_refund.order_line.save(update_fields=["quantity_fulfilled"])
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ fulfillment_line_id = graphene.Node.to_global_id(
+ "FulfillmentLine", fulfillment_line_to_refund.pk
+ )
+ order_line_id = graphene.Node.to_global_id(
+ "OrderLine", fulfillment_line_to_refund.order_line.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "fulfillmentLines": [
+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 3}
+ ]
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ refund_fulfillment = data["fulfillment"]
+ errors = data["errors"]
+
+ assert not errors
+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()
+ assert len(refund_fulfillment["lines"]) == 1
+ assert refund_fulfillment["lines"][0]["orderLine"]["id"] == order_line_id
+ assert refund_fulfillment["lines"][0]["quantity"] == 3
+ assert not FulfillmentLine.objects.filter(pk=fulfillment_line_to_refund.pk).exists()
+ mocked_refund.assert_called_with(
+ payment_dummy,
+ ANY,
+ amount=fulfillment_line_to_refund.order_line.unit_price_gross_amount * 3,
+ channel_slug=fulfilled_order.channel.slug,
+ )
+
+
def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_total(
staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
):