Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add refund products support (#6530)
Maciej Korycinski305415e0f8b7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 22c754b752..43dfff6019 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ All notable, unreleased changes to this project will be documented in this file.- Order confirmation backend - #6498 by @tomaszszymanski129- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki- Fix password reset request - #6351 by @Manfred-Madelaine-pro, Ambroise and Pierre+- Refund products support - #6530 by @korycins- Add possibility to exclude products from shipping method - #6506 by @korycins# 2.11.1diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex 88dfe40298..347d395729 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -6,17 +6,21 @@ from django.template.defaultfilters import pluralizefrom ....core.exceptions import InsufficientStockfrom ....core.permissions import OrderPermissions+from ....order import FulfillmentStatus, models as order_modelsfrom ....order.actions import (cancel_fulfillment,create_fulfillments,+ create_refund_fulfillment,fulfillment_tracking_updated,)from ....order.emails import send_fulfillment_updatefrom ....order.error_codes import OrderErrorCodefrom ...core.mutations import BaseMutation+from ...core.scalars import PositiveDecimalfrom ...core.types.common import OrderErrorfrom ...core.utils import from_global_id_strict_type, get_duplicated_values-from ...order.types import Fulfillment, Order+from ...order.types import Fulfillment, FulfillmentLine, Order+from ...utils import get_user_or_app_from_contextfrom ...warehouse.types import Warehousefrom ..types import OrderLine@@ -308,3 +312,219 @@ class FulfillmentCancel(BaseMutation):fulfillment.refresh_from_db(fields=["status"])order.refresh_from_db(fields=["status"])return FulfillmentCancel(fulfillment=fulfillment, order=order)+++class OrderRefundLineInput(graphene.InputObjectType):+ order_line_id = graphene.ID(+ description="The ID of the order line to refund.",+ name="orderLineId",+ required=True,+ )+ quantity = graphene.Int(+ description="The number of items to be refunded.", required=True,+ )+++class OrderRefundFulfillmentLineInput(graphene.InputObjectType):+ fulfillment_line_id = graphene.ID(+ description="The ID of the fulfillment line to refund.",+ name="fulfillmentLineId",+ required=True,+ )+ quantity = graphene.Int(+ description="The number of items to be refunded.", required=True,+ )+++class OrderRefundProductsInput(graphene.InputObjectType):+ order_lines = graphene.List(+ graphene.NonNull(OrderRefundLineInput),+ description="List of unfulfilled lines to refund.",+ )+ fulfillment_lines = graphene.List(+ graphene.NonNull(OrderRefundFulfillmentLineInput),+ description="List of fulfilled lines to refund.",+ )+ amount_to_refund = PositiveDecimal(+ required=False,+ description=("The total amount of refund when the value is provided manually."),+ )+ include_shipping_costs = graphene.Boolean(+ description=(+ "If true, Saleor will refund shipping costs. If amountToRefund is provided"+ "includeShippingCosts will be ignored."+ ),+ default_value=False,+ )+++class FulfillmentRefundProducts(BaseMutation):+ fulfillment = graphene.Field(Fulfillment, description="A refunded fulfillment.")+ order = graphene.Field(Order, description="Order which fulfillment was refunded.")++ class Arguments:+ order = graphene.ID(+ description="ID of the order to be refunded.", required=True+ )+ input = OrderRefundProductsInput(+ required=True,+ description="Fields required to create an refund fulfillment.",+ )++ class Meta:+ description = "Refund products."+ permissions = (OrderPermissions.MANAGE_ORDERS,)+ error_type_class = OrderError+ error_type_field = "order_errors"++ @classmethod+ def clean_order_payment(cls, payment, cleaned_input):+ if not payment or not payment.can_refund():+ raise ValidationError(+ {+ "order": ValidationError(+ "Order cannot be refunded.",+ code=OrderErrorCode.CANNOT_REFUND.value,+ )+ }+ )+ cleaned_input["payment"] = payment++ @classmethod+ def clean_amount_to_refund(cls, amount_to_refund, payment, cleaned_input):+ if amount_to_refund is not None and amount_to_refund > payment.captured_amount:+ raise ValidationError(+ {+ "amount_to_refund": ValidationError(+ (+ "The amountToRefund is greater than the maximal possible "+ "amount to refund."+ ),+ code=OrderErrorCode.CANNOT_REFUND.value,+ ),+ }+ )+ cleaned_input["amount_to_refund"] = amount_to_refund++ @classmethod+ def clean_input(cls, info, order_id, input):+ cleaned_input = {}+ amount_to_refund = input.get("amount_to_refund")+ include_shipping_costs = input["include_shipping_costs"]++ qs = order_models.Order.objects.prefetch_related("payments")+ order = cls.get_node_or_error(+ info, order_id, field="order", only_type=Order, qs=qs+ )+ payment = order.get_last_payment()+ cls.clean_order_payment(payment, cleaned_input)+ cls.clean_amount_to_refund(amount_to_refund, payment, cleaned_input)++ cleaned_input.update(+ {"include_shipping_costs": include_shipping_costs, "order": order}+ )++ order_lines_data = input.get("order_lines")+ fulfillment_lines_data = input.get("fulfillment_lines")++ if order_lines_data:+ cls.clean_lines(order_lines_data, cleaned_input)+ if fulfillment_lines_data:+ cls.clean_fulfillment_lines(fulfillment_lines_data, cleaned_input)+ return cleaned_input++ @classmethod+ def _raise_error_for_line(cls, msg, type, line_id, field_name, code=None):+ line_global_id = graphene.Node.to_global_id(type, line_id)+ if not code:+ code = OrderErrorCode.INVALID_REFUND_QUANTITY.value+ raise ValidationError(+ {+ field_name: ValidationError(+ msg, code=code, params={field_name: line_global_id},+ )+ }+ )++ @classmethod+ def clean_fulfillment_lines(cls, fulfillment_lines_data, cleaned_input):+ lines_ids = [line["fulfillment_line_id"] for line in fulfillment_lines_data]+ quantities_to_refund = [line["quantity"] for line in fulfillment_lines_data]+ lines_to_refund = cls.get_nodes_or_error(+ lines_ids,+ field="fulfillment_lines",+ only_type=FulfillmentLine,+ qs=order_models.FulfillmentLine.objects.prefetch_related("fulfillment"),+ )+ lines_to_refund = list(lines_to_refund)+ for line, quantity in zip(lines_to_refund, quantities_to_refund):+ if line.quantity < quantity:+ cls._raise_error_for_line(+ "Quantity provided to refund is bigger than quantity from "+ "fulfillment line",+ "FulfillmentLine",+ line.pk,+ "fulfillment_line_id",+ )+ if line.fulfillment.status != FulfillmentStatus.FULFILLED:+ cls._raise_error_for_line(+ "Unable to refund fulfillmentLine with different type than "+ "FULFILLED.",+ "FulfillmentLine",+ line.pk,+ "fulfillment_line_id",+ code=OrderErrorCode.CANNOT_REFUND_FULFILLMENT_LINE.value,+ )+ cleaned_input["fulfillment_lines_quantities_to_refund"] = quantities_to_refund+ cleaned_input["fulfillment_lines_to_refund"] = lines_to_refund++ @classmethod+ def clean_lines(cls, lines_data, cleaned_input):+ lines_ids = [line["order_line_id"] for line in lines_data]+ quantities_to_refund = [line["quantity"] for line in lines_data]+ lines_to_refund = cls.get_nodes_or_error(+ lines_ids,+ field="order_lines",+ only_type=OrderLine,+ qs=order_models.OrderLine.objects.prefetch_related(+ "fulfillment_lines__fulfillment"+ ),+ )+ lines_to_refund = list(lines_to_refund)+ for line, quantity in zip(lines_to_refund, quantities_to_refund):+ if line.quantity < quantity:+ cls._raise_error_for_line(+ "Quantity provided to refund is bigger than quantity from order "+ "line.",+ "OrderLine",+ line.pk,+ "order_line_id",+ )+ quantity_ready_to_refund = line.quantity_unfulfilled+ if quantity_ready_to_refund < quantity:+ cls._raise_error_for_line(+ "Quantity provided to refund is bigger than unfulfilled quantity.",+ "OrderLine",+ line.pk,+ "order_line_id",+ )++ cleaned_input["order_lines_quantities_to_refund"] = quantities_to_refund+ cleaned_input["order_lines_to_refund"] = lines_to_refund++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))+ order = cleaned_input["order"]+ refund_fulfillment = create_refund_fulfillment(+ get_user_or_app_from_context(info.context),+ order,+ cleaned_input["payment"],+ cleaned_input.get("order_lines_to_refund", []),+ cleaned_input.get("order_lines_quantities_to_refund", []),+ cleaned_input.get("fulfillment_lines_to_refund", []),+ cleaned_input.get("fulfillment_lines_quantities_to_refund", []),+ cleaned_input["amount_to_refund"],+ cleaned_input["include_shipping_costs"],+ )+ return cls(order=order, fulfillment=refund_fulfillment)diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 0f3040ffd8..662d3f27ee 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -21,6 +21,7 @@ from .mutations.draft_orders import ()from .mutations.fulfillments import (FulfillmentCancel,+ FulfillmentRefundProducts,FulfillmentUpdateTracking,OrderFulfill,)@@ -160,9 +161,12 @@ class OrderMutations(graphene.ObjectType):order_cancel = OrderCancel.Field()order_capture = OrderCapture.Field()order_confirm = OrderConfirm.Field()+order_fulfill = OrderFulfill.Field()order_fulfillment_cancel = FulfillmentCancel.Field()order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()+ order_fulfillment_refund_products = FulfillmentRefundProducts.Field()+order_mark_as_paid = OrderMarkAsPaid.Field()order_refund = OrderRefund.Field()order_update = OrderUpdate.Field()diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex e61b9d5a68..60b773fa06 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -1,13 +1,17 @@+from decimal import Decimalfrom unittest.mock import patchimport graphenefrom django.contrib.auth.models import AnonymousUser+from prices import Money, TaxedMoneyfrom ....core.exceptions import InsufficientStock+from ....core.prices import quantize_pricefrom ....order import OrderStatusfrom ....order.error_codes import OrderErrorCodefrom ....order.events import OrderEventsfrom ....order.models import FulfillmentStatus+from ....payment import ChargeStatusfrom ....warehouse.models import Allocation, Stockfrom ...tests.utils import assert_no_permission, get_graphql_content@@ -827,3 +831,541 @@ def test_staff_can_query_order_fulfill_data_without_permission(variables = {"id": order_id}response = staff_api_client.post_graphql(QUERY_ORDER_FULFILL_DATA, variables)assert_no_permission(response)+++ORDER_FULFILL_REFUND_MUTATION = """+mutation OrderFulfillmentRefundProducts(+ $order: ID!, $input: OrderRefundProductsInput!+) {+ orderFulfillmentRefundProducts(+ order: $order,+ input: $input+ ) {+ fulfillment{+ id+ status+ lines{+ id+ quantity+ orderLine{+ id+ }+ }+ }+ orderErrors {+ field+ code+ message+ warehouse+ orderLine+ }+ }+}+"""+++def test_fulfillment_refund_products_order_without_payment(+ staff_api_client, permission_manage_orders, fulfilled_order+):+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)+ variables = {"order": order_id, "input": {"amountToRefund": "11.00"}}+ 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"]+ fulfillment = data["fulfillment"]+ errors = data["orderErrors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "order"+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name+ assert fulfillment is None+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_amount_and_shipping_costs(+ mocked_refund,+ staff_api_client,+ permission_manage_orders,+ fulfilled_order,+ payment_dummy,+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ fulfilled_order.payments.add(payment_dummy)+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)+ amount_to_refund = Decimal("11.00")+ variables = {+ "order": order_id,+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)++ mocked_refund.assert_called_with(+ payment_dummy, quantize_price(amount_to_refund, fulfilled_order.currency)+ )+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_order_lines(+ mocked_refund,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ payment_dummy,+):+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ line_to_refund = order_with_lines.lines.first()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 2}]},+ }+ 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["orderErrors"]+ assert not errors+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()+ assert len(refund_fulfillment["lines"]) == 1+ assert refund_fulfillment["lines"][0]["orderLine"]["id"] == line_id+ assert refund_fulfillment["lines"][0]["quantity"] == 2+ mocked_refund.assert_called_with(+ payment_dummy, line_to_refund.unit_price_gross_amount * 2+ )+++def test_fulfillment_refund_products_order_lines_quantity_bigger_than_total(+ staff_api_client, permission_manage_orders, order_with_lines, payment_dummy+):+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ line_to_refund = order_with_lines.lines.first()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 200}]},+ }+ 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["orderErrors"]++ assert len(errors) == 1+ assert errors[0]["field"] == "orderLineId"+ assert errors[0]["code"] == OrderErrorCode.INVALID_REFUND_QUANTITY.name+ assert refund_fulfillment is None+++def test_fulfillment_refund_products_order_lines_quantity_bigger_than_unfulfilled(+ staff_api_client, permission_manage_orders, order_with_lines, payment_dummy+):+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ line_to_refund = order_with_lines.lines.first()+ line_to_refund.quantity = 3+ line_to_refund.quantity_fulfilled = 3+ line_to_refund.save()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},+ }+ 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["orderErrors"]++ assert len(errors) == 1+ assert errors[0]["field"] == "orderLineId"+ assert errors[0]["code"] == OrderErrorCode.INVALID_REFUND_QUANTITY.name+ assert refund_fulfillment is None+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_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()+ fulfilled_order.payments.add(payment_dummy)+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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": 2}+ ]+ },+ }+ 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["orderErrors"]++ 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"] == 2+ mocked_refund.assert_called_with(+ payment_dummy, fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2+ )+++def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_total(+ 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()+ fulfilled_order.payments.add(payment_dummy)+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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+ )+ variables = {+ "order": order_id,+ "input": {+ "fulfillmentLines": [+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 200}+ ]+ },+ }+ 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["orderErrors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "fulfillmentLineId"+ assert errors[0]["code"] == OrderErrorCode.INVALID_REFUND_QUANTITY.name+ assert refund_fulfillment is None+++def test_fulfillment_refund_products_amount_bigger_than_captured_amount(+ 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()+ fulfilled_order.payments.add(payment_dummy)+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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+ )+ variables = {+ "order": order_id,+ "input": {+ "amountToRefund": "1000.00",+ "fulfillmentLines": [+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 2}+ ],+ },+ }+ 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["orderErrors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "amountToRefund"+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name+ assert refund_fulfillment is None+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_fulfillment_lines_include_shipping_costs(+ 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()+ fulfilled_order.payments.add(payment_dummy)+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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": {+ "includeShippingCosts": True,+ "fulfillmentLines": [+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 2}+ ],+ },+ }+ 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["orderErrors"]++ 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"] == 2+ amount = fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2+ amount += fulfilled_order.shipping_price_gross_amount+ mocked_refund.assert_called_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_order_lines_include_shipping_costs(+ mocked_refund,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ payment_dummy,+):+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ line_to_refund = order_with_lines.lines.first()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {+ "includeShippingCosts": True,+ "orderLines": [{"orderLineId": line_id, "quantity": 2}],+ },+ }+ 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["orderErrors"]+ assert not errors+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()+ assert len(refund_fulfillment["lines"]) == 1+ assert refund_fulfillment["lines"][0]["orderLine"]["id"] == line_id+ assert refund_fulfillment["lines"][0]["quantity"] == 2+ amount = line_to_refund.unit_price_gross_amount * 2+ amount += order_with_lines.shipping_price_gross_amount+ mocked_refund.assert_called_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_fulfillment_lines_custom_amount(+ 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()+ fulfilled_order.payments.add(payment_dummy)+ amount_to_refund = Decimal("10.99")+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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": {+ "amountToRefund": amount_to_refund,+ "fulfillmentLines": [+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 2}+ ],+ },+ }+ 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["orderErrors"]++ 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"] == 2+ mocked_refund.assert_called_with(payment_dummy, amount_to_refund)+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_order_lines_custom_amount(+ mocked_refund,+ staff_api_client,+ permission_manage_orders,+ order_with_lines,+ payment_dummy,+):+ payment_dummy.total = order_with_lines.total_gross_amount+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ amount_to_refund = Decimal("10.99")+ line_to_refund = order_with_lines.lines.first()+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)+ variables = {+ "order": order_id,+ "input": {+ "amountToRefund": amount_to_refund,+ "orderLines": [{"orderLineId": line_id, "quantity": 2}],+ },+ }+ 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["orderErrors"]+ assert not errors+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()+ assert len(refund_fulfillment["lines"]) == 1+ assert refund_fulfillment["lines"][0]["orderLine"]["id"] == line_id+ assert refund_fulfillment["lines"][0]["quantity"] == 2+ mocked_refund.assert_called_with(payment_dummy, amount_to_refund)+++@patch("saleor.order.actions.gateway.refund")+def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(+ mocked_refund,+ warehouse,+ variant,+ channel_USD,+ 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()+ fulfilled_order.payments.add(payment_dummy)+ stock = Stock.objects.create(+ warehouse=warehouse, product_variant=variant, quantity=5+ )+ net = variant.get_price(channel_USD.slug)+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)+ order_line = fulfilled_order.lines.create(+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=5,+ quantity_fulfilled=2,+ variant=variant,+ unit_price=TaxedMoney(net=net, gross=gross),+ tax_rate=23,+ )+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=order_line.quantity+ )+ fulfillment = fulfilled_order.fulfillments.get()+ fulfillment.lines.create(order_line=order_line, quantity=2, stock=stock)+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()+ 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_from_fulfillment_line = graphene.Node.to_global_id(+ "OrderLine", fulfillment_line_to_refund.order_line.pk+ )+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)+ variables = {+ "order": order_id,+ "input": {+ "orderLines": [{"orderLineId": order_line_id, "quantity": 2}],+ "fulfillmentLines": [+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 2}+ ],+ },+ }+ 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["orderErrors"]++ assert not errors+ assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()+ assert len(refund_fulfillment["lines"]) == 2+ assert refund_fulfillment["lines"][0]["orderLine"]["id"] in [+ order_line_id,+ order_line_from_fulfillment_line,+ ]+ assert refund_fulfillment["lines"][0]["quantity"] == 2++ assert refund_fulfillment["lines"][1]["orderLine"]["id"] in [+ order_line_id,+ order_line_from_fulfillment_line,+ ]+ assert refund_fulfillment["lines"][1]["quantity"] == 2+ amount = fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2+ amount += order_line.unit_price_gross_amount * 2+ amount = quantize_price(amount, fulfilled_order.currency)+ mocked_refund.assert_called_with(payment_dummy, amount)diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 9228f388ec..55f52faa37 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -76,6 +76,9 @@ class OrderEvent(CountableDjangoObjectType):transaction_reference = graphene.String(description="The transaction reference of captured payment.")+ shipping_costs_included = graphene.Boolean(+ description="Define if shipping costs were included to the refund."+ )class Meta:description = "History log of the order."@@ -183,6 +186,10 @@ class OrderEvent(CountableDjangoObjectType):def resolve_transaction_reference(root: models.OrderEvent, _info):return root.parameters.get("transaction_reference")+ @staticmethod+ def resolve_shipping_costs_included(root: models.OrderEvent, _info):+ return root.parameters.get("shipping_costs_included")+class FulfillmentLine(CountableDjangoObjectType):order_line = graphene.Field(lambda: OrderLine)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e73baff3d1..07eb8993f4 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2000,8 +2000,16 @@ type FulfillmentLine implements Node {orderLine: OrderLine}+type FulfillmentRefundProducts {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ fulfillment: Fulfillment+ order: Order+ orderErrors: [OrderError!]!+}+enum FulfillmentStatus {FULFILLED+ REFUNDEDCANCELED}@@ -2653,6 +2661,7 @@ type Mutation {orderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfillorderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancelorderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking+ orderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProductsorderMarkAsPaid(id: ID!, transactionReference: String): OrderMarkAsPaidorderRefund(amount: PositiveDecimal!, id: ID!): OrderRefundorderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate@@ -2950,6 +2959,8 @@ enum OrderErrorCode {UNIQUEVOID_INACTIVE_PAYMENTZERO_QUANTITY+ INVALID_REFUND_QUANTITY+ CANNOT_REFUND_FULFILLMENT_LINEINSUFFICIENT_STOCKDUPLICATED_INPUT_ITEMNOT_AVAILABLE_IN_CHANNEL@@ -2976,6 +2987,7 @@ type OrderEvent implements Node {fulfilledItems: [FulfillmentLine]warehouse: WarehousetransactionReference: String+ shippingCostsIncluded: Boolean}type OrderEventCountableConnection {@@ -3033,6 +3045,7 @@ enum OrderEventsEnum {FULFILLMENT_CANCELEDFULFILLMENT_RESTOCKED_ITEMSFULFILLMENT_FULFILLED_ITEMS+ FULFILLMENT_REFUNDEDTRACKING_UPDATEDNOTE_ADDEDOTHER@@ -3108,6 +3121,23 @@ type OrderRefund {orderErrors: [OrderError!]!}+input OrderRefundFulfillmentLineInput {+ fulfillmentLineId: ID!+ quantity: Int!+}++input OrderRefundLineInput {+ orderLineId: ID!+ quantity: Int!+}++input OrderRefundProductsInput {+ orderLines: [OrderRefundLineInput!]+ fulfillmentLines: [OrderRefundFulfillmentLineInput!]+ amountToRefund: PositiveDecimal+ includeShippingCosts: Boolean = false+}+type OrderSettings {automaticallyConfirmAllNewOrders: Boolean!}diff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex 07be3266dd..7262c098ab 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -22,10 +22,12 @@ class OrderStatus:class FulfillmentStatus:FULFILLED = "fulfilled" # group of products in an order marked as fulfilled+ REFUNDED = "refunded" # group of refunded productsCANCELED = "canceled" # fulfilled group of products in an order marked as canceledCHOICES = [(FULFILLED, "Fulfilled"),+ (REFUNDED, "Refunded"),(CANCELED, "Canceled"),]@@ -66,6 +68,7 @@ class OrderEvents:FULFILLMENT_CANCELED = "fulfillment_canceled"FULFILLMENT_RESTOCKED_ITEMS = "fulfillment_restocked_items"FULFILLMENT_FULFILLED_ITEMS = "fulfillment_fulfilled_items"+ FULFILLMENT_REFUNDED = "fulfillment_refunded"TRACKING_UPDATED = "tracking_updated"NOTE_ADDED = "note_added"@@ -98,6 +101,7 @@ class OrderEvents:(FULFILLMENT_CANCELED, "A fulfillment was canceled"),(FULFILLMENT_RESTOCKED_ITEMS, "The items of the fulfillment were restocked"),(FULFILLMENT_FULFILLED_ITEMS, "Some items were fulfilled"),+ (FULFILLMENT_REFUNDED, "Some items were refunded"),(TRACKING_UPDATED, "The fulfillment's tracking code was updated"),(NOTE_ADDED, "A note was added to the order"),(OTHER, "An unknown order event containing a message"),diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 712b5006f0..796a278860 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -1,6 +1,6 @@import loggingfrom decimal import Decimal-from typing import TYPE_CHECKING, Dict, List, Optional+from typing import TYPE_CHECKING, Dict, List, Optional, Tuplefrom django.contrib.sites.models import Sitefrom django.db import transaction@@ -8,11 +8,21 @@ from django.db import transactionfrom ..core import analyticsfrom ..core.exceptions import InsufficientStockfrom ..order.emails import send_order_confirmed-from ..payment import ChargeStatus, CustomPaymentChoices, PaymentError, TransactionKind+from ..payment import (+ ChargeStatus,+ CustomPaymentChoices,+ PaymentError,+ TransactionKind,+ gateway,+)from ..payment.models import Payment, Transactionfrom ..payment.utils import create_paymentfrom ..plugins.manager import get_plugins_manager-from ..warehouse.management import deallocate_stock_for_order, decrease_stock+from ..warehouse.management import (+ deallocate_stock,+ deallocate_stock_for_order,+ decrease_stock,+)from . import FulfillmentStatus, OrderStatus, emails, events, utilsfrom .emails import (send_fulfillment_confirmation_to_customer,@@ -20,7 +30,8 @@ from .emails import (send_order_refunded_confirmation,send_payment_confirmation,)-from .models import Fulfillment, FulfillmentLine+from .events import fulfillment_refunded_event+from .models import Fulfillment, FulfillmentLine, OrderLinefrom .utils import (order_line_needs_automatic_fulfillment,recalculate_order,@@ -406,3 +417,231 @@ def create_fulfillments(fulfillments, requester, fulfillment_lines, notify_customer,)return fulfillments+++def _get_fulfillment_line_if_exists(+ fulfillment_lines: List[FulfillmentLine], order_line_id, stock_id=None+):+ for line in fulfillment_lines:+ if line.order_line_id == order_line_id and line.stock_id == stock_id:+ return line+ return None+++def _refund_fulfillment_for_order_lines(+ order_lines_to_refund: List[OrderLine],+ order_lines_quantities_to_refund: List[int],+ already_refunded_lines: List[FulfillmentLine],+ refunded_fulfillment: Fulfillment,+ all_refunded_lines: Dict[int, Tuple[int, OrderLine]],+):+ """Proceed the refund for unfulfilled order lines."""+ fulfillment_lines_to_create: List[FulfillmentLine] = []+ fulfillment_lines_to_update: List[FulfillmentLine] = []+ order_lines_to_update: List[OrderLine] = []+ refund_amount = Decimal(0)++ for line_to_refund, quantity_to_refund in zip(+ order_lines_to_refund, order_lines_quantities_to_refund+ ):+ # Check if refund line for order_line_id and stock_id does not exist in DB.+ refunded_line = _get_fulfillment_line_if_exists(+ already_refunded_lines, line_to_refund.id+ )+ fulfillment_line_existed = True+ if not refunded_line:+ # Create new not saved FulfillmentLine object and assign it to refund+ # fulfillment+ fulfillment_line_existed = False+ refunded_line = FulfillmentLine(+ fulfillment=refunded_fulfillment, order_line=line_to_refund, quantity=0,+ )++ # calculate the quantity fulfilled/unfulfilled/to refund+ unfulfilled_to_refund = min(+ line_to_refund.quantity_unfulfilled, quantity_to_refund+ )+ quantity_to_refund -= unfulfilled_to_refund+ line_to_refund.quantity_fulfilled += unfulfilled_to_refund+ refunded_line.quantity += unfulfilled_to_refund++ # update current lines with new value of quantity+ order_lines_to_update.append(line_to_refund)++ refund_amount += line_to_refund.unit_price_gross_amount * unfulfilled_to_refund+ if refunded_line.quantity > 0 and not fulfillment_line_existed:+ # If this is new type of (orderl_line, stock) then we create new fulfillment+ # line+ fulfillment_lines_to_create.append(refunded_line)+ elif fulfillment_line_existed:+ # if refund fulfillment already have the same line, we just update the+ # quantity+ fulfillment_lines_to_update.append(refunded_line)++ deallocate_stock(line_to_refund, unfulfilled_to_refund)++ # prepare structure which will be used to create new order event.+ all_refunded_lines[line_to_refund.id] = (+ unfulfilled_to_refund,+ line_to_refund,+ )++ # update the fulfillment lines with new calues+ FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])+ FulfillmentLine.objects.bulk_create(fulfillment_lines_to_create)+ OrderLine.objects.bulk_update(order_lines_to_update, ["quantity_fulfilled"])+ return refund_amount+++def _refund_fulfillment_for_fulfillment_lines(+ fulfillment_lines_to_refund: List[FulfillmentLine],+ fulfillment_lines_quantities_to_refund: List[int],+ already_refunded_lines: List[FulfillmentLine],+ refunded_fulfillment: Fulfillment,+ all_refunded_lines: Dict[int, Tuple[int, OrderLine]],+):+ """Proceed the refund for fulfillment lines."""+ fulfillment_lines_to_create: List[FulfillmentLine] = []+ fulfillment_lines_to_update: List[FulfillmentLine] = []+ empty_fulfillment_lines_to_delete: List[FulfillmentLine] = []+ refund_amount = Decimal(0)++ # fetch order lines before for loop to save DB queries+ order_lines_with_fulfillment = OrderLine.objects.in_bulk(+ [line.order_line_id for line in fulfillment_lines_to_refund]+ )+ for fulfillment_line, quantity_to_refund in zip(+ fulfillment_lines_to_refund, fulfillment_lines_quantities_to_refund+ ):+ # Check if refund line for order_line_id and stock_id does not exist in DB.+ refunded_line = _get_fulfillment_line_if_exists(+ already_refunded_lines,+ fulfillment_line.order_line_id,+ fulfillment_line.stock_id,+ )+ fulfillment_line_existed = True+ if not refunded_line:+ # Create new not saved FulfillmentLine object and assign it to refund+ # fulfillment+ fulfillment_line_existed = False+ refunded_line = FulfillmentLine(+ fulfillment=refunded_fulfillment,+ order_line_id=fulfillment_line.order_line_id,+ stock_id=fulfillment_line.stock_id,+ quantity=0,+ )++ # calculate the quantity fulfilled/unfulfilled/to refund+ fulfilled_to_refund = min(fulfillment_line.quantity, quantity_to_refund)+ quantity_to_refund -= fulfilled_to_refund+ refunded_line.quantity += fulfilled_to_refund+ fulfillment_line.quantity -= fulfilled_to_refund++ order_line: OrderLine = order_lines_with_fulfillment.get( # type: ignore+ fulfillment_line.order_line_id+ )+ refund_amount += order_line.unit_price_gross_amount * fulfilled_to_refund++ if fulfillment_line.quantity == 0:+ # the fulfillment line without any items will be deleted+ empty_fulfillment_lines_to_delete.append(fulfillment_line)+ else:+ # update with new quantity value+ fulfillment_lines_to_update.append(fulfillment_line)++ if refunded_line.quantity > 0 and not fulfillment_line_existed:+ # If this is new type of (orderl_line, stock) then we create new fulfillment+ # line+ fulfillment_lines_to_create.append(refunded_line)+ elif fulfillment_line_existed:+ # if refund fulfillment already have the same line, we just update the+ # quantity+ fulfillment_lines_to_update.append(refunded_line)++ # check how many items we already refunded from unfulfilled lines for given+ # order_line.+ data_from_all_refunded_lines = all_refunded_lines.get(order_line.id)+ if data_from_all_refunded_lines:+ quantity, line = data_from_all_refunded_lines+ quantity += fulfilled_to_refund+ all_refunded_lines[order_line.id] = (quantity, line)+ else:+ all_refunded_lines[order_line.id] = (fulfilled_to_refund, order_line)++ # update the fulfillment lines with new calues+ FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])+ FulfillmentLine.objects.bulk_create(fulfillment_lines_to_create)++ # Remove the empty fulfillment lines+ FulfillmentLine.objects.filter(+ id__in=[f.id for f in empty_fulfillment_lines_to_delete]+ ).delete()+ return refund_amount+++def create_refund_fulfillment(+ requester: Optional["User"],+ order,+ payment,+ order_lines_to_refund: List[OrderLine],+ order_lines_quantities_to_refund: List[int],+ fulfillment_lines_to_refund: List[FulfillmentLine],+ fulfillment_lines_quantities_to_refund: List[int],+ amount=None,+ refund_shipping_costs=False,+):+ """Proceed with all steps required for refunding products.++ Calculate refunds for products based on the order's order lines and fulfillment+ lines. The logic takes the list of order lines, fulfillment lines, and their+ quantities which is used to create the refund fulfillment. The stock for+ unfulfilled lines will be deallocated. It creates only single refund fulfillment+ for each order. Calling the method N-time will increase the quantity of the already+ refunded line. The refund fulfillment can have assigned lines with the same+ products but with the different stocks.+ """+ with transaction.atomic():+ refunded_fulfillment, _ = Fulfillment.objects.get_or_create(+ status=FulfillmentStatus.REFUNDED, order=order+ )+ already_refunded_lines = list(refunded_fulfillment.lines.all())+ all_refunded_lines: Dict[int, Tuple[int, OrderLine]] = dict()+ refund_order_lines = _refund_fulfillment_for_order_lines(+ order_lines_to_refund=order_lines_to_refund,+ order_lines_quantities_to_refund=order_lines_quantities_to_refund,+ already_refunded_lines=already_refunded_lines,+ refunded_fulfillment=refunded_fulfillment,+ all_refunded_lines=all_refunded_lines,+ )+ refund_fulfillment_lines = _refund_fulfillment_for_fulfillment_lines(+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=(+ fulfillment_lines_quantities_to_refund+ ),+ already_refunded_lines=already_refunded_lines,+ refunded_fulfillment=refunded_fulfillment,+ all_refunded_lines=all_refunded_lines,+ )+ refund_amount = refund_order_lines + refund_fulfillment_lines++ Fulfillment.objects.filter(order=order, lines=None).delete()++ if amount is None:+ amount = refund_amount+ # we take into consideration the shipping costs only when amount is not+ # provided.+ if refund_shipping_costs:+ amount += order.shipping_price_gross_amount+ if amount:+ amount = min(payment.captured_amount, amount)+ gateway.refund(payment, amount)+ order_refunded(order, requester, amount, payment)++ fulfillment_refunded_event(+ order=order,+ user=requester,+ refunded_lines=list(all_refunded_lines.values()),+ amount=amount,+ shipping_costs_included=refund_shipping_costs,+ )+ return refunded_fulfillmentdiff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.pyindex 120c04c265..84c963709d 100644--- a/saleor/order/error_codes.py+++ b/saleor/order/error_codes.py@@ -25,6 +25,8 @@ class OrderErrorCode(Enum):UNIQUE = "unique"VOID_INACTIVE_PAYMENT = "void_inactive_payment"ZERO_QUANTITY = "zero_quantity"+ INVALID_REFUND_QUANTITY = "invalid_refund_quantity"+ CANNOT_REFUND_FULFILLMENT_LINE = "cannot_refund_fulfillmet_line"INSUFFICIENT_STOCK = "insufficient_stock"DUPLICATED_INPUT_ITEM = "duplicated_input_item"NOT_AVAILABLE_IN_CHANNEL = "not_available_in_channel"diff --git a/saleor/order/events.py b/saleor/order/events.pyindex 4071098c04..8960cd02e1 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -338,6 +338,28 @@ def fulfillment_fulfilled_items_event()+def fulfillment_refunded_event(+ *,+ order: Order,+ user: UserType,+ refunded_lines: List[Tuple[int, OrderLine]],+ amount: Decimal,+ shipping_costs_included: bool+):+ if not _user_is_valid(user):+ user = None+ return OrderEvent.objects.create(+ order=order,+ type=OrderEvents.FULFILLMENT_REFUNDED,+ user=user,+ parameters={+ "lines": _lines_per_quantity_to_line_object_list(refunded_lines),+ "amount": amount,+ "shipping_costs_included": shipping_costs_included,+ },+ )++def fulfillment_tracking_updated_event(*, order: Order, user: UserType, tracking_number: str, fulfillment: Fulfillment) -> OrderEvent:diff --git a/saleor/order/migrations/0093_auto_20201130_1406.py b/saleor/order/migrations/0093_auto_20201130_1406.pynew file mode 100644index 0000000000..f31c410530--- /dev/null+++ b/saleor/order/migrations/0093_auto_20201130_1406.py@@ -0,0 +1,74 @@+# Generated by Django 3.1.3 on 2020-11-30 14:06++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0092_order_unconfirmed"),+ ]++ operations = [+ migrations.AlterField(+ model_name="fulfillment",+ name="status",+ field=models.CharField(+ choices=[+ ("fulfilled", "Fulfilled"),+ ("refunded", "Refunded"),+ ("canceled", "Canceled"),+ ],+ default="fulfilled",+ max_length=32,+ ),+ ),+ migrations.AlterField(+ model_name="fulfillmentline",+ name="order_line",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="fulfillment_lines",+ to="order.orderline",+ ),+ ),+ migrations.AlterField(+ model_name="orderevent",+ name="type",+ field=models.CharField(+ choices=[+ ("DRAFT_CREATED", "draft_created"),+ ("DRAFT_ADDED_PRODUCTS", "draft_added_products"),+ ("DRAFT_REMOVED_PRODUCTS", "draft_removed_products"),+ ("PLACED", "placed"),+ ("PLACED_FROM_DRAFT", "placed_from_draft"),+ ("OVERSOLD_ITEMS", "oversold_items"),+ ("CANCELED", "canceled"),+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),+ ("ORDER_FULLY_PAID", "order_fully_paid"),+ ("UPDATED_ADDRESS", "updated_address"),+ ("EMAIL_SENT", "email_sent"),+ ("CONFIRMED", "confirmed"),+ ("PAYMENT_AUTHORIZED", "payment_authorized"),+ ("PAYMENT_CAPTURED", "payment_captured"),+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),+ ("PAYMENT_REFUNDED", "payment_refunded"),+ ("PAYMENT_VOIDED", "payment_voided"),+ ("PAYMENT_FAILED", "payment_failed"),+ ("INVOICE_REQUESTED", "invoice_requested"),+ ("INVOICE_GENERATED", "invoice_generated"),+ ("INVOICE_UPDATED", "invoice_updated"),+ ("INVOICE_SENT", "invoice_sent"),+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),+ ("TRACKING_UPDATED", "tracking_updated"),+ ("NOTE_ADDED", "note_added"),+ ("OTHER", "other"),+ ],+ max_length=255,+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex fe9a8b99c8..f2eb23e112 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -489,7 +489,7 @@ class Fulfillment(ModelWithMetadata):class FulfillmentLine(models.Model):order_line = models.ForeignKey(- OrderLine, related_name="+", on_delete=models.CASCADE+ OrderLine, related_name="fulfillment_lines", on_delete=models.CASCADE)fulfillment = models.ForeignKey(Fulfillment, related_name="lines", on_delete=models.CASCADEdiff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.pyindex e94125baca..19f400bc19 100644--- a/saleor/order/tests/test_order_actions.py+++ b/saleor/order/tests/test_order_actions.py@@ -15,12 +15,13 @@ from ..actions import (cancel_fulfillment,cancel_order,clean_mark_order_as_paid,+ create_refund_fulfillment,fulfill_order_line,handle_fully_paid_order,mark_order_as_paid,order_refunded,)-from ..models import Fulfillment+from ..models import Fulfillment, FulfillmentLine@pytest.fixture@@ -316,3 +317,332 @@ def test_fulfill_digital_lines(assert fulfillment_lines.count() == 1assert line.digital_content_urlassert mock_email_fulfillment.delay.called+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_only_order_lines(+ mocked_refund, order_with_lines, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ payment = order_with_lines.get_last_payment()++ order_lines_to_refund = order_with_lines.lines.all()+ original_quantity = {+ line.id: line.quantity_unfulfilled for line in order_with_lines+ }+ order_line_ids = order_lines_to_refund.values_list("id", flat=True)+ original_allocations = list(+ Allocation.objects.filter(order_line_id__in=order_line_ids)+ )+ lines_count = order_with_lines.lines.count()+ order_lines_quantities_to_refund = [2 for _ in range(lines_count)]+ fulfillment_lines_to_refund = []+ fulfillment_lines_quantities_to_refund = []+ returned_fulfillemnt = create_refund_fulfillment(+ requester=None,+ order=order_with_lines,+ payment=payment,+ order_lines_to_refund=order_lines_to_refund,+ order_lines_quantities_to_refund=order_lines_quantities_to_refund,+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=fulfillment_lines_quantities_to_refund,+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == lines_count+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids+ for line in order_lines_to_refund:+ assert line.quantity_unfulfilled == original_quantity.get(line.pk) - 2++ current_allocations = Allocation.objects.in_bulk(+ [allocation.pk for allocation in original_allocations]+ )+ for original_allocation in original_allocations:+ current_allocation = current_allocations.get(original_allocation.pk)+ assert (+ original_allocation.quantity_allocated - 2+ == current_allocation.quantity_allocated+ )+ amount = sum([line.unit_price_gross_amount * 2 for line in order_lines_to_refund])+ mocked_refund.assert_called_once_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_multiple_order_line_refunds(+ mocked_refund, order_with_lines, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ payment = order_with_lines.get_last_payment()+ order_lines_to_refund = order_with_lines.lines.all()+ original_quantity = {+ line.id: line.quantity_unfulfilled for line in order_with_lines+ }+ order_line_ids = order_lines_to_refund.values_list("id", flat=True)+ order_lines_quantities_to_refund = [1 for _ in range(order_lines_to_refund.count())]+ lines_count = order_lines_to_refund.count()+ for _ in range(2):+ # call refund two times+ create_refund_fulfillment(+ requester=None,+ order=order_with_lines,+ payment=payment,+ order_lines_to_refund=order_lines_to_refund,+ order_lines_quantities_to_refund=order_lines_quantities_to_refund,+ fulfillment_lines_to_refund=[],+ fulfillment_lines_quantities_to_refund=[],+ )+ returned_fulfillemnt = Fulfillment.objects.get(+ order=order_with_lines, status=FulfillmentStatus.REFUNDED+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == lines_count+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids+ for line in order_lines_to_refund:+ assert line.quantity_unfulfilled == original_quantity.get(line.pk) - 2++ assert mocked_refund.call_count == 2+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_included_shipping_costs(+ mocked_refund, order_with_lines, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ order_with_lines.payments.add(payment_dummy)+ payment = order_with_lines.get_last_payment()+ order_lines_to_refund = order_with_lines.lines.all()+ original_quantity = {+ line.id: line.quantity_unfulfilled for line in order_with_lines+ }+ order_line_ids = order_lines_to_refund.values_list("id", flat=True)+ lines_count = order_with_lines.lines.count()+ order_lines_quantities_to_refund = [2 for _ in range(lines_count)]+ fulfillment_lines_to_refund = []+ fulfillment_lines_quantities_to_refund = []+ returned_fulfillemnt = create_refund_fulfillment(+ requester=None,+ order=order_with_lines,+ payment=payment,+ order_lines_to_refund=order_lines_to_refund,+ order_lines_quantities_to_refund=order_lines_quantities_to_refund,+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=fulfillment_lines_quantities_to_refund,+ refund_shipping_costs=True,+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == lines_count+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids+ for line in order_lines_to_refund:+ assert line.quantity_unfulfilled == original_quantity.get(line.pk) - 2+ amount = sum([line.unit_price_gross_amount * 2 for line in order_lines_to_refund])+ amount += order_with_lines.shipping_price_gross_amount+ mocked_refund.assert_called_once_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_only_fulfillment_lines(+ mocked_refund, fulfilled_order, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ fulfilled_order.payments.add(payment_dummy)+ payment = fulfilled_order.get_last_payment()+ order_line_ids = fulfilled_order.lines.all().values_list("id", flat=True)+ fulfillment_lines = FulfillmentLine.objects.filter(order_line_id__in=order_line_ids)+ original_quantity = {line.id: line.quantity for line in fulfillment_lines}+ fulfillment_lines_count = fulfillment_lines.count()+ fulfillment_lines_to_refund = fulfillment_lines+ fulfillment_lines_quantities_to_refund = [2 for _ in range(fulfillment_lines_count)]+ returned_fulfillemnt = create_refund_fulfillment(+ requester=None,+ order=fulfilled_order,+ payment=payment,+ order_lines_to_refund=[],+ order_lines_quantities_to_refund=[],+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=fulfillment_lines_quantities_to_refund,+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == len(order_line_ids)+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids++ for line in fulfillment_lines:+ assert line.quantity == original_quantity.get(line.pk) - 2+ amount = sum(+ [line.order_line.unit_price_gross_amount * 2 for line in fulfillment_lines]+ )+ mocked_refund.assert_called_once_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_multiple_fulfillment_lines_refunds(+ mocked_refund, fulfilled_order, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ fulfilled_order.payments.add(payment_dummy)+ payment = fulfilled_order.get_last_payment()+ order_line_ids = fulfilled_order.lines.all().values_list("id", flat=True)+ fulfillment_lines = FulfillmentLine.objects.filter(order_line_id__in=order_line_ids)+ original_quantity = {line.id: line.quantity for line in fulfillment_lines}+ fulfillment_lines_count = fulfillment_lines.count()+ fulfillment_lines_to_refund = fulfillment_lines+ fulfillment_lines_quantities_to_refund = [1 for _ in range(fulfillment_lines_count)]+ for _ in range(2):+ create_refund_fulfillment(+ requester=None,+ order=fulfilled_order,+ payment=payment,+ order_lines_to_refund=[],+ order_lines_quantities_to_refund=[],+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=(+ fulfillment_lines_quantities_to_refund+ ),+ )+ returned_fulfillemnt = Fulfillment.objects.get(+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == len(order_line_ids)+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids++ for line in fulfillment_lines:+ assert line.quantity == original_quantity.get(line.pk) - 2++ assert mocked_refund.call_count == 2+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_custom_amount(+ mocked_refund, fulfilled_order, payment_dummy+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ fulfilled_order.payments.add(payment_dummy)+ payment = fulfilled_order.get_last_payment()+ order_line_ids = fulfilled_order.lines.all().values_list("id", flat=True)+ fulfillment_lines = FulfillmentLine.objects.filter(order_line_id__in=order_line_ids)+ original_quantity = {line.id: line.quantity for line in fulfillment_lines}+ fulfillment_lines_count = fulfillment_lines.count()+ fulfillment_lines_to_refund = fulfillment_lines+ fulfillment_lines_quantities_to_refund = [2 for _ in range(fulfillment_lines_count)]+ amount = Decimal("10.00")+ returned_fulfillemnt = create_refund_fulfillment(+ requester=None,+ order=fulfilled_order,+ payment=payment,+ order_lines_to_refund=[],+ order_lines_quantities_to_refund=[],+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=fulfillment_lines_quantities_to_refund,+ amount=amount,+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == len(order_line_ids)+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids++ for line in fulfillment_lines:+ assert line.quantity == original_quantity.get(line.pk) - 2+ mocked_refund.assert_called_once_with(payment_dummy, amount)+++@patch("saleor.order.actions.gateway.refund")+def test_create_refund_fulfillment_multiple_refunds(+ mocked_refund, fulfilled_order, variant, payment_dummy, warehouse, channel_USD+):+ payment_dummy.captured_amount = payment_dummy.total+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED+ payment_dummy.save()+ fulfilled_order.payments.add(payment_dummy)+ payment = fulfilled_order.get_last_payment()++ stock = Stock.objects.create(+ warehouse=warehouse, product_variant=variant, quantity=5+ )+ net = variant.get_price(channel_USD.slug)+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)+ order_line = fulfilled_order.lines.create(+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ is_shipping_required=variant.is_shipping_required(),+ quantity=5,+ quantity_fulfilled=2,+ variant=variant,+ unit_price=TaxedMoney(net=net, gross=gross),+ tax_rate=23,+ )+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=order_line.quantity+ )+ fulfillment = fulfilled_order.fulfillments.get()+ fulfillment.lines.create(order_line=order_line, quantity=2, stock=stock)++ order_line_ids = fulfilled_order.lines.all().values_list("id", flat=True)+ fulfillment_lines = fulfillment.lines.all()+ original_fulfillment_quantity = {+ line.id: line.quantity for line in fulfillment_lines+ }++ fulfillment_lines_count = fulfillment_lines.count()+ fulfillment_lines_to_refund = fulfillment_lines+ fulfillment_lines_quantities_to_refund = [1 for _ in range(fulfillment_lines_count)]++ for _ in range(2):+ create_refund_fulfillment(+ requester=None,+ order=fulfilled_order,+ payment=payment,+ order_lines_to_refund=[order_line],+ order_lines_quantities_to_refund=[1],+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,+ fulfillment_lines_quantities_to_refund=(+ fulfillment_lines_quantities_to_refund+ ),+ )+ returned_fulfillemnt = Fulfillment.objects.get(+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED+ )+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()+ assert returned_fulfillemnt.status == FulfillmentStatus.REFUNDED+ assert len(returned_fulfillment_lines) == len(order_line_ids) + 1 # + order line+ for fulfillment_line in returned_fulfillment_lines:+ assert fulfillment_line.quantity == 2+ assert fulfillment_line.order_line_id in order_line_ids++ for line in fulfillment_lines:+ assert line.quantity == original_fulfillment_quantity.get(line.pk) - 2++ order_line.refresh_from_db()+ assert order_line.quantity_fulfilled == 4+ assert order_line.quantity_unfulfilled == 1+ assert mocked_refund.call_count == 2